Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dev: introduce basic type checker #183

Merged
merged 10 commits into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 71 additions & 2 deletions crates/tinymist-query/src/analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,82 @@ pub mod linked_def;
pub use linked_def::*;
pub mod signature;
pub use signature::*;
pub mod r#type;
pub(crate) use r#type::*;
pub mod track_values;
pub use track_values::*;
mod prelude;

mod global;
pub use global::*;

#[cfg(test)]
mod type_check_tests {

use core::fmt;

use typst::syntax::Source;

use crate::analysis::type_check;
use crate::tests::*;

use super::TypeCheckInfo;

#[test]
fn test() {
snapshot_testing("type_check", &|ctx, path| {
let source = ctx.source_by_path(&path).unwrap();

let result = type_check(ctx, source.clone());
let result = result
.as_deref()
.map(|e| format!("{:#?}", TypeCheckSnapshot(&source, e)));
let result = result.as_deref().unwrap_or("<nil>");

assert_snapshot!(result);
});
}

struct TypeCheckSnapshot<'a>(&'a Source, &'a TypeCheckInfo);

impl fmt::Debug for TypeCheckSnapshot<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let source = self.0;
let info = self.1;
let mut vars = info
.vars
.iter()
.map(|e| (e.1.name(), e.1))
.collect::<Vec<_>>();

vars.sort_by(|x, y| x.0.cmp(&y.0));

for (name, var) in vars {
writeln!(f, "{:?} = {:?}", name, info.simplify(var.get_ref()))?;
}

writeln!(f, "---")?;
let mut mapping = info
.mapping
.iter()
.map(|e| (source.range(*e.0).unwrap_or_default(), e.1))
.collect::<Vec<_>>();

mapping.sort_by(|x, y| {
x.0.start
.cmp(&y.0.start)
.then_with(|| x.0.end.cmp(&y.0.end))
});

for (range, value) in mapping {
writeln!(f, "{range:?} -> {value:?}")?;
}

Ok(())
}
}
}

