-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathutil.rs
More file actions
231 lines (207 loc) · 6.95 KB
/
Copy pathutil.rs
File metadata and controls
231 lines (207 loc) · 6.95 KB
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use std::{collections::BTreeMap, path::Path};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use stellar_xdr::curr as xdr;
use syn::{File, ItemTrait, TraitItemFn};
/// Read a crate starting from a single file then parse into a file
pub fn parse_crate_as_file(path: &Path) -> Option<File> {
syn_file_expand::read_crate(path)
.map_err(|e| {
println!("{e}");
e
})
.ok()
.map(|file| file.to_token_stream().to_string())
.and_then(|file| syn::parse_file(&file).ok())
}
pub fn has_macro(attrs: &[syn::Attribute], macro_name: &str) -> bool {
for attr in attrs {
if format!("{:#?}", attr.path()).contains(macro_name) {
return true;
}
}
false
}
use syn::visit::Visit;
pub type Traits = BTreeMap<String, Vec<TokenStream>>;
#[derive(Default)]
pub struct TraitVisitor {
pub traits: Traits,
}
impl TraitVisitor {
pub fn find_traits_in_file(ast: &syn::File) -> Traits {
let mut visitor = TraitVisitor::default();
syn::visit::visit_file(&mut visitor, ast);
visitor.traits
}
}
impl<'ast> Visit<'ast> for TraitVisitor {
fn visit_item_trait(&mut self, item: &'ast syn::ItemTrait) {
if has_macro(&item.attrs, "subcontract") {
self.traits
.insert(item.ident.to_string(), generate_methods(item));
}
}
}
fn generate_methods(item: &ItemTrait) -> Vec<TokenStream> {
item.items
.iter()
.filter_map(|item| {
if let syn::TraitItem::Fn(TraitItemFn { sig, attrs, .. }) = item {
let name = &sig.ident;
Some(generate_method(sig, attrs, name, sig.receiver().is_none()))
} else {
None
}
})
.collect::<Vec<_>>()
}
fn generate_method(
sig: &syn::Signature,
attrs: &[syn::Attribute],
name: &syn::Ident,
is_static: bool,
) -> TokenStream {
let output = &sig.output;
let inputs = sig.inputs.iter().skip(usize::from(!is_static));
let args = crate::subcontract::args_to_idents(&sig.inputs, is_static);
quote! {
#(#attrs)*
pub fn #name(env: loam_sdk::soroban_sdk::Env, #(#inputs),*) #output {
loam_sdk::soroban_sdk::set_env(env);
Contract::#name(#(#args),*)
}
}
}
pub const LOCAL: &str = "Standalone Network ; February 2017";
pub const TESTNET: &str = "Test SDF Network ; September 2015";
pub const FUTURENET: &str = "Test SDF Future Network ; October 2022";
pub const MAINNET: &str = "Public Global Stellar Network ; September 2015";
///
/// Match network names to passphrases
///
///
pub fn network_passphrase(s: &str) -> &'static str {
match s.to_lowercase().as_str() {
"local" => LOCAL,
"testnet" => TESTNET,
"future" => FUTURENET,
"main" => MAINNET,
_ => "",
}
}
pub fn generate_asset_id(
asset: &str,
network: &str,
) -> Result<stellar_strkey::Contract, xdr::Error> {
use sha2::{Digest, Sha256};
use xdr::WriteXdr;
let asset = parse_asset(asset).unwrap();
let network_passphrase = network_passphrase(network);
let network_id = xdr::Hash(Sha256::digest(network_passphrase.as_bytes()).into());
let preimage = xdr::HashIdPreimage::ContractId(xdr::HashIdPreimageContractId {
network_id,
contract_id_preimage: xdr::ContractIdPreimage::Asset(asset.clone()),
});
let preimage_xdr = preimage.to_xdr(xdr::Limits::none())?;
Ok(stellar_strkey::Contract(
Sha256::digest(preimage_xdr).into(),
))
}
pub fn parse_asset(str: &str) -> Result<xdr::Asset, xdr::Error> {
if str == "native" {
return Ok(xdr::Asset::Native);
}
let split: Vec<&str> = str.splitn(2, ':').collect();
assert!(split.len() == 2, "invalid asset \"{str}\"");
let code = split[0];
let issuer: xdr::AccountId = split[1].parse()?;
let re = regex::Regex::new("^[[:alnum:]]{1,12}$").expect("regex failed");
assert!(re.is_match(code), "invalid asset \"{str}\"");
let asset_code: xdr::AssetCode = code.parse()?;
Ok(match asset_code {
xdr::AssetCode::CreditAlphanum4(asset_code) => {
xdr::Asset::CreditAlphanum4(xdr::AlphaNum4 { asset_code, issuer })
}
xdr::AssetCode::CreditAlphanum12(asset_code) => {
xdr::Asset::CreditAlphanum12(xdr::AlphaNum12 { asset_code, issuer })
}
})
}
// Generate the code to read the STELLAR_NETWORK environment variable
// and call the generate_asset_id function
pub fn parse_asset_literal(lit_str: &syn::LitStr, network: &str) -> TokenStream {
let asset_code = lit_str.value();
let asset_id = generate_asset_id(&asset_code, network).unwrap();
let asset_id = stellar_strkey::Contract(asset_id.0).to_string();
quote! {
loam_sdk::soroban_sdk::token::Client::new(
loam_sdk::soroban_sdk::env(),
&loam_sdk::soroban_sdk::Address::from_string(
&loam_sdk::soroban_sdk::String::from_str(loam_sdk::soroban_sdk::env(), #asset_id,)
)
)
}
}
#[allow(unused)]
pub(crate) fn equal_tokens(expected: &TokenStream, actual: &TokenStream) {
assert_eq!(
format_snippet(&expected.to_string()),
format_snippet(&actual.to_string())
);
}
pub(crate) fn p_e(e: std::io::Error) -> std::io::Error {
eprintln!("{e:#?}");
e
}
use std::io::{Read, Write};
/// Format the given snippet. The snippet is expected to be *complete* code.
/// When we cannot parse the given snippet, this function returns `None`.
#[allow(unused)]
pub(crate) fn format_snippet(snippet: &str) -> String {
let mut child = std::process::Command::new("rustfmt")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.as_mut()
.unwrap()
.write_all(snippet.as_bytes())
.map_err(p_e)
.unwrap();
child.wait().unwrap();
let mut buf = String::new();
child.stdout.unwrap().read_to_string(&mut buf).unwrap();
println!("\n\n\n{buf}\n\n\n");
buf
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_generate_asset_id() {
let asset_id = generate_asset_id("native", "local").unwrap();
assert_eq!(
asset_id.to_string(),
"CDMLFMKMMD7MWZP3FKUBZPVHTUEDLSX4BYGYKH4GCESXYHS3IHQ4EIG4"
);
}
#[test]
fn test_generate_asset_id_code() {
let asset_id = parse_asset_literal(
&syn::LitStr::new("native", proc_macro2::Span::call_site()),
"local",
);
equal_tokens(
&asset_id,
"e! {
loam_sdk::soroban_sdk::token::Client::new(loam_sdk::soroban_sdk::env(),
&loam_sdk::soroban_sdk::Address::from_string(
&loam_sdk::soroban_sdk::String::from_str( loam_sdk::soroban_sdk::env(), "CDMLFMKMMD7MWZP3FKUBZPVHTUEDLSX4BYGYKH4GCESXYHS3IHQ4EIG4"))
)
},
);
}
}