Skip to content

Commit

Permalink
wip: wip
Browse files Browse the repository at this point in the history
  • Loading branch information
Yohe-Am committed Aug 1, 2024
1 parent a48203a commit f0ecfb5
Show file tree
Hide file tree
Showing 5 changed files with 336 additions and 92 deletions.
35 changes: 17 additions & 18 deletions libs/metagen/src/client_py/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

mod node_metas;
mod selections;
mod types;

use core::fmt::Write;

Expand Down Expand Up @@ -130,23 +131,22 @@ fn render_mdk_ts(_config: &ClienPyGenConfig, tg: &Typegraph) -> anyhow::Result<S
write!(
dest,
r#"
export class QueryGraph extends QueryGraphBase {{
constructor() {{
super({{"#
class QueryGraph(QueryGraphBase):
def __init__(self):
self.ty_to_gql_ty_map = {{"#
)?;
for ty_name in name_mapper.memo.borrow().deref().values() {
write!(
dest,
// TODO: proper any scalar support
r#"
"{ty_name}": "Any","#
"{ty_name}": "Any","#
)?;
}
write!(
dest,
r#"
}});
}}
}};
"#
)?;

Expand All @@ -161,16 +161,16 @@ export class QueryGraph extends QueryGraphBase {{
fun.in_id.map(|id| data_types.get(&id).unwrap()),
fun.select_ty.map(|id| selection_names.get(&id).unwrap()),
) {
(Some(arg_ty), Some(select_ty)) => format!("args: {arg_ty}, select: {select_ty}"),
(Some(arg_ty), Some(select_ty)) => format!("self, args: {arg_ty}, select: {select_ty}"),
// functions that return scalars don't need selections
(Some(arg_ty), None) => format!("args: {arg_ty}"),
(Some(arg_ty), None) => format!("self, args: {arg_ty}"),
// not all functions have args (empty struct arg)
(None, Some(select_ty)) => format!("select: {select_ty}"),
(None, Some(select_ty)) => format!("self, select: {select_ty}"),
(None, None) => "".into(),
};

let args_selection = match (fun.in_id, fun.select_ty) {
(Some(_), Some(_)) => "[args, select]",
(Some(_), Some(_)) => "(args, select)",
(Some(_), None) => "args",
(None, Some(_)) => "select",
(None, None) => "true",
Expand Down Expand Up @@ -311,8 +311,8 @@ fn get_manifest(tg: &Typegraph) -> Result<RenderManifest> {

/// Render the common sections like the transports
fn render_static(dest: &mut GenDestBuf) -> core::fmt::Result {
let mdk_ts = include_str!("static/mod.ts");
writeln!(dest, "{}", mdk_ts)?;
let mod_py = include_str!("static/mod.py");
writeln!(dest, "{}", mod_py)?;
Ok(())
}

Expand Down Expand Up @@ -374,12 +374,11 @@ fn render_node_metas(
write!(
dest,
r#"
const nodeMetas = {{
scalar() {{
return {{}};
}},
{methods}
}}
class NodeDescs:
@staticmethod
def scalar():
return NodeMeta()
{methods}
"#
)?;
Ok(memo)
Expand Down
46 changes: 17 additions & 29 deletions libs/metagen/src/client_py/node_metas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,24 @@ impl TsNodeMetasRenderer {
write!(
dest,
r#"
{ty_name}(): NodeMeta {{
return {{
subNodes: ["#
@staticmethod
{ty_name}():
return NodeMeta(
sub_nodes={{"#
)?;
for (key, node_ref) in props {
write!(
dest,
r#"
["{key}", this.{node_ref}()],"#
"{key}": NodeDescs.{node_ref}(),"#
)?;
}
write!(
dest,
r#"
],
}};
}},"#
}},
);
"#
)?;
Ok(())
}
Expand All @@ -54,36 +55,37 @@ impl TsNodeMetasRenderer {
write!(
dest,
r#"
{ty_name}(): NodeMeta {{
return {{
...this.{return_node}(),"#
@staticmethod
{ty_name}():
return NodeMeta(
sub_nodes=NodeDescs.{return_node}().sub_nodes,"#
)?;
if let Some(fields) = argument_fields {
write!(
dest,
r#"
argumentTypes: {{"#
arg_types={{"#
)?;

for (key, ty) in fields {
write!(
dest,
r#"
{key}: "{ty}","#
"{key}": "{ty}","#
)?;
}

write!(
dest,
r#"
}},"#
}},"#
)?;
}
write!(
dest,
r#"
}};
}},"#
);
"#
)?;
Ok(())
}
Expand Down Expand Up @@ -161,20 +163,6 @@ impl RenderType for TsNodeMetasRenderer {
// data: UnionTypeData { any_of: variants },
// base,
} => {
// let variants = variants
// .iter()
// .map(|&inner| {
// let (ty_name, _cyclic) = renderer.render_subgraph(inner, cursor)?;
// let ty_name = match ty_name {
// RenderedName::Name(name) => name,
// RenderedName::Placeholder(name) => name,
// };
// Ok::<_, anyhow::Error>(ty_name)
// })
// .collect::<Result<Vec<_>, _>>()?;
// let ty_name = normalize_type_title(&base.title);
// self.render_union_type(renderer, &ty_name, variants)?;
// ty_name
todo!("unions are wip")
}
};
Expand Down
62 changes: 35 additions & 27 deletions libs/metagen/src/client_py/selections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,30 +20,51 @@ impl TsNodeSelectionsRenderer {
ty_name: &str,
props: IndexMap<String, (Rc<str>, Option<Rc<str>>)>,
) -> std::fmt::Result {
writeln!(
dest,
"export type {ty_name} = {{
_?: SelectionFlags;"
)?;
writeln!(dest, "class {ty_name}(Selection, total=False):")?;
for (name, (select_ty, arg_ty)) in props {
if let Some(arg_ty) = arg_ty {
if &select_ty[..] == "boolean" {
// just providing the argument is enough to signal selection
writeln!(dest, " {name}:?: {arg_ty};")?;
writeln!(dest, " {name}:?: {arg_ty};")?;
} else {
// we need to allow false to allow explicit disabling
// when the select all flag is set
writeln!(dest, " {name}?: [{arg_ty}, {select_ty}] | false;")?;
writeln!(dest, " {name}?: [{arg_ty}, {select_ty}] | false;")?;
}
} else if &select_ty[..] == "boolean" {
writeln!(dest, " {name}?: {select_ty};")?;
writeln!(dest, " {name}?: {select_ty};")?;
} else {
writeln!(dest, " {name}?: {select_ty} | false;")?;
writeln!(dest, " {name}?: {select_ty} | false;")?;
}
}
writeln!(dest, "}};")?;
Ok(())
}

fn selection_for_function(&self, output_ty: u32, renderer: &TypeRenderer) -> String {
match renderer.nodes[output_ty as usize].deref() {
TypeNode::Boolean { .. }
| TypeNode::Float { .. }
| TypeNode::Integer { .. }
| TypeNode::String { .. }
| TypeNode::File { .. } => {
let arg_ty = self.arg_ty_names.get(&output_ty).unwrap();
format!("ScalarSelectArgs[{arg_ty}]")
},
TypeNode::Object { .. } => {
let arg_ty = self.arg_ty_names.get(&output_ty).unwrap();
format!("CompositSelectArgs[{arg_ty}]")
},
TypeNode::Optional { data: OptionalTypeData { item, .. }, .. }
| TypeNode::List { data: ListTypeData { items: item, .. }, .. }
=> {
self.selection_for_function(*item, renderer)
},
TypeNode::Union { .. } | TypeNode::Either { .. } => todo!("unions are wip"),
TypeNode::Function { .. } => unreachable!("A function can not return a function"),
TypeNode::Any { .. } => unimplemented!("Any type support not implemented"),
}
}
}

impl RenderType for TsNodeSelectionsRenderer {
Expand All @@ -59,12 +80,13 @@ impl RenderType for TsNodeSelectionsRenderer {
| TypeNode::Float { .. }
| TypeNode::Integer { .. }
| TypeNode::String { .. }
| TypeNode::File { .. } => "boolean".to_string(),
| TypeNode::File { .. } => "ScalarSelectNoArgs".to_string(),
TypeNode::Any { .. } => unimplemented!("Any type support not implemented"),
TypeNode::Optional { data: OptionalTypeData { item, .. }, .. }
| TypeNode::List { data: ListTypeData { items: item, .. }, .. }
| TypeNode::Function { data:FunctionTypeData { output:item,.. }, .. }
| TypeNode::List { data: ListTypeData { items: item, .. }, .. }
=> renderer.render_subgraph(*item, cursor)?.0.unwrap().to_string(),
| TypeNode::Function { data:FunctionTypeData { output, .. }, .. }
=> self.selection_for_function(*output, renderer),
TypeNode::Object { data, base } => {
let props = data
.properties
Expand Down Expand Up @@ -93,7 +115,7 @@ impl RenderType for TsNodeSelectionsRenderer {
let ty_name = normalize_type_title(node_name);
let ty_name = format!("{ty_name}Selections").to_pascal_case();
self.render_for_object(renderer, &ty_name, props)?;
ty_name
format!("CompositSelectNoArgs[{ty_name}]")
}
TypeNode::Either {
..
Expand All @@ -105,20 +127,6 @@ impl RenderType for TsNodeSelectionsRenderer {
// data: UnionTypeData { any_of: variants },
// base,
} => {
// let variants = variants
// .iter()
// .map(|&inner| {
// let (ty_name, _cyclic) = renderer.render_subgraph(inner, cursor)?;
// let ty_name = match ty_name {
// RenderedName::Name(name) => name,
// RenderedName::Placeholder(name) => name,
// };
// Ok::<_, anyhow::Error>(ty_name)
// })
// .collect::<Result<Vec<_>, _>>()?;
// let ty_name = normalize_type_title(&base.title);
// self.render_union_type(renderer, &ty_name, variants)?;
// ty_name
todo!("unions are wip")
}
};
Expand Down
28 changes: 10 additions & 18 deletions libs/metagen/src/client_py/static/mod.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def selection_to_nodes(
+ "requires argument object "
+ f"but selection is typeof {type(node_selection)}"
)
sub_selections = node_selection[0]
sub_selections = node_selection[1]
elif isinstance(sub_selections, tuple):
raise Exception(
f"node at {parent_path}.{node_selection} "
Expand Down Expand Up @@ -385,14 +385,10 @@ def Post():
@staticmethod
def Func9():
return NodeMeta(
**{
**asdict(NodeDescs.Post()),
**asdict(NodeMeta(
arg_types={
"filter": "Optional4",
},
))
}
sub_nodes=NodeDescs.Post().sub_nodes,
arg_types={
"filter": "Optional4",
},
)

@staticmethod
Expand All @@ -408,20 +404,16 @@ def User():
@staticmethod
def Func19():
return NodeMeta(
**{
**asdict(NodeDescs.Post()),
**asdict(NodeMeta(
arg_types={
"id": "String13",
},
))
}
sub_nodes=NodeDescs.User().sub_nodes,
arg_types={
"id": "String13",
},
)

@staticmethod
def Func20():
return NodeMeta(
**asdict(NodeDescs.User()),
sub_nodes=NodeDescs.User().sub_nodes,
)


Expand Down
Loading

0 comments on commit f0ecfb5

Please sign in to comment.