1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use proc_macro2::TokenStream;
use quote::quote;
use syn::{
	punctuated::Punctuated, spanned::Spanned, Error, Expr, ExprLit, Lit, Meta, MetaNameValue,
	Result, Token, Variant,
};

fn deprecation_msg_formatter(msg: &str) -> String {
	format!(
		r#"{msg}
		help: the following are the possible correct uses
|
|     #[deprecated = "reason"]
|
|     #[deprecated(/*opt*/ since = "version", /*opt*/ note = "reason")]
|
|     #[deprecated]
|"#
	)
}

fn parse_deprecated_meta(crate_: &TokenStream, attr: &syn::Attribute) -> Result<TokenStream> {
	match &attr.meta {
		Meta::List(meta_list) => {
			let parsed = meta_list
				.parse_args_with(Punctuated::<MetaNameValue, Token![,]>::parse_terminated)
				.map_err(|e| Error::new(attr.span(), e.to_string()))?;
			let (note, since) = parsed.iter().try_fold((None, None), |mut acc, item| {
				let value = match &item.value {
					Expr::Lit(ExprLit { lit: lit @ Lit::Str(_), .. }) => Ok(lit),
					_ => Err(Error::new(
						attr.span(),
						deprecation_msg_formatter(
							"Invalid deprecation attribute: expected string literal",
						),
					)),
				}?;
				if item.path.is_ident("note") {
					acc.0.replace(value);
				} else if item.path.is_ident("since") {
					acc.1.replace(value);
				}
				Ok::<(Option<&syn::Lit>, Option<&syn::Lit>), Error>(acc)
			})?;
			note.map_or_else(
		  || Err(Error::new(attr.span(), deprecation_msg_formatter("Invalid deprecation attribute: missing `note`"))),
				|note| {
					let since = if let Some(str) = since {
						quote! { Some(#str) }
					} else {
						quote! { None }
					};
					let doc = quote! { #crate_::__private::metadata_ir::DeprecationStatusIR::Deprecated { note: #note, since: #since }};
					Ok(doc)
				},
			)
		},
		Meta::NameValue(MetaNameValue {
			value: Expr::Lit(ExprLit { lit: lit @ Lit::Str(_), .. }),
			..
		}) => {
			// #[deprecated = "lit"]
			let doc = quote! { #crate_::__private::metadata_ir::DeprecationStatusIR::Deprecated { note: #lit, since: None } };
			Ok(doc)
		},
		Meta::Path(_) => {
			// #[deprecated]
			Ok(
				quote! { #crate_::__private::metadata_ir::DeprecationStatusIR::DeprecatedWithoutNote },
			)
		},
		_ => Err(Error::new(
			attr.span(),
			deprecation_msg_formatter("Invalid deprecation attribute: expected string literal"),
		)),
	}
}

/// collects deprecation attribute if its present.
pub fn get_deprecation(path: &TokenStream, attrs: &[syn::Attribute]) -> Result<TokenStream> {
	parse_deprecation(path, attrs).map(|item| {
		item.unwrap_or_else(|| {
			quote! {#path::__private::metadata_ir::DeprecationStatusIR::NotDeprecated}
		})
	})
}

fn parse_deprecation(path: &TokenStream, attrs: &[syn::Attribute]) -> Result<Option<TokenStream>> {
	attrs
		.iter()
		.find(|a| a.path().is_ident("deprecated"))
		.map(|a| parse_deprecated_meta(path, a))
		.transpose()
}

/// collects deprecation attribute if its present for enum-like types
pub fn get_deprecation_enum<'a>(
	path: &TokenStream,
	parent_attrs: &[syn::Attribute],
	children_attrs: impl Iterator<Item = (u8, &'a [syn::Attribute])>,
) -> Result<TokenStream> {
	let parent_deprecation = parse_deprecation(path, parent_attrs)?;

	let children = children_attrs
		.filter_map(|(key, attributes)| {
			let key = quote::quote! { #path::__private::codec::Compact(#key as u8) };
			let deprecation_status = parse_deprecation(path, attributes).transpose();
			deprecation_status.map(|item| item.map(|item| quote::quote! { (#key, #item) }))
		})
		.collect::<Result<Vec<TokenStream>>>()?;
	match (parent_deprecation, children.as_slice()) {
		(None, []) =>
			Ok(quote::quote! { #path::__private::metadata_ir::DeprecationInfoIR::NotDeprecated }),
		(None, _) => {
			let children = quote::quote! { #path::__private::scale_info::prelude::collections::BTreeMap::from([#( #children),*]) };
			Ok(
				quote::quote! { #path::__private::metadata_ir::DeprecationInfoIR::VariantsDeprecated(#children) },
			)
		},
		(Some(depr), _) => Ok(
			quote::quote! { #path::__private::metadata_ir::DeprecationInfoIR::ItemDeprecated(#depr) },
		),
	}
}

/// Gets the index for the variant inside `Error` or `Event` declaration.
/// priority is as follows:
/// Manual `#[codec(index = N)]`
/// Explicit discriminant `Variant = N`
/// Variant's definition index
pub fn variant_index_for_deprecation(index: u8, item: &Variant) -> u8 {
	let index: u8 =
		if let Some((_, Expr::Lit(ExprLit { lit: Lit::Int(num_lit), .. }))) = &item.discriminant {
			num_lit.base10_parse::<u8>().unwrap_or(index as u8)
		} else {
			index as u8
		};

	item.attrs
		.iter()
		.find(|attr| attr.path().is_ident("codec"))
		.and_then(|attr| {
			if let Meta::List(meta_list) = &attr.meta {
				meta_list
					.parse_args_with(Punctuated::<MetaNameValue, syn::Token![,]>::parse_terminated)
					.ok()
			} else {
				None
			}
		})
		.and_then(|parsed| {
			parsed.iter().fold(None, |mut acc, item| {
				if let Expr::Lit(ExprLit { lit: Lit::Int(num_lit), .. }) = &item.value {
					num_lit.base10_parse::<u8>().iter().for_each(|val| {
						if item.path.is_ident("index") {
							acc.replace(*val);
						}
					})
				};
				acc
			})
		})
		.unwrap_or(index)
}