From 67a65b5c527d7eec6426b680b8d5cf464ea88f68 Mon Sep 17 00:00:00 2001 From: Shunsuke Shibayama Date: Sun, 18 Aug 2024 13:35:00 +0900 Subject: [PATCH] feat: support glob import --- crates/py2erg/convert.rs | 26 ++++++++++++++++++++++++++ tests/import.py | 3 +++ 2 files changed, 29 insertions(+) diff --git a/crates/py2erg/convert.rs b/crates/py2erg/convert.rs index 9f56714..1a7daa7 100644 --- a/crates/py2erg/convert.rs +++ b/crates/py2erg/convert.rs @@ -2193,6 +2193,29 @@ impl ASTConverter { } } + fn convert_glob_import(&mut self, location: PyLocation, module: String) -> Expr { + let import_acc = Expr::Accessor(Accessor::Ident( + self.convert_ident("__import__".to_string(), location), + )); + let cont = if module == "." { + "\"__init__\"".to_string() + } else { + format!("\"{module}\"") + }; + let mod_name = Expr::Literal(Literal::new(Token::new( + TokenKind::StrLit, + cont, + location.row.get(), + location.column.to_zero_indexed(), + ))); + let call = import_acc.clone().call1(mod_name); + let var = VarSignature::new(VarPattern::Glob(Token::DUMMY), None); + Expr::Def(Def::new( + Signature::Var(var), + DefBody::new(EQUAL, Block::new(vec![call]), DefId(0)), + )) + } + /** ```erg from foo import bar # if bar, baz are modules @@ -2242,6 +2265,9 @@ impl ASTConverter { let call = import_acc.clone().call1(mod_name); let mut exprs = vec![]; let mut imports = vec![]; + if names.len() == 1 && names[0].name.as_str() == "*" { + return self.convert_glob_import(location, module); + } for name in names { let name_path = self .cfg diff --git a/tests/import.py b/tests/import.py index 11228de..222a25c 100644 --- a/tests/import.py +++ b/tests/import.py @@ -9,6 +9,7 @@ import datetime as dt from http.client import HTTPResponse import http +from math import * i = random.randint(0, 1) print(i + 1) @@ -43,3 +44,5 @@ assert export.http.client.HTTPResponse == Resp _ = bar.Baz + +_ = sin(acos(exp(0))) # OK