Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check all rust keywords, deal with recursive structs #15

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions libninja/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ indexmap = "2.0"
ln-macro = { path = "../macro" }
ln-core = { path = "../core" }
ln-mir = { path = "../mir" }
check_keyword = "0.2.0"

[dev-dependencies]
env_logger = "0.10.0"
Expand Down
61 changes: 42 additions & 19 deletions libninja/src/rust/codegen.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use anyhow::Result;
use check_keyword::CheckKeyword;
use convert_case::{Case, Casing};
use openapiv3::{ArrayType, OpenAPI, Schema, SchemaKind};
use proc_macro2::{Span, TokenStream, TokenTree};
use quote::{quote, TokenStreamExt};
use regex::{Captures, Regex};
use syn::Path;

use std::collections::HashSet;
use ln_mir::{ArgIdent, Class, Doc, Field, File, Function, Ident, Import, ImportItem, Literal, Visibility};
pub use typ::*;
pub use example::*;
Expand Down Expand Up @@ -104,7 +105,6 @@ fn codegen_function(func: Function<TokenStream>, self_arg: TokenStream) -> Token
}
}


impl ToRustCode for Class<TokenStream> {
fn to_rust_code(self) -> TokenStream {
let is_pub = pub_tok(self.public);
Expand Down Expand Up @@ -251,7 +251,24 @@ impl ToRustCode for Option<Doc> {
}
}

pub fn to_rust_example_value(ty: &Ty, name: &Name, spec: &MirSpec, use_ref_value: bool) -> Result<TokenStream> {


pub fn to_rust_example_value(
ty: &Ty,
name: &Name,
spec: &MirSpec,
use_ref_value: bool,
) -> Result<TokenStream> {
_to_rust_example_value(ty, name, spec, use_ref_value, &mut HashSet::new())
}

fn _to_rust_example_value(
ty: &Ty,
name: &Name,
spec: &MirSpec,
use_ref_value: bool,
seen: &mut HashSet<Name>,
) -> Result<TokenStream> {
let s = match ty {
Ty::String => {
let s = format!("your {}", name.0.to_case(Case::Lower));
Expand All @@ -270,7 +287,9 @@ pub fn to_rust_example_value(ty: &Ty, name: &Name, spec: &MirSpec, use_ref_value
} else {
use_ref_value
};
let inner = to_rust_example_value(inner, name, spec, use_ref_value)?;

let inner = _to_rust_example_value(inner, name, spec, use_ref_value, seen)?;

if use_ref_value {
quote!(&[#inner])
} else {
Expand All @@ -282,20 +301,28 @@ pub fn to_rust_example_value(ty: &Ty, name: &Name, spec: &MirSpec, use_ref_value
let force_not_ref = model.0.ends_with("Required");
match record {
Record::Struct(Struct { name: _name, fields, nullable }) => {
seen.insert(name.clone());

let fields = fields.iter().map(|(name, field)| {
let mut value = to_rust_example_value(&field.ty, name, spec, force_not_ref)?;
let name = name.to_rust_ident();
if field.optional {
value = quote!(Some(#value));
}
Ok(quote!(#name: #value))
}).collect::<Result<Vec<_>, anyhow::Error>>()?;
let name_ident = name.to_rust_ident();
if seen.contains(name) && field.optional {
Ok(quote!(#name_ident: None))
} else {
let mut value = _to_rust_example_value(&field.ty, name, spec, force_not_ref, seen)?;
if field.optional {
value = quote!(Some(#value));
}
Ok(quote!(#name_ident: #value))
}
})
.collect::<Result<Vec<_>, anyhow::Error>>()?;
let model = model.to_rust_struct();
seen.remove(name);
quote!(#model{#(#fields),*})
}
Record::NewType(NewType { name, fields }) => {
let fields = fields.iter().map(|f| {
to_rust_example_value(&f.ty, name, spec, force_not_ref)
_to_rust_example_value(&f.ty, name, spec, force_not_ref, seen)
}).collect::<Result<Vec<_>, _>>()?;
let name = name.to_rust_struct();
quote!(#name(#(#fields),*))
Expand All @@ -307,7 +334,7 @@ pub fn to_rust_example_value(ty: &Ty, name: &Name, spec: &MirSpec, use_ref_value
quote!(#model::#variant)
}
Record::TypeAlias(name, hir::MirField { ty, optional, .. }) => {
let ty = to_rust_example_value(ty, name, spec, force_not_ref)?;
let ty = _to_rust_example_value(ty, name, spec, force_not_ref, seen)?;
if *optional {
quote!(Some(#ty))
} else {
Expand Down Expand Up @@ -387,7 +414,7 @@ fn sanitize(s: &str) -> String {
c
})
.into();
if is_restricted(&s) {
if s.is_keyword() {
s += "_"
}
if s.chars().next().unwrap().is_numeric() {
Expand All @@ -401,7 +428,7 @@ fn sanitize_struct(s: &str) -> String {
let original = s;
let s = rewrite_names(s);
let mut s = s.to_case(Case::Pascal);
if is_restricted(&s) {
if s.is_keyword() {
s += "Struct"
}
assert_valid_ident(&s, original);
Expand Down Expand Up @@ -477,10 +504,6 @@ mod tests {
}
}

pub fn is_restricted(s: &str) -> bool {
["type", "use", "ref", "self", "match", "final"].contains(&s)
}

pub fn serde_rename(one: &str, two: &str) -> TokenStream {
if one != two {
quote!(#[serde(rename = #one)])
Expand Down