From nobody Tue Dec 24 12:26:40 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1734705122; cv=none; d=zohomail.com; s=zohoarc; b=GgdrGcuOvLhHSZ7rS2JHF+lC/BEOlQZek5C2EL08iFJonTtc3wL4FRDAE7aCg33dT0wL6VFO9irtS4/0j1Neih87D00+CPLFcfSRhrML1IPGf0s+slTVqbJkF/sYeT1iZDfcpyD0NvUaIKaCeWYXvJM+lxHbP2otOMBS9l2d5kw= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1734705122; h=Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=5CE9shW3ftWbl1V1SBQeRNzap/cYi489BVwR842VWpQ=; b=BuUsdcU453uc1/xsEdT5E8HsQ5vRWt4ThLlrV/PYKN52E+P27FEICABxqiUNGWXzarfYVvVfVN8mNpPOEl80RNsMyBaSA9r+rOPOTmmuwtTwo9qdFXobdMbPFldoEMs79wSCZmSzvFPd3ZGHo7Y/4yFQjVlec1w5O2E7gmNww5s= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1734705122953479.939908111318; Fri, 20 Dec 2024 06:32:02 -0800 (PST) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tOe1W-0004UJ-5C; Fri, 20 Dec 2024 09:30:38 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOe1P-0004Sm-Bu for qemu-devel@nongnu.org; Fri, 20 Dec 2024 09:30:32 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOe1N-0006be-F4 for qemu-devel@nongnu.org; Fri, 20 Dec 2024 09:30:30 -0500 Received: from mail-wm1-f72.google.com (mail-wm1-f72.google.com [209.85.128.72]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-31-YID_4nulNQywaQzAs_U7sw-1; Fri, 20 Dec 2024 09:30:26 -0500 Received: by mail-wm1-f72.google.com with SMTP id 5b1f17b1804b1-4361d4e8359so17082095e9.3 for ; Fri, 20 Dec 2024 06:30:26 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-43661289995sm46912885e9.36.2024.12.20.06.30.22 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 20 Dec 2024 06:30:22 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1734705027; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=5CE9shW3ftWbl1V1SBQeRNzap/cYi489BVwR842VWpQ=; b=gH4r/2Fap2gBjHsSbLvfpTYC0/SGMBTRL5K+Pd+9xByr13Hit3MnRuNVBrnpU1hH9lt4SK AwIubgbAIWvEXtV/e+cjcftxVV8z20mRHo7JkPpej7KZpy7ZAmAZxkhhX5fkiwkauCLz6J ZgO36t9NgG9pfZq9IvtaNxa9AJ2xpmA= X-MC-Unique: YID_4nulNQywaQzAs_U7sw-1 X-Mimecast-MFC-AGG-ID: YID_4nulNQywaQzAs_U7sw X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1734705025; x=1735309825; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=5CE9shW3ftWbl1V1SBQeRNzap/cYi489BVwR842VWpQ=; b=bBf8Ke4V8t0u7Wb6NR3eDFTkYXmqSeaSNB7/rNwN3a66U6oF2V/bGuDZPfQ0+y2K79 3R8yrRynjOea5MDjT78Lt/CIXaPxmKZFRbp135zRTy+EXoYaYJNuFfY4aJvJo2PSog+r tdpXYMvGQbbcX5yGBWh+pifSZ3r/kYRonid9ICgq1e1pa23y3y7LrA1wFUzahzkfrRVe 9uhPLU00wgiJYmFukkxrgJ5iXVcI3Ack9iSreiCh55SYhGpTc/2zKmYAC7XcvcvytGvi 2z4necaUiuuKewMwJOoWIOTFq8wjmupjcIP0EnBWSRgqebZYZeoqdqqOqNes4Mpd8n11 DZ3w== X-Gm-Message-State: AOJu0YzJyew+UyQsDXtChZfym/cMElRJ/7qAjXKisjwFvEUqQiZumov3 Jgt0+Y93l+AaR0KZjA8HEF7+fmQoPHLxC3KOYkIQCeLYqDNxcoKv/JTI19UBw/3YEHp0Ehx3A4P 91YMrYgFa2vsAqgQBGJsKk8iblcZalCzSHmd6fDaXhPb6UfdgxZj2d7N6i9xExMrJGE2PQ/sGmK NifGqiFjaBsXdi1AV0kwe7umLWmP4JqDmPPw68 X-Gm-Gg: ASbGnctDBICZ5OQlxBln7PBs92CLTJhgfaVbUBbPpyrLwGtY8bRieO2I6e3Itx1oLm1 C5tNXs4LdirckxnFmrlNj0Om75eqqUp1ba4VFcV/EVyRaCY+XJZszatn/q7HNNEsg0P1LE1N7bo I5BmHR+fxmzca4W4MheR6GKmnHWaRRGl3mcsKC5/9YUyTSxvXRrCkBUr540Xvx9p+/RzyqvM2ZZ db1mkRtDviWOIGDVR0xW1oIXP7kXE9DgZK4Ygn8vIYVFpZ+a2GriyhFI7tm X-Received: by 2002:a05:600c:3b9a:b0:42c:bb10:7292 with SMTP id 5b1f17b1804b1-436685470f8mr21997485e9.1.1734705024572; Fri, 20 Dec 2024 06:30:24 -0800 (PST) X-Google-Smtp-Source: AGHT+IETpWXaWaw9US5iVVn857lDgNrX33bWnLjJZuYEEXU6N/4z+3xZlssf+uLvsNzyHsfsNXkd8w== X-Received: by 2002:a05:600c:3b9a:b0:42c:bb10:7292 with SMTP id 5b1f17b1804b1-436685470f8mr21997215e9.1.1734705024070; Fri, 20 Dec 2024 06:30:24 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: zhao1.liu@intel.com, junjie.mao@hotmail.com Subject: [PATCH 11/12] rust: qemu-api-macros: add automatic TryFrom/TryInto derivation Date: Fri, 20 Dec 2024 15:29:53 +0100 Message-ID: <20241220142955.652636-12-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241220142955.652636-1-pbonzini@redhat.com> References: <20241220142955.652636-1-pbonzini@redhat.com> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -31 X-Spam_score: -3.2 X-Spam_bar: --- X-Spam_report: (-3.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-1.129, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, RCVD_IN_VALIDITY_SAFE_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1734705124960116600 Content-Type: text/plain; charset="utf-8" This is going to be fairly common. Using a custom procedural macro provides better error messages and automatically finds the right type. Note that this is different from the same-named macro in the derive_more crate. That one provides conversion from e.g. tuples to enums with tuple variants, not from integers to enums. Signed-off-by: Paolo Bonzini --- rust/hw/char/pl011/src/lib.rs | 28 +------------ rust/qemu-api-macros/src/lib.rs | 74 ++++++++++++++++++++++++++++++++- 2 files changed, 73 insertions(+), 29 deletions(-) diff --git a/rust/hw/char/pl011/src/lib.rs b/rust/hw/char/pl011/src/lib.rs index 69064d6929b..0a89d393e0f 100644 --- a/rust/hw/char/pl011/src/lib.rs +++ b/rust/hw/char/pl011/src/lib.rs @@ -45,7 +45,7 @@ #[doc(alias =3D "offset")] #[allow(non_camel_case_types)] #[repr(u64)] -#[derive(Debug)] +#[derive(Debug, qemu_api_macros::TryInto)] pub enum RegisterOffset { /// Data Register /// @@ -102,32 +102,6 @@ pub enum RegisterOffset { //Reserved =3D 0x04C, } =20 -impl core::convert::TryFrom for RegisterOffset { - type Error =3D u64; - - fn try_from(value: u64) -> Result { - macro_rules! case { - ($($discriminant:ident),*$(,)*) =3D> { - /* check that matching on all macro arguments compiles, wh= ich means we are not - * missing any enum value; if the type definition ever cha= nges this will stop - * compiling. - */ - const fn _assert_exhaustive(val: RegisterOffset) { - match val { - $(RegisterOffset::$discriminant =3D> (),)* - } - } - - match value { - $(x if x =3D=3D Self::$discriminant as u64 =3D> Ok(Sel= f::$discriminant),)* - _ =3D> Err(value), - } - } - } - case! { DR, RSR, FR, FBRD, ILPR, IBRD, LCR_H, CR, FLS, IMSC, RIS, = MIS, ICR, DMACR } - } -} - pub mod registers { //! Device registers exposed as typed structs which are backed by arbi= trary //! integer bitmaps. [`Data`], [`Control`], [`LineControl`], etc. diff --git a/rust/qemu-api-macros/src/lib.rs b/rust/qemu-api-macros/src/lib= .rs index 539c48df298..7ec218202f4 100644 --- a/rust/qemu-api-macros/src/lib.rs +++ b/rust/qemu-api-macros/src/lib.rs @@ -5,8 +5,8 @@ use proc_macro::TokenStream; use quote::quote; use syn::{ - parse_macro_input, parse_quote, punctuated::Punctuated, token::Comma, = Data, DeriveInput, Field, - Fields, Ident, Type, Visibility, + parse_macro_input, parse_quote, punctuated::Punctuated, spanned::Spann= ed, token::Comma, Data, + DeriveInput, Field, Fields, Ident, Meta, Path, Token, Type, Variant, V= isibility, }; =20 mod utils; @@ -98,3 +98,73 @@ pub fn derive_offsets(input: TokenStream) -> TokenStream= { =20 TokenStream::from(expanded) } + +#[allow(non_snake_case)] +fn get_repr_uN(input: &DeriveInput, msg: &str) -> Result= { + let repr =3D input.attrs.iter().find(|attr| attr.path().is_ident("repr= ")); + if let Some(repr) =3D repr { + let nested =3D repr.parse_args_with(Punctuated:::= :parse_terminated)?; + for meta in nested { + match meta { + Meta::Path(path) if path.is_ident("u8") =3D> return Ok(pat= h), + Meta::Path(path) if path.is_ident("u16") =3D> return Ok(pa= th), + Meta::Path(path) if path.is_ident("u32") =3D> return Ok(pa= th), + Meta::Path(path) if path.is_ident("u64") =3D> return Ok(pa= th), + _ =3D> {} + } + } + } + + Err(MacroError::Message( + format!("#[repr(u8/u16/u32/u64) required for {}", msg), + input.ident.span(), + )) +} + +fn get_variants(input: &DeriveInput) -> Result<&Punctuated= , MacroError> { + if let Data::Enum(e) =3D &input.data { + if let Some(v) =3D e.variants.iter().find(|v| v.fields !=3D Fields= ::Unit) { + return Err(MacroError::Message( + "Cannot derive TryInto for enum with non-unit variants.".t= o_string(), + v.fields.span(), + )); + } + Ok(&e.variants) + } else { + Err(MacroError::Message( + "Cannot derive TryInto for union or struct.".to_string(), + input.ident.span(), + )) + } +} + +#[rustfmt::skip::macros(quote)] +fn derive_tryinto_or_error(input: DeriveInput) -> Result { + let repr =3D get_repr_uN(&input, "#[derive(TryInto)]")?; + + let name =3D &input.ident; + let variants =3D get_variants(&input)?; + let discriminants: Vec<&Ident> =3D variants.iter().map(|f| &f.ident).c= ollect(); + + Ok(quote! { + impl core::convert::TryFrom<#repr> for #name { + type Error =3D #repr; + + fn try_from(value: #repr) -> Result { + #(const #discriminants: #repr =3D #name::#discriminants as= #repr;)*; + match value { + #(#discriminants =3D> Ok(Self::#discriminants),)* + _ =3D> Err(value), + } + } + } + }) +} + +#[proc_macro_derive(TryInto)] +pub fn derive_tryinto(input: TokenStream) -> TokenStream { + let input =3D parse_macro_input!(input as DeriveInput); + let expanded =3D derive_tryinto_or_error(input).unwrap_or_else(Into::i= nto); + + TokenStream::from(expanded) +} --=20 2.47.1