Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
kurtbuilds committed Sep 16, 2024
1 parent 2a8a29e commit 56cb5a8
Show file tree
Hide file tree
Showing 9 changed files with 47 additions and 60 deletions.
36 changes: 13 additions & 23 deletions codegen_rust/src/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,15 @@ use crate::write_rust;
use anyhow::Result;
use hir::{Config, HirSpec, Language, Operation};
use libninja_macro::rfunction;
use mir::{File, Function, Import, Item};
use mir::{import, File, Function, Item};
use mir_rust::{to_rust_example_value, ToRustCode, ToRustIdent};
use proc_macro2::TokenStream;
use quote::quote;
use std::collections::HashSet;
use std::fs;
use std::path::PathBuf;

pub fn write_examples_folder(
spec: &HirSpec,
config: &Config,
modified: &mut HashSet<PathBuf>,
) -> Result<()> {
pub fn write_examples_folder(spec: &HirSpec, config: &Config, modified: &mut HashSet<PathBuf>) -> Result<()> {
let path = config.dest.join("examples");
fs::create_dir_all(&path)?;
for operation in &spec.operations {
Expand All @@ -25,11 +21,7 @@ pub fn write_examples_folder(
Ok(())
}

pub fn generate_example(
operation: &Operation,
opt: &Config,
spec: &HirSpec,
) -> Result<File<TokenStream>> {
pub fn generate_example(operation: &Operation, cfg: &Config, spec: &HirSpec) -> Result<File<TokenStream>> {
let args = operation.function_args(Language::Rust);
let declarations = args
.iter()
Expand All @@ -42,7 +34,7 @@ pub fn generate_example(
})
.collect::<Result<Vec<_>>>()?;
let fn_args = args.iter().map(|p| p.name.to_rust_ident());
let optionals = operation
let optionals: Vec<TokenStream> = operation
.optional_args()
.into_iter()
.map(|p| {
Expand All @@ -52,19 +44,17 @@ pub fn generate_example(
.#ident(#value)
})
})
.collect::<anyhow::Result<Vec<_>, anyhow::Error>>()?;
let qualified_client = format!("{}::{}", opt.name, opt.client_name());
.collect::<Result<Vec<_>>>()?;
let mut imports = vec![
Import::package(&qualified_client),
Import::package("crate::model::*"),
import!(format!("{}::model::*", cfg.package_name())),
import!(cfg.package_name(), cfg.client_name()),
];
let struct_name = operation
.required_struct_name()
.to_rust_struct()
.to_string();
imports.push(Import::package(format!("crate::request::{}", struct_name)));
if operation.use_required_struct(Language::Rust) {
let struct_name = operation.required_struct_name();
imports.push(import!(format!("{}::request", cfg.package_name()), struct_name));
}
let operation = operation.name.to_rust_ident();
let client = opt.client_name();
let client = cfg.client_name();
let mut main: Function<TokenStream> = rfunction!(async main() {
let client = #client::from_env();
#(#declarations)*
Expand All @@ -77,7 +67,7 @@ pub fn generate_example(
main.attributes.push(quote!(#[tokio::main]));

Ok(File {
attributes: vec![quote! {allow(unused_imports)}],
attributes: vec![quote! {#![allow(unused_imports)]}],
imports,
items: vec![Item::Fn(main)],
..File::default()
Expand Down
4 changes: 4 additions & 0 deletions hir/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ impl Config {
format!("{}Auth", self.name)
}

pub fn package_name(&self) -> String {
self.name.to_case(Case::Snake)
}

pub fn env_var(&self, name: &str) -> Literal<String> {
Literal(format!(
"{}_{}",
Expand Down
11 changes: 2 additions & 9 deletions hir/src/operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ impl Operation {
self.parameters.iter().filter(|p| !p.optional).collect()
}

pub fn parameters_by_header_query_body(
&self,
) -> (Vec<&Parameter>, Vec<&Parameter>, Vec<&Parameter>) {
pub fn parameters_by_header_query_body(&self) -> (Vec<&Parameter>, Vec<&Parameter>, Vec<&Parameter>) {
let mut header = Vec::new();
let mut query = Vec::new();
let mut body = Vec::new();
Expand Down Expand Up @@ -89,12 +87,7 @@ impl Operation {
example: None,
}]
}
_ => self
.parameters
.iter()
.filter(|p| !p.optional)
.cloned()
.collect(),
_ => self.parameters.iter().filter(|p| !p.optional).cloned().collect(),
}
}

Expand Down
5 changes: 3 additions & 2 deletions libninja/tests/basic/link_create_token.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use plaid::PlaidClient;
#![allow(unused_imports)]
use plaid::model::*;
use plaid::PlaidClient;
#[tokio::main]
async fn main() {
let client = PlaidClient::from_env();
Expand All @@ -17,4 +18,4 @@ async fn main() {
.await
.unwrap();
println!("{:#?}", response);
}
}
18 changes: 6 additions & 12 deletions mir/src/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,19 @@ pub struct Import {
}

impl Import {
pub fn package(path: impl AsRef<str>) -> Self {
pub fn package(path: impl Into<String>) -> Self {
Self {
path: path.as_ref().to_string(),
path: path.into(),
imports: vec![],
alias: None,
vis: Visibility::Private,
feature: None,
}
}

pub fn new(path: &str, imports: impl IntoIterator<Item = impl Into<ImportItem>>) -> Self {
pub fn new(path: impl Into<String>, imports: impl IntoIterator<Item = impl Into<ImportItem>>) -> Self {
Self {
path: path.to_string(),
path: path.into(),
imports: imports.into_iter().map(|s| s.into()).collect(),
alias: None,
vis: Visibility::Private,
Expand Down Expand Up @@ -88,10 +88,7 @@ impl From<&String> for ImportItem {

impl From<String> for ImportItem {
fn from(s: String) -> Self {
let r = Self {
name: s,
alias: None,
};
let r = Self { name: s, alias: None };
r.validate().unwrap();
r
}
Expand All @@ -110,9 +107,6 @@ impl From<&str> for ImportItem {

impl From<Ident> for ImportItem {
fn from(s: Ident) -> Self {
Self {
name: s.0,
alias: None,
}
Self { name: s.0, alias: None }
}
}
6 changes: 6 additions & 0 deletions mir/src/macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ macro_rules! import {
(pub $path:path, $($imports:ident),*) => {
::mir::Import::new(stringify!($path), vec![$(stringify!($imports)),*]).public()
};
($c:expr, $($imports:expr),*) => {
::mir::Import::new($c, vec![$($imports),*])
};
($c:expr) => {
::mir::Import::package($c)
};
}
/// Macro to create a FnArg. Called targ because the type is a TokenStream (specifically a path), rather than a &str.
/// targ!(access_token: String)
Expand Down
2 changes: 1 addition & 1 deletion mir_rust/src/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ impl ToRustCode for File<TokenStream> {
let doc = doc.to_rust_code();
let items = items.into_iter().map(|f| f.to_rust_code());
quote! {
#(#![ #annotations ])*
#(#annotations)*
#doc
#(#imports)*
#(#items)*
Expand Down
2 changes: 1 addition & 1 deletion mir_rust/src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ impl ToRustCode for Function<TokenStream> {
let args = args.into_iter().map(|a| a.to_rust_code());
let ret = (!ret.is_empty()).to_value(|| quote!( -> #ret));
quote! {
#(#[ #annotations ])*
#(#annotations)*
#doc
#vis #async_ fn #name(#(#args),*) #ret {
#body
Expand Down
23 changes: 11 additions & 12 deletions mir_rust/src/import.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use mir::{Import, ImportItem};
use crate::ToRustCode;
use proc_macro2::{TokenStream, Span};
use syn::Path;
use mir::{Import, ImportItem};
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::Path;

impl ToRustCode for Import {
fn to_rust_code(mut self) -> TokenStream {
Expand Down Expand Up @@ -30,10 +30,12 @@ impl ToRustCode for Import {
quote! { #vis use #path; }
}
}
let feature = std::mem::take(&mut self.feature).map(|f| {
let f = syn::Ident::new(&f, Span::call_site());
quote!(#[cfg(feature = #f)])
}).unwrap_or_default();
let feature = std::mem::take(&mut self.feature)
.map(|f| {
let f = syn::Ident::new(&f, Span::call_site());
quote!(#[cfg(feature = #f)])
})
.unwrap_or_default();
let import = inner(self);
quote!(#feature #import)
}
Expand All @@ -43,16 +45,13 @@ impl ToRustCode for ImportItem {
fn to_rust_code(self) -> TokenStream {
if let Some(alias) = self.alias {
let alias = syn::Ident::new(&alias, Span::call_site());
let path = syn::parse_str::<syn::Path>(&self.name).unwrap();
let path = syn::parse_str::<Path>(&self.name).unwrap();
quote! { #path as #alias }
} else if &self.name == "*" {
quote! { * }
} else {
let path = syn::parse_str::<syn::Path>(&self.name).unwrap();
let path = syn::parse_str::<Path>(&self.name).unwrap();
quote! { #path }
}
}
}



0 comments on commit 56cb5a8

Please sign in to comment.