Skip to content

Commit

Permalink
Update gen_decl.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
mtshiba committed Aug 17, 2024
1 parent 172cd52 commit 18387ef
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions crates/py2erg/gen_decl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,6 @@ pub struct DeclFile {
pub filename: String,
pub code: String,
}

fn escape_type(typ: String) -> String {
typ.replace('%', "Type_").replace("<module>", "")
}

pub struct DeclFileGenerator {
filename: String,
namespace: String,
Expand Down Expand Up @@ -65,10 +60,17 @@ impl DeclFileGenerator {
}
}

fn escape_type(&self, typ: String) -> String {
typ.replace('%', "Type_")
.replace("<module>", "")
.replace(self.filename.trim_end_matches(".d.er"), "")
.replace(&self.namespace, "")
}

// e.g. `x: foo.Bar` => `foo = pyimport "foo"; x: foo.Bar`
fn prepare_using_type(&mut self, typ: &Type) {
let namespace = Str::rc(typ.namespace().split('.').next().unwrap());
if !namespace.is_empty() && self.imported.insert(namespace.clone()) {
if namespace != self.namespace && !namespace.is_empty() && self.imported.insert(namespace.clone()) {
self.code += &format!("{namespace} = pyimport \"{namespace}\"\n");
}
}
Expand All @@ -84,7 +86,7 @@ impl DeclFileGenerator {
.replace(['%', '*'], "___");
let ref_t = def.sig.ident().ref_t();
self.prepare_using_type(ref_t);
let typ = escape_type(ref_t.replace_failure().to_string_unabbreviated());
let typ = self.escape_type(ref_t.replace_failure().to_string_unabbreviated());
// Erg can automatically import nested modules
// `import http.client` => `http = pyimport "http"`
let decl = if ref_t.is_py_module() {
Expand Down Expand Up @@ -129,7 +131,7 @@ impl DeclFileGenerator {
.replace_failure()
.to_string_unabbreviated();
self.prepare_using_type(class.sup.typ());
let sup = escape_type(sup);
let sup = self.escape_type(sup);
let decl = format!(".{class_name} <: {sup}\n");
self.code += &decl;
}
Expand All @@ -140,7 +142,7 @@ impl DeclFileGenerator {
{
for (attr, t) in rec.iter() {
self.prepare_using_type(t);
let typ = escape_type(t.replace_failure().to_string_unabbreviated());
let typ = self.escape_type(t.replace_failure().to_string_unabbreviated());
let decl = format!("{}.{}: {typ}\n", self.namespace, attr.symbol);
self.code += &decl;
}
Expand All @@ -152,7 +154,7 @@ impl DeclFileGenerator {
{
for (attr, t) in rec.iter() {
self.prepare_using_type(t);
let typ = escape_type(t.replace_failure().to_string_unabbreviated());
let typ = self.escape_type(t.replace_failure().to_string_unabbreviated());
let decl = format!("{}.{}: {typ}\n", self.namespace, attr.symbol);
self.code += &decl;
}
Expand Down

0 comments on commit 18387ef

Please sign in to comment.