Skip to content

Commit c609a6d

Browse files
committed
Add annotation setup
1 parent d497994 commit c609a6d

2 files changed

Lines changed: 76 additions & 0 deletions

File tree

compiler/src/compile.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -984,6 +984,64 @@ impl<O: OutputStream> Compiler<O> {
984984
Ok(())
985985
}
986986

987+
fn option_stmt_to_bool(&mut self, stmts: &Option<ast::Suite>) -> bool {
988+
match &stmts {
989+
Some(stmts) => self.find_ann(stmts),
990+
None => false,
991+
}
992+
}
993+
994+
fn find_ann(&mut self, body: &[ast::Statement]) -> bool {
995+
use ast::StatementType::*;
996+
997+
for statement in body {
998+
let res = match &statement.node {
999+
AnnAssign {
1000+
target: _,
1001+
annotation: _,
1002+
value: _,
1003+
} => true,
1004+
For {
1005+
is_async: _,
1006+
target: _,
1007+
iter: _,
1008+
body,
1009+
orelse,
1010+
} => self.find_ann(body) || self.option_stmt_to_bool(orelse),
1011+
If {
1012+
test: _,
1013+
body,
1014+
orelse,
1015+
} => self.find_ann(body) || self.option_stmt_to_bool(orelse),
1016+
While {
1017+
test: _,
1018+
body,
1019+
orelse,
1020+
} => self.find_ann(body) || self.option_stmt_to_bool(orelse),
1021+
With {
1022+
is_async: _,
1023+
items: _,
1024+
body,
1025+
} => self.find_ann(body),
1026+
Try {
1027+
body,
1028+
handlers: _,
1029+
orelse,
1030+
finalbody,
1031+
} => {
1032+
self.find_ann(body)
1033+
|| self.option_stmt_to_bool(orelse)
1034+
|| self.option_stmt_to_bool(finalbody)
1035+
}
1036+
_ => false,
1037+
};
1038+
if res {
1039+
return true;
1040+
}
1041+
}
1042+
return false;
1043+
}
1044+
9871045
fn compile_class_def(
9881046
&mut self,
9891047
name: &str,
@@ -1037,6 +1095,18 @@ impl<O: OutputStream> Compiler<O> {
10371095
name: "__qualname__".to_owned(),
10381096
scope: bytecode::NameScope::Free,
10391097
});
1098+
// setup annotations
1099+
if self.find_ann(body) {
1100+
self.emit(Instruction::BuildMap {
1101+
size: 0,
1102+
unpack: false,
1103+
for_call: false,
1104+
});
1105+
self.emit(Instruction::StoreName {
1106+
name: "__annotations__".to_owned(),
1107+
scope: bytecode::NameScope::Free,
1108+
});
1109+
}
10401110
self.compile_statements(new_body)?;
10411111
self.emit(Instruction::LoadConst {
10421112
value: bytecode::Constant::None,

tests/snippets/class.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,3 +253,9 @@ class C(A, B):
253253
pass
254254
else:
255255
assert False, "Managed to create a class without local type precedence."
256+
257+
258+
class A():
259+
a: int
260+
261+
assert A.__annotations__['a'] == int

0 commit comments

Comments
 (0)