#[cfg(test)]
mod module_tests {
use reflexo::path::unix_slash;
Expand Down Expand Up @@ -283,15 +352,15 @@ mod signature_tests {
write!(f, "with ")?;
for arg in &w.items {
if let Some(name) = &arg.name {
write!(f, "{}: ", name)?;
write!(f, "{name}: ")?;
}
write!(
f,
"{}, ",
arg.value.as_ref().map(|v| v.repr()).unwrap_or_default()
)?;
}
writeln!(f, "")?;
f.write_str("\n")?;
}

&sig.signature
Expand Down
4 changes: 2 additions & 2 deletions crates/tinymist-query/src/analysis/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ pub struct CallInfo {

// todo: cache call
/// Analyzes a function call.
pub fn analyze_call<'a>(
pub fn analyze_call(
ctx: &mut AnalysisContext,
source: Source,
node: LinkedNode<'a>,
node: LinkedNode,
) -> Option<Arc<CallInfo>> {
trace!("func call found: {:?}", node);
let f = node.cast::<ast::FuncCall>()?;
Expand Down
107 changes: 77 additions & 30 deletions crates/tinymist-query/src/analysis/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use once_cell::sync::OnceCell;
use parking_lot::RwLock;
use reflexo::hash::hash128;
use reflexo::{cow_mut::CowMut, debug_loc::DataSource, ImmutPath};
use typst::eval::Eval;
use typst::foundations;
use typst::{
diag::{eco_format, FileError, FileResult, PackageError},
Expand All @@ -20,7 +21,7 @@ use typst::{
use typst::{foundations::Value, syntax::ast, text::Font};
use typst::{layout::Position, syntax::FileId as TypstFileId};

use super::{DefUseInfo, ImportInfo, Signature, SignatureTarget};
use super::{DefUseInfo, ImportInfo, Signature, SignatureTarget, TypeCheckInfo};
use crate::{
lsp_to_typst,
syntax::{
Expand All @@ -35,6 +36,7 @@ use crate::{
#[derive(Default)]
pub struct ModuleAnalysisCache {
source: OnceCell<FileResult<Source>>,
top_level_eval: OnceCell<Option<Arc<TypeCheckInfo>>>,
def_use: OnceCell<Option<Arc<DefUseInfo>>>,
}

Expand All @@ -58,6 +60,19 @@ impl ModuleAnalysisCache {
) -> Option<Arc<DefUseInfo>> {
self.def_use.get_or_init(f).clone()
}

/// Try to get the top-level evaluation information of a file.
pub(crate) fn type_check(&self) -> Option<Arc<TypeCheckInfo>> {
self.top_level_eval.get().cloned().flatten()
}

/// Compute the top-level evaluation information of a file.
pub(crate) fn compute_type_check(
&self,
f: impl FnOnce() -> Option<Arc<TypeCheckInfo>>,
) -> Option<Arc<TypeCheckInfo>> {
self.top_level_eval.get_or_init(f).clone()
}
}

/// The analysis data holds globally.
Expand Down Expand Up @@ -195,9 +210,10 @@ impl<Inputs, Output> ComputingNode<Inputs, Output> {
#[allow(clippy::type_complexity)]
pub struct ModuleAnalysisGlobalCache {
def_use_lexical_hierarchy: ComputingNode<Source, EcoVec<LexicalHierarchy>>,
import: Arc<ComputingNode<EcoVec<LexicalHierarchy>, Arc<ImportInfo>>>,
type_check: Arc<ComputingNode<Source, Arc<TypeCheckInfo>>>,
def_use: Arc<ComputingNode<(EcoVec<LexicalHierarchy>, Arc<ImportInfo>), Arc<DefUseInfo>>>,

import: Arc<ComputingNode<EcoVec<LexicalHierarchy>, Arc<ImportInfo>>>,
signature_source: Option<Source>,
signatures: HashMap<usize, Signature>,
}
Expand All @@ -206,6 +222,7 @@ impl Default for ModuleAnalysisGlobalCache {
fn default() -> Self {
Self {
def_use_lexical_hierarchy: ComputingNode::new("def_use_lexical_hierarchy"),
type_check: Arc::new(ComputingNode::new("type_check")),
import: Arc::new(ComputingNode::new("import")),
def_use: Arc::new(ComputingNode::new("def_use")),

Expand Down Expand Up @@ -462,6 +479,34 @@ impl<'w> AnalysisContext<'w> {
typst_to_lsp::range(position, src, self.analysis.position_encoding)
}

/// Get the type check information of a source file.
pub(crate) fn type_check(&mut self, source: Source) -> Option<Arc<TypeCheckInfo>> {
let fid = source.id();

if let Some(res) = self.caches.modules.entry(fid).or_default().type_check() {
return Some(res);
}

let cache = self.at_module(fid);

let tl = cache.type_check.clone();
let res = tl
.compute(source, |_before, after| {
let next = crate::analysis::type_check(self, after);
next.or_else(|| tl.output.read().clone())
})
.ok()
.flatten();

self.caches
.modules
.entry(fid)
.or_default()
.compute_type_check(|| res.clone());

res
}

/// Get the def-use information of a source file.
pub fn def_use(&mut self, source: Source) -> Option<Arc<DefUseInfo>> {
let fid = source.id();
Expand Down Expand Up @@ -512,6 +557,35 @@ impl<'w> AnalysisContext<'w> {
self.analysis.caches.modules.entry(fid).or_default()
}

pub(crate) fn with_vm<T>(&self, f: impl FnOnce(&mut typst::eval::Vm) -> T) -> T {
use comemo::Track;
use typst::engine::*;
use typst::eval::*;
use typst::foundations::*;
use typst::introspection::*;

let mut locator = Locator::default();
let introspector = Introspector::default();
let mut tracer = Tracer::new();
let engine = Engine {
world: self.world().track(),
route: Route::default(),
introspector: introspector.track(),
locator: &mut locator,
tracer: tracer.track_mut(),
};

let context = Context::none();
let mut vm = Vm::new(
engine,
context.track(),
Scopes::new(Some(self.world().library())),
Span::detached(),
);

f(&mut vm)
}

pub(crate) fn mini_eval(&self, rr: ast::Expr<'_>) -> Option<Value> {
Some(match rr {
ast::Expr::None(_) => Value::None,
Expand All @@ -521,34 +595,7 @@ impl<'w> AnalysisContext<'w> {
ast::Expr::Float(v) => Value::Float(v.get()),
ast::Expr::Numeric(v) => Value::numeric(v.get()),
ast::Expr::Str(v) => Value::Str(v.get().into()),
e => {
use comemo::Track;
use typst::engine::*;
use typst::eval::*;
use typst::foundations::*;
use typst::introspection::*;

let mut locator = Locator::default();
let introspector = Introspector::default();
let mut tracer = Tracer::new();
let engine = Engine {
world: self.world().track(),
route: Route::default(),
introspector: introspector.track(),
locator: &mut locator,
tracer: tracer.track_mut(),
};

let context = Context::none();
let mut vm = Vm::new(
engine,
context.track(),
Scopes::new(Some(self.world().library())),
Span::detached(),
);

return e.eval(&mut vm).ok();
}
e => return self.with_vm(|vm| e.eval(vm).ok()),
})
}
}
Expand Down
19 changes: 14 additions & 5 deletions crates/tinymist-query/src/analysis/linked_def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ pub fn find_definition(
}

let Some((def_fid, def)) = def_info else {
return resolve_global(ctx, use_site.clone()).and_then(move |f| {
return resolve_global_value(ctx, use_site.clone(), false).and_then(move |f| {
value_to_def(
ctx,
f,
Expand Down Expand Up @@ -209,20 +209,29 @@ pub fn resolve_callee(ctx: &mut AnalysisContext, callee: LinkedNode) -> Option<F
}
})
.or_else(|| {
resolve_global(ctx, callee).and_then(|v| match v {
resolve_global_value(ctx, callee, false).and_then(|v| match v {
Value::Func(f) => Some(f),
_ => None,
})
})
}

// todo: math scope
fn resolve_global(ctx: &AnalysisContext, callee: LinkedNode) -> Option<Value> {
pub(crate) fn resolve_global_value(
ctx: &AnalysisContext,
callee: LinkedNode,
is_math: bool,
) -> Option<Value> {
let lib = ctx.world().library();
let scope = if is_math {
lib.math.scope()
} else {
lib.global.scope()
};
let v = match callee.cast::<ast::Expr>()? {
ast::Expr::Ident(ident) => lib.global.scope().get(&ident)?,
ast::Expr::Ident(ident) => scope.get(&ident)?,
ast::Expr::FieldAccess(access) => match access.target() {
ast::Expr::Ident(target) => match lib.global.scope().get(&target)? {
ast::Expr::Ident(target) => match scope.get(&target)? {
Value::Module(module) => module.field(&access.field()).ok()?,
Value::Func(func) => func.field(&access.field()).ok()?,
_ => return None,
Expand Down
Loading