Add comments & refactoring

This commit is contained in:
Shunsuke Shibayama 2022-11-08 02:26:06 +09:00
parent 14b143778f
commit 7663d3cd62
12 changed files with 42 additions and 23 deletions

View file

@ -71,7 +71,7 @@ fn escape_name(ident: Identifier) -> Str {
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CodeGenUnit { pub struct PyCodeGenUnit {
pub(crate) id: usize, pub(crate) id: usize,
pub(crate) py_version: PythonVersion, pub(crate) py_version: PythonVersion,
pub(crate) codeobj: CodeObj, pub(crate) codeobj: CodeObj,
@ -82,14 +82,14 @@ pub struct CodeGenUnit {
pub(crate) _refs: Vec<ValueObj>, // ref-counted objects pub(crate) _refs: Vec<ValueObj>, // ref-counted objects
} }
impl PartialEq for CodeGenUnit { impl PartialEq for PyCodeGenUnit {
#[inline] #[inline]
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.id == other.id self.id == other.id
} }
} }
impl fmt::Display for CodeGenUnit { impl fmt::Display for PyCodeGenUnit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!( write!(
f, f,
@ -100,7 +100,7 @@ impl fmt::Display for CodeGenUnit {
} }
} }
impl CodeGenUnit { impl PyCodeGenUnit {
pub fn new<S: Into<Str>, T: Into<Str>>( pub fn new<S: Into<Str>, T: Into<Str>>(
id: usize, id: usize,
py_version: PythonVersion, py_version: PythonVersion,
@ -123,12 +123,12 @@ impl CodeGenUnit {
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CodeGenStack(Vec<CodeGenUnit>); pub struct PyCodeGenStack(Vec<PyCodeGenUnit>);
impl_stream_for_wrapper!(CodeGenStack, CodeGenUnit); impl_stream_for_wrapper!(PyCodeGenStack, PyCodeGenUnit);
#[derive(Debug)] #[derive(Debug)]
pub struct CodeGenerator { pub struct PyCodeGenerator {
cfg: ErgConfig, cfg: ErgConfig,
pub(crate) py_version: PythonVersion, pub(crate) py_version: PythonVersion,
str_cache: CacheSet<str>, str_cache: CacheSet<str>,
@ -138,10 +138,10 @@ pub struct CodeGenerator {
module_type_loaded: bool, module_type_loaded: bool,
abc_loaded: bool, abc_loaded: bool,
unit_size: usize, unit_size: usize,
units: CodeGenStack, units: PyCodeGenStack,
} }
impl CodeGenerator { impl PyCodeGenerator {
pub fn new(cfg: ErgConfig) -> Self { pub fn new(cfg: ErgConfig) -> Self {
Self { Self {
py_version: cfg.target_version.unwrap_or_else(env_python_version), py_version: cfg.target_version.unwrap_or_else(env_python_version),
@ -153,7 +153,7 @@ impl CodeGenerator {
module_type_loaded: false, module_type_loaded: false,
abc_loaded: false, abc_loaded: false,
unit_size: 0, unit_size: 0,
units: CodeGenStack::empty(), units: PyCodeGenStack::empty(),
} }
} }
@ -172,17 +172,17 @@ impl CodeGenerator {
/// 大抵の場合はモジュールのブロックが返る /// 大抵の場合はモジュールのブロックが返る
#[inline] #[inline]
fn toplevel_block(&self) -> &CodeGenUnit { fn toplevel_block(&self) -> &PyCodeGenUnit {
self.units.first().unwrap() self.units.first().unwrap()
} }
#[inline] #[inline]
fn cur_block(&self) -> &CodeGenUnit { fn cur_block(&self) -> &PyCodeGenUnit {
self.units.last().unwrap() self.units.last().unwrap()
} }
#[inline] #[inline]
fn mut_cur_block(&mut self) -> &mut CodeGenUnit { fn mut_cur_block(&mut self) -> &mut PyCodeGenUnit {
self.units.last_mut().unwrap() self.units.last_mut().unwrap()
} }
@ -923,7 +923,7 @@ impl CodeGenerator {
.get(0) .get(0)
.and_then(|def| def.ln_begin()) .and_then(|def| def.ln_begin())
.unwrap_or_else(|| sig.ln_begin().unwrap()); .unwrap_or_else(|| sig.ln_begin().unwrap());
self.units.push(CodeGenUnit::new( self.units.push(PyCodeGenUnit::new(
self.unit_size, self.unit_size,
self.py_version, self.py_version,
vec![], vec![],
@ -991,7 +991,7 @@ impl CodeGenerator {
} }
let code = { let code = {
self.unit_size += 1; self.unit_size += 1;
self.units.push(CodeGenUnit::new( self.units.push(PyCodeGenUnit::new(
self.unit_size, self.unit_size,
self.py_version, self.py_version,
vec![], vec![],
@ -2288,7 +2288,7 @@ impl CodeGenerator {
Some(l) => l, Some(l) => l,
None => class.sig.ln_begin().unwrap(), None => class.sig.ln_begin().unwrap(),
}; };
self.units.push(CodeGenUnit::new( self.units.push(PyCodeGenUnit::new(
self.unit_size, self.unit_size,
self.py_version, self.py_version,
vec![], vec![],
@ -2436,7 +2436,7 @@ impl CodeGenerator {
.first() .first()
.and_then(|first| first.ln_begin()) .and_then(|first| first.ln_begin())
.unwrap_or(0); .unwrap_or(0);
self.units.push(CodeGenUnit::new( self.units.push(PyCodeGenUnit::new(
self.unit_size, self.unit_size,
self.py_version, self.py_version,
params, params,
@ -2588,7 +2588,7 @@ impl CodeGenerator {
pub fn emit(&mut self, hir: HIR) -> CodeObj { pub fn emit(&mut self, hir: HIR) -> CodeObj {
log!(info "the code-generating process has started.{RESET}"); log!(info "the code-generating process has started.{RESET}");
self.unit_size += 1; self.unit_size += 1;
self.units.push(CodeGenUnit::new( self.units.push(PyCodeGenUnit::new(
self.unit_size, self.unit_size,
self.py_version, self.py_version,
vec![], vec![],

View file

@ -10,7 +10,7 @@ use erg_common::traits::{Runnable, Stream};
use crate::ty::codeobj::CodeObj; use crate::ty::codeobj::CodeObj;
use crate::build_hir::HIRBuilder; use crate::build_hir::HIRBuilder;
use crate::codegen::CodeGenerator; use crate::codegen::PyCodeGenerator;
use crate::desugar_hir::HIRDesugarer; use crate::desugar_hir::HIRDesugarer;
use crate::error::{CompileError, CompileErrors}; use crate::error::{CompileError, CompileErrors};
use crate::hir::{Expr, HIR}; use crate::hir::{Expr, HIR};
@ -96,7 +96,7 @@ pub struct Compiler {
pub cfg: ErgConfig, pub cfg: ErgConfig,
builder: HIRBuilder, builder: HIRBuilder,
mod_cache: SharedModuleCache, mod_cache: SharedModuleCache,
code_generator: CodeGenerator, code_generator: PyCodeGenerator,
} }
impl Runnable for Compiler { impl Runnable for Compiler {
@ -114,7 +114,7 @@ impl Runnable for Compiler {
mod_cache.clone(), mod_cache.clone(),
py_mod_cache, py_mod_cache,
), ),
code_generator: CodeGenerator::new(cfg.copy()), code_generator: PyCodeGenerator::new(cfg.copy()),
mod_cache, mod_cache,
cfg, cfg,
} }

View file

@ -19,6 +19,9 @@ impl SubtypePair {
} }
} }
/// Caches type relationships.
/// The cost of searching for subtype relations of a class, for example, is not small.
/// Some relationships are cached because they tend to be queried many times.
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct TypeCmpCache { pub struct TypeCmpCache {
cache: Dict<SubtypePair, bool>, cache: Dict<SubtypePair, bool>,

View file

@ -26,7 +26,6 @@ use Variance::*;
impl Context { impl Context {
pub const TOP_LEVEL: usize = 1; pub const TOP_LEVEL: usize = 1;
/// 型を非依存化する
fn _independentise(_t: Type, _ts: &[Type]) -> Type { fn _independentise(_t: Type, _ts: &[Type]) -> Type {
todo!() todo!()
} }

View file

@ -3,6 +3,7 @@ use erg_common::traits::Stream;
use crate::hir::{Accessor, AttrDef, Block, Expr, HIR}; use crate::hir::{Accessor, AttrDef, Block, Expr, HIR};
/// Desugares HIR to make it more like Python semantics.
pub struct HIRDesugarer {} pub struct HIRDesugarer {}
impl HIRDesugarer { impl HIRDesugarer {

View file

@ -28,6 +28,10 @@ enum BlockKind {
use BlockKind::*; use BlockKind::*;
/// Checks code for side effects.
/// For example:
/// * check if expressions with side effects are not used in functions
/// * check if methods that change internal state are not defined in immutable classes
#[derive(Debug)] #[derive(Debug)]
pub struct SideEffectChecker { pub struct SideEffectChecker {
cfg: ErgConfig, cfg: ErgConfig,

View file

@ -1925,6 +1925,8 @@ impl Locational for Module {
impl_stream_for_wrapper!(Module, Expr); impl_stream_for_wrapper!(Module, Expr);
/// High-level Intermediate Representation
/// AST with type information added
#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HIR { pub struct HIR {
pub name: Str, pub name: Str,

View file

@ -18,6 +18,8 @@ use crate::ty::HasType;
use crate::hir::*; use crate::hir::*;
use crate::mod_cache::SharedModuleCache; use crate::mod_cache::SharedModuleCache;
/// Link code using the module cache.
/// Erg links all non-Python modules into a single pyc file.
pub struct Linker<'a> { pub struct Linker<'a> {
cfg: &'a ErgConfig, cfg: &'a ErgConfig,
mod_cache: &'a SharedModuleCache, mod_cache: &'a SharedModuleCache,

View file

@ -41,7 +41,7 @@ use crate::varinfo::{Mutability, VarInfo, VarKind};
use crate::AccessKind; use crate::AccessKind;
use Visibility::*; use Visibility::*;
/// Singleton that checks types of an AST, and convert (lower) it into a HIR /// Checks & infers types of an AST, and convert (lower) it into a HIR
#[derive(Debug)] #[derive(Debug)]
pub struct ASTLowerer { pub struct ASTLowerer {
cfg: ErgConfig, cfg: ErgConfig,

View file

@ -62,6 +62,9 @@ impl ModuleEntry {
} }
} }
/// Caches checked modules.
/// In addition to being queried here when re-imported, it is also used when linking
/// (Erg links all scripts defined in erg and outputs them to a single pyc file).
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct ModuleCache { pub struct ModuleCache {
cache: Dict<PathBuf, ModuleEntry>, cache: Dict<PathBuf, ModuleEntry>,

View file

@ -28,6 +28,10 @@ struct LocalVars {
dropped_vars: Dict<Str, Location>, dropped_vars: Dict<Str, Location>,
} }
/// Check code ownership.
/// for example:
/// * Check if moved variables are not used again.
/// * Checks whether a mutable reference method is called in an immutable reference method.
#[derive(Debug)] #[derive(Debug)]
pub struct OwnershipChecker { pub struct OwnershipChecker {
cfg: ErgConfig, cfg: ErgConfig,

View file

@ -36,6 +36,7 @@ impl Mutability {
use Mutability::*; use Mutability::*;
/// TODO: removed in the future
/// e.g. /// e.g.
/// ```python /// ```python
/// K(T, [U, V]) = ... /// K(T, [U, V]) = ...