use std::cell::RefCell;
use oxc_ast::ast::{Argument, CallExpression, Class, Expression, IdentifierReference};
use oxc_semantic::{Semantic, SymbolId};
use rustc_hash::{FxHashMap, FxHashSet};
use fallow_types::extract::{ImportInfo, ImportedName};
#[path = "effect_schema_names.rs"]
mod names;
use names::{
DATA_FIRST_ARITY, HTTP_API_PIPE_TRANSFORMS, LOWERCASE_SCHEMA_CONSTRUCTORS,
NON_SCHEMA_VALUE_NAMES, PIPE_TRANSFORMS, TYPE_ONLY_NAMES,
};
#[path = "effect_schema_helpers.rs"]
mod helpers;
#[path = "effect_schema_containers.rs"]
mod containers;
const CLASS_FACTORIES: &[&str] = &[
"Class",
"Error",
"Opaque",
"TaggedClass",
"TaggedError",
"TaggedRequest",
];
const PIPE_CONSTRUCTORS: &[&str] = &[
"Array",
"NonEmptyArray",
"NullOr",
"NullishOr",
"UndefinedOr",
];
const SCHEMA_METHODS: &[&str] = &[
"annotate",
"annotateKey",
"annotations",
"brand",
"check",
"extend",
"mapFields",
"mapMembers",
"omit",
"pick",
"pipe",
"rename",
];
fn is_schema_module_import(import: &ImportInfo) -> bool {
match &import.imported_name {
ImportedName::Named(name) => {
name == "Schema" && matches!(import.source.as_str(), "effect" | "@effect/schema")
}
ImportedName::Namespace => {
matches!(
import.source.as_str(),
"effect/Schema" | "@effect/schema/Schema"
)
}
ImportedName::Default | ImportedName::SideEffect => false,
}
}
fn is_http_api_schema_module_import(import: &ImportInfo) -> bool {
match &import.imported_name {
ImportedName::Named(name) => {
name == "HttpApiSchema"
&& matches!(
import.source.as_str(),
"effect/http-api" | "@effect/platform"
)
}
ImportedName::Namespace => {
matches!(
import.source.as_str(),
"effect/http-api/HttpApiSchema" | "@effect/platform/HttpApiSchema"
)
}
ImportedName::Default | ImportedName::SideEffect => false,
}
}
fn is_schema_constructor(name: &str) -> bool {
if name.starts_with(|c: char| c.is_ascii_uppercase()) {
return !TYPE_ONLY_NAMES.contains(&name) && !NON_SCHEMA_VALUE_NAMES.contains(&name);
}
LOWERCASE_SCHEMA_CONSTRUCTORS.contains(&name)
}
fn is_schema_giving_call(member: &str, next: Option<&Link<'_, '_>>) -> bool {
let Some(Link::Call(call)) = next else {
return false;
};
let Some(&(_, arity)) = DATA_FIRST_ARITY.iter().find(|(name, _)| *name == member) else {
return true;
};
call.arguments.len() >= arity
|| call
.arguments
.iter()
.any(|argument| matches!(argument, Argument::SpreadElement(_)))
}
fn is_class_factory(name: &str) -> bool {
CLASS_FACTORIES.contains(&name)
}
fn is_pipe_call(callee: &Expression<'_>) -> bool {
matches!(
unwrap(callee),
Expression::StaticMemberExpression(member) if member.property.name == "pipe"
)
}
fn unwrap<'e, 'a>(expression: &'e Expression<'a>) -> &'e Expression<'a> {
let mut current = expression.without_parentheses();
loop {
current = match current {
Expression::TSAsExpression(node) => node.expression.without_parentheses(),
Expression::TSSatisfiesExpression(node) => node.expression.without_parentheses(),
Expression::TSNonNullExpression(node) => node.expression.without_parentheses(),
Expression::TSInstantiationExpression(node) => node.expression.without_parentheses(),
_ => return current,
};
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchemaShape {
Known,
Derived {
import_local: String,
through_call: bool,
member: Option<String>,
},
}
impl SchemaShape {
fn join(self, other: Self) -> Option<Self> {
match (self, other) {
(Self::Known, shape) | (shape, Self::Known) => Some(shape),
(left, right) => (left == right).then_some(left),
}
}
}
enum Link<'e, 'a> {
Member(&'e str),
Key(String),
Call(&'e CallExpression<'a>),
}
fn is_schema_tail(links: &[Link<'_, '_>]) -> bool {
links.iter().enumerate().all(|(index, link)| match link {
Link::Member(name) => {
SCHEMA_METHODS.contains(name) && matches!(links.get(index + 1), Some(Link::Call(_)))
}
Link::Key(_) => false,
Link::Call(_) => true,
})
}
fn literal_key(expression: &Expression<'_>) -> Option<String> {
match unwrap(expression) {
Expression::StringLiteral(literal) => literal.value.as_str().map(str::to_string),
Expression::NumericLiteral(literal)
if (0.0..1e21).contains(&literal.value) && literal.value.fract() == 0.0 =>
{
Some(format!("{}", literal.value))
}
_ => None,
}
}
pub struct SchemaShapes<'s, 'a> {
semantic: &'s Semantic<'a>,
namespaces: FxHashSet<SymbolId>,
http_api_namespaces: FxHashSet<SymbolId>,
imports: FxHashMap<SymbolId, String>,
namespace_imports: FxHashMap<SymbolId, String>,
locals: FxHashMap<SymbolId, SchemaShape>,
local_names: FxHashMap<String, SchemaShape>,
helpers: RefCell<FxHashMap<SymbolId, helpers::HelperResult>>,
helper_locals: RefCell<FxHashMap<SymbolId, SchemaShape>>,
in_progress: RefCell<FxHashSet<u32>>,
containers: RefCell<FxHashMap<SymbolId, bool>>,
}
impl<'s, 'a> SchemaShapes<'s, 'a> {
pub fn new(semantic: &'s Semantic<'a>, imports: &[ImportInfo]) -> Self {
let namespaces = imports
.iter()
.filter(|import| is_schema_module_import(import))
.filter_map(|import| {
crate::binding_references::admitted_import_symbol(semantic, import)
})
.collect();
let http_api_namespaces = imports
.iter()
.filter(|import| is_http_api_schema_module_import(import))
.filter_map(|import| {
crate::binding_references::admitted_import_symbol(semantic, import)
})
.collect();
let namespace_imports = imports
.iter()
.filter(|import| {
!import.is_type_only
&& import.imported_name == ImportedName::Namespace
&& !is_schema_module_import(import)
&& !is_http_api_schema_module_import(import)
})
.filter_map(|import| {
crate::binding_references::admitted_import_symbol(semantic, import)
.map(|symbol| (symbol, import.local_name.clone()))
})
.collect();
let imports = imports
.iter()
.filter(|import| {
!import.is_type_only
&& matches!(
import.imported_name,
ImportedName::Named(_) | ImportedName::Default
)
&& !is_schema_module_import(import)
&& !is_http_api_schema_module_import(import)
})
.filter_map(|import| {
crate::binding_references::admitted_import_symbol(semantic, import)
.map(|symbol| (symbol, import.local_name.clone()))
})
.collect();
Self {
semantic,
namespaces,
http_api_namespaces,
imports,
namespace_imports,
locals: FxHashMap::default(),
local_names: FxHashMap::default(),
helpers: RefCell::new(FxHashMap::default()),
helper_locals: RefCell::new(FxHashMap::default()),
in_progress: RefCell::new(FxHashSet::default()),
containers: RefCell::new(FxHashMap::default()),
}
}
pub fn record(&mut self, symbol: SymbolId, name: &str, shape: SchemaShape) {
if self.semantic.scoping().symbol_is_mutated(symbol) {
return;
}
self.locals.insert(symbol, shape.clone());
self.local_names.insert(name.to_string(), shape);
}
pub fn name_shape(&self, name: &str) -> Option<&SchemaShape> {
self.local_names.get(name)
}
pub fn class_shape(&self, class: &Class<'a>) -> Option<SchemaShape> {
class
.heritage
.as_ref()
.and_then(|heritage| self.schema_chain(&heritage.expression, is_class_factory))
}
pub fn expression_shape(&self, expression: &Expression<'a>) -> Option<SchemaShape> {
if let Expression::ConditionalExpression(conditional) = unwrap(expression) {
let consequent = self.expression_shape(&conditional.consequent)?;
return consequent.join(self.expression_shape(&conditional.alternate)?);
}
self.schema_chain(expression, is_schema_constructor)
}
fn schema_chain(
&self,
expression: &Expression<'a>,
accepts_head: fn(&str) -> bool,
) -> Option<SchemaShape> {
if self.namespaces.is_empty()
&& self.imports.is_empty()
&& self.namespace_imports.is_empty()
{
return None;
}
let (root, links) = self.flatten(expression)?;
let symbol = self.symbol(root)?;
if self.namespaces.contains(&symbol) {
let Some((Link::Member(head), rest)) = links.split_first() else {
return None;
};
if head.starts_with(|c: char| c.is_ascii_lowercase())
&& !is_schema_giving_call(head, rest.first())
{
return None;
}
return (accepts_head(head) && is_schema_tail(rest)).then_some(SchemaShape::Known);
}
if let Some(local) = self.namespace_imports.get(&symbol) {
return namespace_member_shape(local, &links);
}
if self.is_container(symbol) {
return self.container_chain(symbol, &links);
}
if !is_schema_tail(&links) {
return None;
}
if let Some(shape) = self.locals.get(&symbol) {
return Some(shape.clone());
}
if let Some(shape) = self.helper_locals.borrow().get(&symbol) {
return Some(shape.clone());
}
let root_calls = links
.iter()
.take_while(|link| matches!(link, Link::Call(_)))
.count();
if let Some(local) = self.imports.get(&symbol) {
return Some(SchemaShape::Derived {
import_local: local.clone(),
through_call: root_calls == 1,
member: None,
});
}
match links.first() {
Some(Link::Call(call)) if root_calls == 1 => {
self.helper_call_shape(symbol, &call.arguments)
}
_ => None,
}
}
fn flatten<'e>(
&self,
expression: &'e Expression<'a>,
) -> Option<(&'e IdentifierReference<'a>, Vec<Link<'e, 'a>>)> {
let mut links = Vec::new();
let mut current = expression;
let root = loop {
current = match unwrap(current) {
Expression::CallExpression(call) => {
if is_pipe_call(&call.callee)
&& !call
.arguments
.iter()
.all(|argument| self.is_pipe_transform(argument))
{
return None;
}
links.push(Link::Call(call));
&call.callee
}
Expression::StaticMemberExpression(member) => {
links.push(Link::Member(member.property.name.as_str()));
&member.object
}
Expression::ComputedMemberExpression(member) => {
links.push(Link::Key(literal_key(&member.expression)?));
&member.object
}
Expression::Identifier(identifier) => break identifier,
_ => return None,
};
};
links.reverse();
Some((root, links))
}
fn is_pipe_transform(&self, argument: &Argument<'a>) -> bool {
let Some(expression) = argument.as_expression() else {
return false;
};
let (callee, called) = match unwrap(expression) {
Expression::CallExpression(call) => (unwrap(&call.callee), true),
other => (other, false),
};
let Expression::StaticMemberExpression(member) = callee else {
return false;
};
let Expression::Identifier(object) = unwrap(&member.object) else {
return false;
};
let name = member.property.name.as_str();
let Some(symbol) = self.symbol(object) else {
return false;
};
if self.http_api_namespaces.contains(&symbol) {
return called && HTTP_API_PIPE_TRANSFORMS.contains(&name);
}
let known =
PIPE_TRANSFORMS.contains(&name) || (!called && PIPE_CONSTRUCTORS.contains(&name));
known && self.namespaces.contains(&symbol)
}
fn guarded<T>(&self, key: u32, inspect: impl FnOnce() -> Option<T>) -> Option<T> {
if self.in_progress.borrow().len() >= helpers::MAX_HELPER_DEPTH
|| !self.in_progress.borrow_mut().insert(key)
{
return None;
}
let result = inspect();
self.in_progress.borrow_mut().remove(&key);
result
}
fn symbol(&self, identifier: &IdentifierReference<'a>) -> Option<SymbolId> {
let reference = identifier.reference_id.get()?;
self.semantic.scoping().get_reference(reference).symbol_id()
}
}
fn namespace_member_shape(local: &str, links: &[Link<'_, '_>]) -> Option<SchemaShape> {
let Some((Link::Member(member), rest)) = links.split_first() else {
return None;
};
let (through_call, rest) = match rest.split_first() {
Some((Link::Call(_), tail)) => (true, tail),
_ => (false, rest),
};
if matches!(rest.first(), Some(Link::Call(_))) || !is_schema_tail(rest) {
return None;
}
Some(SchemaShape::Derived {
import_local: local.to_string(),
through_call,
member: Some((*member).to_string()),
})
}