Skip to content

Commit

Permalink
fix: #510
Browse files Browse the repository at this point in the history
  • Loading branch information
mtshiba committed May 3, 2024
1 parent 29a70b0 commit 50787a0
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
24 changes: 24 additions & 0 deletions crates/erg_compiler/link_hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,11 @@ impl<'a> HIRLinker<'a> {
match acc {
Accessor::Attr(attr) => {
self.replace_import(&mut attr.obj);
if attr.ident.inspect() == "__file__"
&& attr.ident.vi.def_loc.module.is_none()
{
*expr = self.__file__();
}
}
Accessor::Ident(ident) => match &ident.inspect()[..] {
"module" => {
Expand All @@ -241,6 +246,9 @@ impl<'a> HIRLinker<'a> {
"global" => {
*expr = Expr::from(Identifier::static_public("__builtins__"));
}
"__file__" if ident.vi.def_loc.module.is_none() => {
*expr = self.__file__();
}
_ => {}
},
}
Expand Down Expand Up @@ -363,6 +371,22 @@ impl<'a> HIRLinker<'a> {
Expr::from(__import__).call1(Expr::from(__name__))
}

fn __file__(&self) -> Expr {
let path = self.cfg.input.path().to_path_buf();
let token = Token::new_fake(
TokenKind::StrLit,
format!(
"\"{}\"",
path.canonicalize().unwrap_or(path).to_string_lossy()
),
0,
0,
0,
);
let lit = Literal::try_from(token).unwrap();
Expr::from(lit)
}

/// ```erg
/// x = import "mod"
/// ```
Expand Down
15 changes: 15 additions & 0 deletions tests/should_ok/dunder.er
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
imp = import "import"

func() =
__file__ = "foo"
__file__

C = Class()
C.
__file__ = "bar"

assert __file__.endswith "dunder.er"
assert func() == "foo"
assert module::__file__.endswith "dunder.er"
assert C.new().__file__ == "bar"
assert imp.func().endswith "import.er"
1 change: 1 addition & 0 deletions tests/should_ok/import.er
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.func() = __file__
5 changes: 5 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ fn exec_dict_test() -> Result<(), ()> {
expect_success("tests/should_ok/dict.er", 0)
}

#[test]
fn exec_dunder() -> Result<(), ()> {
expect_success("tests/should_ok/dunder.er", 0)
}

#[test]
fn exec_empty_check() -> Result<(), ()> {
expect_success("tests/should_ok/dyn_type_check.er", 0)
Expand Down

0 comments on commit 50787a0

Please sign in to comment.