use ecow::EcoString;
use crate::program::{CalleeName, DotAccessResolution, MethodName};
use crate::types;
use crate::types::{Symbol, Type};
use fmt::Formatter;
use std::borrow::Cow;
use std::fmt;
use std::fmt::Display;
use std::iter;
use std::mem;
use std::ops::Deref;
use std::ops::DerefMut;
use std::ops::Index;
use std::ptr;
use std::slice::Iter;
use std::slice::IterMut;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeadCodeCause {
Return,
Break,
Continue,
DivergingIf,
DivergingMatch,
InfiniteLoop,
DivergingCall,
}
#[derive(Clone, PartialEq)]
pub struct Binding {
pub pattern: Pattern,
pub annotation: Option<Annotation>,
pub ty: Type,
pub mut_span: Option<Span>,
}
impl Binding {
pub fn is_mutable(&self) -> bool {
self.mut_span.is_some()
}
}
impl fmt::Debug for Binding {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut s = f.debug_struct("Binding");
s.field("pattern", &self.pattern);
s.field("annotation", &self.annotation);
s.field("ty", &self.ty);
if self.mut_span.is_some() {
s.field("mut_span", &self.mut_span);
}
s.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct BindingId(u32);
impl BindingId {
pub const fn new(index: u32) -> Self {
Self(index)
}
pub const fn index(self) -> u32 {
self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IdentifierResolution {
Unresolved,
Binding(BindingId),
Definition {
name: Symbol,
instantiation: types::SubstitutionMap,
},
Method {
method: MethodName,
instantiation: types::SubstitutionMap,
},
}
impl IdentifierResolution {
pub fn binding_id(&self) -> Option<BindingId> {
match self {
Self::Binding(id) => Some(*id),
Self::Unresolved | Self::Definition { .. } | Self::Method { .. } => None,
}
}
pub fn definition(&self) -> Option<&str> {
match self {
Self::Definition { name, .. } => Some(name),
Self::Unresolved | Self::Binding(_) | Self::Method { .. } => None,
}
}
pub fn method(&self) -> Option<&MethodName> {
match self {
Self::Method { method, .. } => Some(method),
Self::Unresolved | Self::Binding(_) | Self::Definition { .. } => None,
}
}
pub fn callee_name(&self) -> Option<CalleeName> {
match self {
Self::Definition { name, .. } => Some(CalleeName::Definition(name.clone())),
Self::Method { method, .. } => Some(CalleeName::Method(method.clone())),
Self::Unresolved | Self::Binding(_) => None,
}
}
pub fn instantiation(&self) -> Option<&types::SubstitutionMap> {
match self {
Self::Definition { instantiation, .. } | Self::Method { instantiation, .. } => {
Some(instantiation)
}
Self::Unresolved | Self::Binding(_) => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum LetMode {
Plain,
Assert,
Else {
block: Box<Expression>,
else_span: Span,
},
InvalidAssertElse {
block: Box<Expression>,
else_span: Span,
},
}
impl LetMode {
pub fn is_assert(&self) -> bool {
matches!(self, Self::Assert | Self::InvalidAssertElse { .. })
}
pub fn else_block(&self) -> Option<&Expression> {
match self {
Self::Else { block, .. } | Self::InvalidAssertElse { block, .. } => Some(block),
Self::Plain | Self::Assert => None,
}
}
pub fn else_block_mut(&mut self) -> Option<&mut Expression> {
match self {
Self::Else { block, .. } | Self::InvalidAssertElse { block, .. } => Some(block),
Self::Plain | Self::Assert => None,
}
}
pub fn map_else(self, map: impl FnOnce(Expression, Span) -> Expression) -> Self {
match self {
Self::Else { block, else_span } => Self::Else {
block: Box::new(map(*block, else_span)),
else_span,
},
Self::InvalidAssertElse { block, else_span } => Self::InvalidAssertElse {
block: Box::new(map(*block, else_span)),
else_span,
},
Self::Plain => Self::Plain,
Self::Assert => Self::Assert,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum FunctionBody {
Declaration,
Definition(Box<Expression>),
}
impl FunctionBody {
pub fn definition(&self) -> Option<&Expression> {
match self {
Self::Declaration => None,
Self::Definition(body) => Some(body),
}
}
pub fn definition_mut(&mut self) -> Option<&mut Expression> {
match self {
Self::Declaration => None,
Self::Definition(body) => Some(body),
}
}
pub fn map_definition(self, map: impl FnOnce(Expression) -> Expression) -> Self {
match self {
Self::Declaration => Self::Declaration,
Self::Definition(body) => Self::Definition(Box::new(map(*body))),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ConstInitializer {
Declaration,
Value(Box<Expression>),
}
#[derive(Debug, Clone, PartialEq)]
pub enum IfLetAlternative {
Absent,
Present {
expression: Box<Expression>,
else_span: Span,
},
}
impl IfLetAlternative {
pub fn expression(&self) -> Option<&Expression> {
match self {
Self::Absent => None,
Self::Present { expression, .. } => Some(expression),
}
}
pub fn expression_mut(&mut self) -> Option<&mut Expression> {
match self {
Self::Absent => None,
Self::Present { expression, .. } => Some(expression),
}
}
pub fn else_span(&self) -> Option<Span> {
match self {
Self::Absent => None,
Self::Present { else_span, .. } => Some(*else_span),
}
}
}
impl ConstInitializer {
pub fn value(&self) -> Option<&Expression> {
match self {
Self::Declaration => None,
Self::Value(value) => Some(value),
}
}
pub fn value_mut(&mut self) -> Option<&mut Expression> {
match self {
Self::Declaration => None,
Self::Value(value) => Some(value),
}
}
pub fn map_value(self, map: impl FnOnce(Expression) -> Expression) -> Self {
match self {
Self::Declaration => Self::Declaration,
Self::Value(value) => Self::Value(Box::new(map(*value))),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BindingKind {
Const,
Let { mutable: bool },
Parameter,
MatchArm,
IfLet,
WhileLet,
}
impl BindingKind {
pub fn is_mutable(&self) -> bool {
matches!(self, BindingKind::Let { mutable: true })
}
pub fn is_param(&self) -> bool {
matches!(self, BindingKind::Parameter)
}
pub fn is_match_arm(&self) -> bool {
matches!(self, BindingKind::MatchArm)
}
pub fn is_pattern_position(&self) -> bool {
matches!(
self,
BindingKind::MatchArm | BindingKind::IfLet | BindingKind::WhileLet
)
}
}
#[derive(Clone, PartialEq)]
pub struct MatchArm {
pub pattern: Pattern,
pub guard: Option<Box<Expression>>,
pub expression: Box<Expression>,
}
impl MatchArm {
pub fn has_guard(&self) -> bool {
self.guard.is_some()
}
fn pattern_site(&self) -> PatternSite {
PatternSite::MatchArm {
has_guard: self.has_guard(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PatternSite {
Parameter,
Binding,
MatchArm { has_guard: bool },
}
impl fmt::Debug for MatchArm {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut s = f.debug_struct("MatchArm");
s.field("pattern", &self.pattern);
if self.guard.is_some() {
s.field("guard", &self.guard);
}
s.field("expression", &self.expression);
s.finish()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum SelectArm {
Receive {
binding: Box<Pattern>,
receive_expression: Box<Expression>,
body: Box<Expression>,
},
Send {
send_expression: Box<Expression>,
body: Box<Expression>,
},
MatchReceive {
receive_expression: Box<Expression>,
arms: Vec<MatchArm>,
},
WildCard {
span: Span,
body: Box<Expression>,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum RestPattern {
Absent,
Discard(Span),
Bind {
name: EcoString,
span: Span,
binding: Option<BindingId>,
},
}
impl RestPattern {
pub fn binding_id(&self) -> Option<BindingId> {
match self {
Self::Bind { binding, .. } => *binding,
Self::Absent | Self::Discard(_) => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ConstructorPatternResolution {
Unresolved,
Const {
qualified_name: Symbol,
},
ConstValue {
qualified_name: Symbol,
value: Literal,
},
EnumVariant {
enum_name: Symbol,
variant_name: EcoString,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum RecordPatternResolution {
Unresolved,
Struct {
struct_name: EcoString,
},
EnumVariant {
enum_name: Symbol,
variant_name: EcoString,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum SequencePatternResolution {
Unresolved,
Slice { element_type: Type },
Array { element_type: Type, length: u64 },
}
impl RestPattern {
pub fn is_present(&self) -> bool {
!matches!(self, RestPattern::Absent)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Pattern {
Literal {
literal: Literal,
ty: Type,
span: Span,
},
Unit {
ty: Type,
span: Span,
},
EnumVariant {
identifier: EcoString,
fields: Vec<Self>,
rest: bool,
resolution: ConstructorPatternResolution,
ty: Type,
span: Span,
},
Struct {
identifier: EcoString,
fields: Vec<StructFieldPattern>,
rest: bool,
resolution: RecordPatternResolution,
ty: Type,
span: Span,
},
Tuple {
elements: Vec<Self>,
span: Span,
},
WildCard {
span: Span,
},
Identifier {
identifier: EcoString,
span: Span,
binding: Option<BindingId>,
},
Slice {
prefix: Vec<Self>,
rest: RestPattern,
resolution: SequencePatternResolution,
span: Span,
},
Or {
patterns: Vec<Self>,
span: Span,
},
AsBinding {
pattern: Box<Self>,
name: EcoString,
name_span: Span,
span: Span,
binding: Option<BindingId>,
},
}
pub fn collect_pattern_bindings(pattern: &Pattern) -> Vec<(String, Span)> {
match pattern {
Pattern::Identifier {
identifier, span, ..
} => vec![(identifier.to_string(), *span)],
Pattern::Tuple { elements, .. } => {
elements.iter().flat_map(collect_pattern_bindings).collect()
}
Pattern::EnumVariant { fields, .. } => {
fields.iter().flat_map(collect_pattern_bindings).collect()
}
Pattern::Struct { fields, .. } => fields
.iter()
.flat_map(|f| collect_pattern_bindings(&f.value))
.collect(),
Pattern::Slice { prefix, rest, .. } => {
let mut bindings: Vec<_> = prefix.iter().flat_map(collect_pattern_bindings).collect();
if let RestPattern::Bind { name, span, .. } = rest {
bindings.push((name.to_string(), *span));
}
bindings
}
Pattern::Or { patterns, .. } => patterns
.first()
.map(collect_pattern_bindings)
.unwrap_or_default(),
Pattern::AsBinding {
pattern,
name,
name_span,
..
} => {
let mut bindings = collect_pattern_bindings(pattern);
bindings.push((name.to_string(), *name_span));
bindings
}
Pattern::WildCard { .. } | Pattern::Literal { .. } | Pattern::Unit { .. } => vec![],
}
}
pub fn outermost_or_patterns(pattern: &Pattern) -> Vec<&Pattern> {
match pattern {
Pattern::Or { .. } => vec![pattern],
Pattern::Tuple {
elements: patterns, ..
}
| Pattern::EnumVariant {
fields: patterns, ..
}
| Pattern::Slice {
prefix: patterns, ..
} => patterns.iter().flat_map(outermost_or_patterns).collect(),
Pattern::Struct { fields, .. } => fields
.iter()
.flat_map(|field| outermost_or_patterns(&field.value))
.collect(),
Pattern::AsBinding { pattern, .. } => outermost_or_patterns(pattern),
Pattern::Identifier { .. }
| Pattern::WildCard { .. }
| Pattern::Literal { .. }
| Pattern::Unit { .. } => vec![],
}
}
#[derive(Debug, Clone)]
pub struct OrExpansion<'a> {
pub pattern: Cow<'a, Pattern>,
pub choices: Vec<OrChoice>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OrChoice {
pub or_span: Span,
pub alternative_span: Span,
}
pub fn expand_or_patterns<'a>(
pattern: &'a Pattern,
split: &impl Fn(&Pattern) -> bool,
) -> Vec<OrExpansion<'a>> {
match pattern {
Pattern::Or { patterns, span } if split(pattern) => patterns
.iter()
.flat_map(|alternative| {
let choice = OrChoice {
or_span: *span,
alternative_span: alternative.get_span(),
};
expand_or_patterns(alternative, split)
.into_iter()
.map(move |mut expansion| {
expansion.choices.insert(0, choice);
expansion
})
})
.collect(),
Pattern::AsBinding {
pattern: inner,
name,
name_span,
span,
binding,
} => expand_children(pattern, iter::once(inner.as_ref()), split, |mut inner| {
Pattern::AsBinding {
pattern: Box::new(inner.remove(0)),
name: name.clone(),
name_span: *name_span,
span: *span,
binding: *binding,
}
}),
Pattern::Tuple { elements, span } => {
expand_children(pattern, elements.iter(), split, |elements| Pattern::Tuple {
elements,
span: *span,
})
}
Pattern::EnumVariant {
identifier,
fields,
rest,
resolution,
ty,
span,
} => expand_children(pattern, fields.iter(), split, |fields| {
Pattern::EnumVariant {
identifier: identifier.clone(),
fields,
rest: *rest,
resolution: resolution.clone(),
ty: ty.clone(),
span: *span,
}
}),
Pattern::Struct {
identifier,
fields,
rest,
resolution,
ty,
span,
} => expand_children(
pattern,
fields.iter().map(|field| &field.value),
split,
|values| Pattern::Struct {
identifier: identifier.clone(),
fields: fields
.iter()
.zip(values)
.map(|(field, value)| StructFieldPattern {
name: field.name.clone(),
name_span: field.name_span,
value,
})
.collect(),
rest: *rest,
resolution: resolution.clone(),
ty: ty.clone(),
span: *span,
},
),
Pattern::Slice {
prefix,
rest,
resolution,
span,
} => expand_children(pattern, prefix.iter(), split, |prefix| Pattern::Slice {
prefix,
rest: rest.clone(),
resolution: resolution.clone(),
span: *span,
}),
Pattern::Or { .. }
| Pattern::Identifier { .. }
| Pattern::WildCard { .. }
| Pattern::Literal { .. }
| Pattern::Unit { .. } => unexpanded(pattern),
}
}
fn unexpanded(pattern: &Pattern) -> Vec<OrExpansion<'_>> {
vec![OrExpansion {
pattern: Cow::Borrowed(pattern),
choices: vec![],
}]
}
fn expand_children<'a>(
pattern: &'a Pattern,
children: impl Iterator<Item = &'a Pattern>,
split: &impl Fn(&Pattern) -> bool,
rebuild: impl Fn(Vec<Pattern>) -> Pattern,
) -> Vec<OrExpansion<'a>> {
let child_expansions: Vec<Vec<OrExpansion<'a>>> = children
.map(|child| expand_or_patterns(child, split))
.collect();
if child_expansions
.iter()
.flatten()
.all(|expansion| expansion.choices.is_empty())
{
return unexpanded(pattern);
}
let mut combinations: Vec<(Vec<Pattern>, Vec<OrChoice>)> = vec![(vec![], vec![])];
for expansions in &child_expansions {
combinations = combinations
.into_iter()
.flat_map(|(children, choices)| {
expansions.iter().map(move |expansion| {
let mut children = children.clone();
children.push(expansion.pattern.as_ref().clone());
let mut choices = choices.clone();
choices.extend_from_slice(&expansion.choices);
(children, choices)
})
})
.collect();
}
combinations
.into_iter()
.map(|(children, choices)| OrExpansion {
pattern: Cow::Owned(rebuild(children)),
choices,
})
.collect()
}
impl Pattern {
pub fn get_span(&self) -> Span {
match self {
Pattern::Identifier { span, .. } => *span,
Pattern::Literal { span, .. } => *span,
Pattern::EnumVariant { span, .. } => *span,
Pattern::Struct { span, .. } => *span,
Pattern::WildCard { span } => *span,
Pattern::Unit { span, .. } => *span,
Pattern::Tuple { span, .. } => *span,
Pattern::Slice { span, .. } => *span,
Pattern::Or { span, .. } => *span,
Pattern::AsBinding { span, .. } => *span,
}
}
pub fn get_type(&self) -> Option<Type> {
match self {
Pattern::Identifier { .. } => None,
Pattern::Literal { ty, .. } => Some(ty.clone()),
Pattern::EnumVariant { ty, .. } => Some(ty.clone()),
Pattern::Struct { ty, .. } => Some(ty.clone()),
Pattern::WildCard { .. } => None,
Pattern::Unit { ty, .. } => Some(ty.clone()),
Pattern::Tuple { .. } => None,
Pattern::Slice { .. } => None,
Pattern::Or { .. } => None,
Pattern::AsBinding { pattern, .. } => pattern.get_type(),
}
}
pub fn is_identifier(&self) -> bool {
matches!(self, Pattern::Identifier { .. } | Pattern::AsBinding { .. })
}
pub fn binding_id(&self) -> Option<BindingId> {
match self {
Pattern::Identifier { binding, .. } | Pattern::AsBinding { binding, .. } => *binding,
_ => None,
}
}
pub fn get_identifier(&self) -> Option<EcoString> {
match self {
Pattern::Identifier { identifier, .. } => Some(identifier.clone()),
Pattern::AsBinding { name, .. } => Some(name.clone()),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct StructFieldPattern {
pub name: EcoString,
pub name_span: Span,
pub value: Pattern,
}
impl StructFieldPattern {
pub fn is_shorthand(&self) -> bool {
matches!(&self.value, Pattern::Identifier { identifier, .. } if identifier == &self.name)
}
}
#[derive(Clone, Copy)]
pub struct FunctionDefinitionView<'a> {
pub name: &'a EcoString,
pub name_span: Span,
pub generics: &'a [Generic],
pub params: &'a [Binding],
pub body: Option<&'a Expression>,
pub return_type: &'a Type,
pub annotation: &'a Annotation,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum VariantFields {
Unit,
Tuple(Vec<EnumFieldDefinition>),
Struct(Vec<EnumFieldDefinition>),
}
impl VariantFields {
pub fn is_empty(&self) -> bool {
match self {
VariantFields::Unit => true,
VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.is_empty(),
}
}
pub fn len(&self) -> usize {
match self {
VariantFields::Unit => 0,
VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields.len(),
}
}
pub fn as_slice(&self) -> &[EnumFieldDefinition] {
match self {
VariantFields::Unit => &[],
VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields,
}
}
pub fn iter(&self) -> Iter<'_, EnumFieldDefinition> {
self.as_slice().iter()
}
pub fn is_struct(&self) -> bool {
matches!(self, VariantFields::Struct(_))
}
}
impl<'a> IntoIterator for &'a VariantFields {
type Item = &'a EnumFieldDefinition;
type IntoIter = Iter<'a, EnumFieldDefinition>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EnumVariant {
pub doc: Option<String>,
pub attributes: Vec<Attribute>,
pub name: EcoString,
pub name_span: Span,
pub fields: VariantFields,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EnumFieldDefinition {
pub name: EcoString,
pub name_span: Span,
pub annotation: Annotation,
pub ty: Type,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Attribute {
pub name: String,
pub args: Vec<AttributeArg>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AttributeArg {
Flag(String),
NegatedFlag(String),
String(String),
Raw(String),
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum StructKind {
Record,
Tuple,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum StructFields {
Record(Vec<StructFieldDefinition>),
Tuple(Vec<StructFieldDefinition>),
}
impl StructFields {
pub fn kind(&self) -> StructKind {
match self {
Self::Record(_) => StructKind::Record,
Self::Tuple(_) => StructKind::Tuple,
}
}
pub fn as_slice(&self) -> &[StructFieldDefinition] {
match self {
Self::Record(fields) | Self::Tuple(fields) => fields,
}
}
}
pub fn tuple_field_name(index: usize) -> EcoString {
format!("_{index}").into()
}
impl Deref for StructFields {
type Target = [StructFieldDefinition];
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl DerefMut for StructFields {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
Self::Record(fields) | Self::Tuple(fields) => fields,
}
}
}
impl<'a> IntoIterator for &'a StructFields {
type Item = &'a StructFieldDefinition;
type IntoIter = Iter<'a, StructFieldDefinition>;
fn into_iter(self) -> Self::IntoIter {
self.as_slice().iter()
}
}
impl<'a> IntoIterator for &'a mut StructFields {
type Item = &'a mut StructFieldDefinition;
type IntoIter = IterMut<'a, StructFieldDefinition>;
fn into_iter(self) -> Self::IntoIter {
match self {
StructFields::Record(fields) | StructFields::Tuple(fields) => fields.iter_mut(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StructFieldDefinition {
pub doc: Option<String>,
pub name: EcoString,
pub name_span: Span,
pub annotation: Annotation,
pub visibility: Visibility,
pub ty: Type,
pub kind: StructFieldKind,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum StructFieldKind {
Named { attributes: Vec<Attribute> },
Embedded,
}
impl StructFieldDefinition {
pub fn attributes(&self) -> &[Attribute] {
match &self.kind {
StructFieldKind::Named { attributes } => attributes,
StructFieldKind::Embedded => &[],
}
}
pub fn is_embedded(&self) -> bool {
matches!(self.kind, StructFieldKind::Embedded)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct StructFieldAssignment {
pub name: EcoString,
pub name_span: Span,
pub value: Box<Expression>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum StructSpread {
None,
From(Box<Expression>),
Autofill { span: Span },
}
impl StructSpread {
pub fn is_none(&self) -> bool {
matches!(self, Self::None)
}
pub(crate) fn is_some(&self) -> bool {
!self.is_none()
}
pub fn span(&self) -> Option<Span> {
match self {
Self::None => None,
Self::From(e) => Some(e.get_span()),
Self::Autofill { span } => Some(*span),
}
}
pub fn as_expression(&self) -> Option<&Expression> {
match self {
Self::From(e) => Some(e),
Self::None | Self::Autofill { .. } => None,
}
}
pub fn as_expression_mut(&mut self) -> Option<&mut Expression> {
match self {
Self::From(e) => Some(e),
Self::None | Self::Autofill { .. } => None,
}
}
}
#[derive(Clone, PartialEq)]
pub struct CallTypeArguments(CallTypeArgumentState);
#[derive(Clone, PartialEq)]
enum CallTypeArgumentState {
None,
Unresolved(Vec<Annotation>),
Resolved(Vec<ResolvedCallTypeArgument>),
CheckedWithoutTypes(Vec<Annotation>),
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
struct ResolvedCallTypeArgument {
annotation: Annotation,
ty: Type,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ResolvedCallTypeArguments<'a> {
arguments: &'a [ResolvedCallTypeArgument],
}
impl<'a> ResolvedCallTypeArguments<'a> {
pub fn len(self) -> usize {
self.arguments.len()
}
pub fn is_empty(self) -> bool {
self.arguments.is_empty()
}
pub fn first(self) -> Option<&'a Type> {
self.arguments.first().map(|argument| &argument.ty)
}
pub fn get(self, index: usize) -> Option<&'a Type> {
self.arguments.get(index).map(|argument| &argument.ty)
}
pub fn iter(self) -> impl ExactSizeIterator<Item = &'a Type> + Clone {
self.arguments.iter().map(|argument| &argument.ty)
}
}
impl Index<usize> for ResolvedCallTypeArguments<'_> {
type Output = Type;
fn index(&self, index: usize) -> &Self::Output {
&self.arguments[index].ty
}
}
impl fmt::Debug for CallTypeArguments {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match &self.0 {
CallTypeArgumentState::None => f.write_str("None"),
CallTypeArgumentState::Unresolved(annotations) => {
f.debug_tuple("Unresolved").field(annotations).finish()
}
CallTypeArgumentState::Resolved(arguments) => {
let annotations = arguments
.iter()
.map(|argument| &argument.annotation)
.collect::<Vec<_>>();
let types = arguments
.iter()
.map(|argument| &argument.ty)
.collect::<Vec<_>>();
f.debug_struct("Resolved")
.field("annotations", &annotations)
.field("types", &types)
.finish()
}
CallTypeArgumentState::CheckedWithoutTypes(annotations) => f
.debug_struct("Resolved")
.field("annotations", annotations)
.field("types", &Vec::<Type>::new())
.finish(),
}
}
}
impl CallTypeArguments {
pub const fn none() -> Self {
Self(CallTypeArgumentState::None)
}
pub fn unresolved(annotations: Vec<Annotation>) -> Self {
if annotations.is_empty() {
Self::none()
} else {
Self(CallTypeArgumentState::Unresolved(annotations))
}
}
pub fn resolved(arguments: impl IntoIterator<Item = (Annotation, Type)>) -> Self {
let arguments = arguments
.into_iter()
.map(|(annotation, ty)| ResolvedCallTypeArgument { annotation, ty })
.collect::<Vec<_>>();
if arguments.is_empty() {
Self::none()
} else {
Self(CallTypeArgumentState::Resolved(arguments))
}
}
pub fn checked_without_types(annotations: Vec<Annotation>) -> Self {
if annotations.is_empty() {
Self::none()
} else {
Self(CallTypeArgumentState::CheckedWithoutTypes(annotations))
}
}
pub fn annotations(
&self,
) -> impl ExactSizeIterator<Item = &Annotation> + DoubleEndedIterator + Clone {
let len = match &self.0 {
CallTypeArgumentState::None => 0,
CallTypeArgumentState::Unresolved(annotations)
| CallTypeArgumentState::CheckedWithoutTypes(annotations) => annotations.len(),
CallTypeArgumentState::Resolved(arguments) => arguments.len(),
};
(0..len).map(move |index| match &self.0 {
CallTypeArgumentState::None => unreachable!(),
CallTypeArgumentState::Unresolved(annotations)
| CallTypeArgumentState::CheckedWithoutTypes(annotations) => &annotations[index],
CallTypeArgumentState::Resolved(arguments) => &arguments[index].annotation,
})
}
pub fn resolved_types(&self) -> Option<ResolvedCallTypeArguments<'_>> {
let arguments: &[ResolvedCallTypeArgument] = match &self.0 {
CallTypeArgumentState::None | CallTypeArgumentState::CheckedWithoutTypes(_) => &[],
CallTypeArgumentState::Unresolved(_) => return None,
CallTypeArgumentState::Resolved(arguments) => arguments,
};
Some(ResolvedCallTypeArguments { arguments })
}
pub fn into_annotations(self) -> Vec<Annotation> {
match self.0 {
CallTypeArgumentState::None => Vec::new(),
CallTypeArgumentState::Unresolved(annotations)
| CallTypeArgumentState::CheckedWithoutTypes(annotations) => annotations,
CallTypeArgumentState::Resolved(arguments) => arguments
.into_iter()
.map(|argument| argument.annotation)
.collect(),
}
}
pub fn is_empty(&self) -> bool {
matches!(self.0, CallTypeArgumentState::None)
}
}
impl Default for CallTypeArguments {
fn default() -> Self {
Self::none()
}
}
#[derive(Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Annotation {
Constructor {
name: EcoString,
params: Vec<Self>,
writable: bool,
mut_span: Option<Span>,
span: Span,
},
Function {
params: Vec<Self>,
return_type: Box<Self>,
span: Span,
},
Tuple {
elements: Vec<Self>,
span: Span,
},
Unknown,
Opaque {
span: Span,
},
Constant {
value: u64,
text: Option<String>,
span: Span,
},
}
impl fmt::Debug for Annotation {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Constructor {
name,
params,
writable,
mut_span: _,
span,
} => {
let mut s = f.debug_struct("Constructor");
s.field("name", name).field("params", params);
if *writable {
s.field("writable", writable);
}
s.field("span", span).finish()
}
Self::Function {
params,
return_type,
span,
} => f
.debug_struct("Function")
.field("params", params)
.field("return_type", return_type)
.field("span", span)
.finish(),
Self::Tuple { elements, span } => f
.debug_struct("Tuple")
.field("elements", elements)
.field("span", span)
.finish(),
Self::Unknown => write!(f, "Unknown"),
Self::Opaque { span } => f.debug_struct("Opaque").field("span", span).finish(),
Self::Constant { value, text, span } => f
.debug_struct("Constant")
.field("value", value)
.field("text", text)
.field("span", span)
.finish(),
}
}
}
impl Annotation {
pub(crate) fn unit() -> Self {
Self::Constructor {
name: "Unit".into(),
params: vec![],
writable: false,
mut_span: None,
span: Span::dummy(),
}
}
pub fn get_span(&self) -> Span {
match self {
Self::Constructor { span, .. } => *span,
Self::Function { span, .. } => *span,
Self::Tuple { span, .. } => *span,
Self::Opaque { span } => *span,
Self::Constant { span, .. } => *span,
Self::Unknown => Span::dummy(),
}
}
pub fn get_name(&self) -> Option<String> {
match self {
Self::Constructor { name, .. } => Some(name.to_string()),
_ => None,
}
}
pub fn is_unknown(&self) -> bool {
matches!(self, Self::Unknown)
}
pub fn is_opaque(&self) -> bool {
matches!(self, Self::Opaque { .. })
}
}
#[derive(Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Generic {
pub name: EcoString,
bounds: GenericBounds,
pub span: Span,
}
impl fmt::Debug for Generic {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let bounds = self.bounds().collect::<Vec<_>>();
let resolved_bounds = self
.resolved_bounds()
.into_iter()
.flatten()
.collect::<Vec<_>>();
f.debug_struct("Generic")
.field("name", &self.name)
.field("bounds", &bounds)
.field("resolved_bounds", &resolved_bounds)
.field("span", &self.span)
.finish()
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
enum GenericBounds {
Unresolved(Vec<Annotation>),
Resolved(Vec<ResolvedGenericBound>),
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
struct ResolvedGenericBound {
annotation: Annotation,
ty: Type,
}
impl Generic {
pub fn new(name: impl Into<EcoString>, bounds: Vec<Annotation>, span: Span) -> Self {
let bounds = if bounds.is_empty() {
GenericBounds::Resolved(Vec::new())
} else {
GenericBounds::Unresolved(bounds)
};
Self {
name: name.into(),
bounds,
span,
}
}
pub fn resolved(
name: impl Into<EcoString>,
bounds: impl IntoIterator<Item = (Annotation, Type)>,
span: Span,
) -> Self {
Self {
name: name.into(),
bounds: GenericBounds::Resolved(
bounds
.into_iter()
.map(|(annotation, ty)| ResolvedGenericBound { annotation, ty })
.collect(),
),
span,
}
}
pub fn bounds(&self) -> impl Iterator<Item = &Annotation> + Clone {
let unresolved = match &self.bounds {
GenericBounds::Unresolved(bounds) => Some(bounds.as_slice()),
GenericBounds::Resolved(_) => None,
};
let resolved = match &self.bounds {
GenericBounds::Unresolved(_) => None,
GenericBounds::Resolved(bounds) => Some(bounds.as_slice()),
};
unresolved.into_iter().flatten().chain(
resolved
.into_iter()
.flatten()
.map(|bound| &bound.annotation),
)
}
pub fn bound_count(&self) -> usize {
match &self.bounds {
GenericBounds::Unresolved(bounds) => bounds.len(),
GenericBounds::Resolved(bounds) => bounds.len(),
}
}
pub fn bounds_are_resolved(&self) -> bool {
matches!(self.bounds, GenericBounds::Resolved(_))
}
pub fn resolved_bounds(&self) -> Option<impl Iterator<Item = &Type> + Clone> {
let GenericBounds::Resolved(bounds) = &self.bounds else {
return None;
};
Some(bounds.iter().map(|bound| &bound.ty))
}
pub fn for_each_bound_annotation_mut(&mut self, mut visit: impl FnMut(&mut Annotation)) {
match &mut self.bounds {
GenericBounds::Unresolved(annotations) => annotations.iter_mut().for_each(visit),
GenericBounds::Resolved(bounds) => {
bounds
.iter_mut()
.for_each(|bound| visit(&mut bound.annotation));
}
}
}
pub fn resolve_bounds_with(&mut self, mut resolve: impl FnMut(&Annotation) -> Type) {
let resolved = match &mut self.bounds {
GenericBounds::Unresolved(annotations) => annotations
.drain(..)
.map(|annotation| {
let ty = resolve(&annotation);
ResolvedGenericBound { annotation, ty }
})
.collect(),
GenericBounds::Resolved(bounds) => {
for bound in bounds {
bound.ty = resolve(&bound.annotation);
}
return;
}
};
self.bounds = GenericBounds::Resolved(resolved);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Span {
pub file_id: u32,
pub byte_offset: u32,
pub byte_length: u32,
}
impl Span {
pub fn new(file_id: u32, byte_offset: u32, byte_length: u32) -> Self {
Span {
file_id,
byte_offset,
byte_length,
}
}
pub fn dummy() -> Self {
Span {
file_id: u32::MAX,
byte_offset: 0,
byte_length: 0,
}
}
pub fn is_dummy(&self) -> bool {
self.file_id == u32::MAX
}
pub fn end(&self) -> u32 {
self.byte_offset + self.byte_length
}
pub fn contains(&self, inner: &Span) -> bool {
self.file_id == inner.file_id
&& self.byte_offset <= inner.byte_offset
&& inner.end() <= self.end()
}
pub fn merge(self, other: Span) -> Span {
assert_eq!(
self.file_id, other.file_id,
"cannot merge spans from different files"
);
let start = self.byte_offset.min(other.byte_offset);
let end = self.end().max(other.end());
Span::new(self.file_id, start, end - start)
}
pub fn after(self, prefix: Span) -> Span {
Span::new(self.file_id, prefix.end(), self.end() - prefix.end())
}
pub fn trailing(self, length: u32) -> Span {
let length = length.min(self.byte_length);
Span::new(self.file_id, self.end() - length, length)
}
pub fn trailing_name(self, source: &str, name: &str) -> Option<Span> {
let text = source.get(self.byte_offset as usize..self.end() as usize)?;
let trimmed = text.trim_end_matches(|c: char| c.is_whitespace() || c == ')');
let before = trimmed.strip_suffix(name)?;
if before.ends_with(|c: char| c.is_alphanumeric() || c == '_') {
return None;
}
Some(Span::new(
self.file_id,
self.byte_offset + before.len() as u32,
name.len() as u32,
))
}
pub fn name_segments(self, source: &str, name: &str) -> Option<Vec<Span>> {
let mut remaining = source.get(self.byte_offset as usize..self.end() as usize)?;
let mut offset = self.byte_offset as usize;
let mut segments = Vec::new();
for (index, segment) in name.split('.').enumerate() {
if index > 0 {
let trimmed = remaining.trim_start();
offset += remaining.len() - trimmed.len();
remaining = trimmed.strip_prefix('.')?;
offset += 1;
}
let trimmed = if index == 0 {
remaining.trim_start_matches(|c: char| c.is_whitespace() || c == '(')
} else {
remaining.trim_start()
};
offset += remaining.len() - trimmed.len();
remaining = trimmed.strip_prefix(segment)?;
if remaining.starts_with(|c: char| c.is_alphanumeric() || c == '_') {
return None;
}
segments.push(Span::new(self.file_id, offset as u32, segment.len() as u32));
offset += segment.len();
}
Some(segments)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ExpressionId {
file_id: u32,
index: u32,
}
impl ExpressionId {
pub fn file_id(&self) -> u32 {
self.file_id
}
pub fn parsed(file_id: u32, index: u32) -> Self {
Self { file_id, index }
}
pub fn generated(file_id: u32, index: u32) -> Self {
Self {
file_id,
index: u32::MAX - index,
}
}
}
impl fmt::Debug for ExpressionId {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(formatter, "ExpressionId({}:{})", self.file_id, self.index)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Expression {
Literal {
literal: Literal,
ty: Type,
span: Span,
id: ExpressionId,
},
Function {
doc: Option<String>,
attributes: Vec<Attribute>,
name: EcoString,
name_span: Span,
generics: Vec<Generic>,
params: Vec<Binding>,
return_annotation: Annotation,
return_type: Type,
visibility: Visibility,
body: FunctionBody,
ty: Type,
span: Span,
id: ExpressionId,
},
Lambda {
params: Vec<Binding>,
return_annotation: Annotation,
body: Box<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
Block {
items: Vec<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
Let {
binding: Box<Binding>,
value: Box<Expression>,
mode: LetMode,
ty: Type,
span: Span,
id: ExpressionId,
},
Identifier {
value: EcoString,
ty: Type,
span: Span,
resolution: IdentifierResolution,
id: ExpressionId,
},
Call {
expression: Box<Expression>,
args: Vec<Expression>,
spread: Option<Box<Expression>>,
type_arguments: CallTypeArguments,
ty: Type,
span: Span,
id: ExpressionId,
},
If {
condition: Box<Expression>,
consequence: Box<Expression>,
alternative: Option<Box<Expression>>,
ty: Type,
span: Span,
id: ExpressionId,
},
IfLet {
pattern: Pattern,
scrutinee: Box<Expression>,
consequence: Box<Expression>,
alternative: IfLetAlternative,
ty: Type,
span: Span,
id: ExpressionId,
},
Match {
subject: Box<Expression>,
arms: Vec<MatchArm>,
ty: Type,
span: Span,
id: ExpressionId,
},
Tuple {
elements: Vec<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
StructCall {
name: EcoString,
field_assignments: Vec<StructFieldAssignment>,
spread: StructSpread,
ty: Type,
span: Span,
id: ExpressionId,
},
DotAccess {
expression: Box<Expression>,
member: EcoString,
ty: Type,
span: Span,
resolution: DotAccessResolution,
id: ExpressionId,
},
Assignment {
target: Box<Expression>,
value: Box<Expression>,
compound_operator: Option<BinaryOperator>,
span: Span,
id: ExpressionId,
},
Return {
expression: Box<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
Propagate {
expression: Box<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
TryBlock {
items: Vec<Expression>,
ty: Type,
try_keyword_span: Span,
span: Span,
id: ExpressionId,
},
RecoverBlock {
items: Vec<Expression>,
ty: Type,
recover_keyword_span: Span,
span: Span,
id: ExpressionId,
},
ImplBlock {
annotation: Annotation,
receiver_name: EcoString,
methods: Vec<Expression>,
generics: Vec<Generic>,
ty: Type,
span: Span,
id: ExpressionId,
},
Binary {
operator: BinaryOperator,
left: Box<Expression>,
right: Box<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
Unary {
operator: UnaryOperator,
expression: Box<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
Paren {
expression: Box<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
Const {
binding: Option<BindingId>,
doc: Option<String>,
identifier: EcoString,
identifier_span: Span,
annotation: Option<Annotation>,
expression: ConstInitializer,
visibility: Visibility,
ty: Type,
span: Span,
id: ExpressionId,
},
VariableDeclaration {
doc: Option<String>,
attributes: Vec<Attribute>,
name: EcoString,
name_span: Span,
annotation: Annotation,
visibility: Visibility,
ty: Type,
span: Span,
id: ExpressionId,
},
Loop {
body: Box<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
While {
condition: Box<Expression>,
body: Box<Expression>,
span: Span,
id: ExpressionId,
},
WhileLet {
pattern: Pattern,
scrutinee: Box<Expression>,
body: Box<Expression>,
span: Span,
id: ExpressionId,
},
For {
binding: Box<Binding>,
iterable: Box<Expression>,
body: Box<Expression>,
span: Span,
id: ExpressionId,
},
Break {
value: Option<Box<Expression>>,
span: Span,
id: ExpressionId,
},
Continue {
span: Span,
id: ExpressionId,
},
Enum {
doc: Option<String>,
attributes: Vec<Attribute>,
name: EcoString,
name_span: Span,
generics: Vec<Generic>,
variants: Vec<EnumVariant>,
visibility: Visibility,
span: Span,
id: ExpressionId,
},
Struct {
doc: Option<String>,
attributes: Vec<Attribute>,
name: EcoString,
name_span: Span,
generics: Vec<Generic>,
fields: StructFields,
visibility: Visibility,
span: Span,
id: ExpressionId,
},
TypeAlias {
doc: Option<String>,
attributes: Vec<Attribute>,
name: EcoString,
name_span: Span,
generics: Vec<Generic>,
annotation: Annotation,
ty: Type,
visibility: Visibility,
span: Span,
id: ExpressionId,
},
PackageImport {
name: EcoString,
name_span: Span,
alias: Option<ImportAlias>,
span: Span,
id: ExpressionId,
},
Reference {
expression: Box<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
Interface {
doc: Option<String>,
attributes: Vec<Attribute>,
name: EcoString,
name_span: Span,
generics: Vec<Generic>,
parents: Vec<ParentInterface>,
method_signatures: Vec<Expression>,
visibility: Visibility,
span: Span,
id: ExpressionId,
},
IndexedAccess {
expression: Box<Expression>,
index: Box<Expression>,
ty: Type,
span: Span,
from_colon_syntax: bool,
id: ExpressionId,
},
Task {
expression: Box<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
Defer {
expression: Box<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
Assert {
expression: Box<Expression>,
ty: Type,
span: Span,
id: ExpressionId,
},
Select {
arms: Vec<SelectArm>,
ty: Type,
span: Span,
id: ExpressionId,
},
Unit {
ty: Type,
span: Span,
id: ExpressionId,
},
Range {
start: Option<Box<Expression>>,
end: Option<Box<Expression>>,
inclusive: bool,
ty: Type,
span: Span,
id: ExpressionId,
},
Cast {
expression: Box<Expression>,
target_type: Annotation,
ty: Type,
span: Span,
id: ExpressionId,
},
}
impl Expression {
pub fn imaginary_coefficient(&self) -> Option<f64> {
match self.unwrap_parens() {
Expression::Literal {
literal: Literal::Imaginary(coefficient),
..
} => Some(*coefficient),
_ => None,
}
}
pub fn id(&self) -> ExpressionId {
match self {
Self::Literal { id, .. }
| Self::Function { id, .. }
| Self::Lambda { id, .. }
| Self::Block { id, .. }
| Self::Let { id, .. }
| Self::Identifier { id, .. }
| Self::Call { id, .. }
| Self::If { id, .. }
| Self::IfLet { id, .. }
| Self::Match { id, .. }
| Self::Tuple { id, .. }
| Self::StructCall { id, .. }
| Self::DotAccess { id, .. }
| Self::Assignment { id, .. }
| Self::Return { id, .. }
| Self::Propagate { id, .. }
| Self::TryBlock { id, .. }
| Self::RecoverBlock { id, .. }
| Self::ImplBlock { id, .. }
| Self::Binary { id, .. }
| Self::Unary { id, .. }
| Self::Paren { id, .. }
| Self::Const { id, .. }
| Self::VariableDeclaration { id, .. }
| Self::Loop { id, .. }
| Self::While { id, .. }
| Self::WhileLet { id, .. }
| Self::For { id, .. }
| Self::Break { id, .. }
| Self::Continue { id, .. }
| Self::Enum { id, .. }
| Self::Struct { id, .. }
| Self::TypeAlias { id, .. }
| Self::PackageImport { id, .. }
| Self::Reference { id, .. }
| Self::Interface { id, .. }
| Self::IndexedAccess { id, .. }
| Self::Task { id, .. }
| Self::Defer { id, .. }
| Self::Assert { id, .. }
| Self::Select { id, .. }
| Self::Unit { id, .. }
| Self::Range { id, .. }
| Self::Cast { id, .. } => *id,
}
}
pub(crate) fn is_block(&self) -> bool {
matches!(self, Expression::Block { .. })
}
pub fn is_range(&self) -> bool {
matches!(self, Expression::Range { .. })
}
pub fn is_conditional(&self) -> bool {
matches!(self, Expression::If { .. } | Expression::IfLet { .. })
}
pub fn is_control_flow(&self) -> bool {
matches!(
self,
Expression::If { .. }
| Expression::IfLet { .. }
| Expression::Match { .. }
| Expression::Select { .. }
| Expression::For { .. }
| Expression::While { .. }
| Expression::WhileLet { .. }
| Expression::Loop { .. }
)
}
pub fn is_temp_producing(&self) -> bool {
matches!(
self.unwrap_parens(),
Expression::If { .. }
| Expression::IfLet { .. }
| Expression::Match { .. }
| Expression::Block { .. }
| Expression::Loop { .. }
| Expression::Select { .. }
| Expression::TryBlock { .. }
| Expression::RecoverBlock { .. }
)
}
pub fn function_definition_view(&self) -> FunctionDefinitionView<'_> {
match self {
Expression::Function {
name,
name_span,
generics,
params,
return_annotation,
return_type,
body,
..
} => FunctionDefinitionView {
name,
name_span: *name_span,
generics,
params,
body: body.definition(),
return_type,
annotation: return_annotation,
},
_ => panic!("function_definition_view called on non-Function expression"),
}
}
pub fn get_type(&self) -> Type {
self.value_type().unwrap_or_else(Type::unit)
}
pub fn value_type(&self) -> Option<Type> {
self.type_ref().cloned().or_else(|| {
matches!(self, Self::Break { .. } | Self::Continue { .. }).then(Type::never)
})
}
pub fn type_ref(&self) -> Option<&Type> {
match self {
Self::Literal { ty, .. }
| Self::Function { ty, .. }
| Self::Lambda { ty, .. }
| Self::Block { ty, .. }
| Self::Let { ty, .. }
| Self::Identifier { ty, .. }
| Self::Call { ty, .. }
| Self::If { ty, .. }
| Self::IfLet { ty, .. }
| Self::Match { ty, .. }
| Self::Tuple { ty, .. }
| Self::StructCall { ty, .. }
| Self::DotAccess { ty, .. }
| Self::Return { ty, .. }
| Self::Propagate { ty, .. }
| Self::TryBlock { ty, .. }
| Self::RecoverBlock { ty, .. }
| Self::Binary { ty, .. }
| Self::Paren { ty, .. }
| Self::Unary { ty, .. }
| Self::Const { ty, .. }
| Self::VariableDeclaration { ty, .. }
| Self::Defer { ty, .. }
| Self::Assert { ty, .. }
| Self::Reference { ty, .. }
| Self::IndexedAccess { ty, .. }
| Self::Task { ty, .. }
| Self::Select { ty, .. }
| Self::Unit { ty, .. }
| Self::Loop { ty, .. }
| Self::Range { ty, .. }
| Self::Cast { ty, .. } => Some(ty),
Self::Enum { .. }
| Self::Struct { .. }
| Self::Assignment { .. }
| Self::ImplBlock { .. }
| Self::TypeAlias { .. }
| Self::PackageImport { .. }
| Self::Interface { .. }
| Self::While { .. }
| Self::WhileLet { .. }
| Self::For { .. } => None,
Self::Break { .. } | Self::Continue { .. } => None,
}
}
pub fn get_span(&self) -> Span {
match self {
Self::Literal { span, .. }
| Self::Function { span, .. }
| Self::Lambda { span, .. }
| Self::Block { span, .. }
| Self::Let { span, .. }
| Self::Identifier { span, .. }
| Self::Call { span, .. }
| Self::If { span, .. }
| Self::IfLet { span, .. }
| Self::Match { span, .. }
| Self::Tuple { span, .. }
| Self::Enum { span, .. }
| Self::Struct { span, .. }
| Self::StructCall { span, .. }
| Self::DotAccess { span, .. }
| Self::Assignment { span, .. }
| Self::Return { span, .. }
| Self::Propagate { span, .. }
| Self::TryBlock { span, .. }
| Self::RecoverBlock { span, .. }
| Self::ImplBlock { span, .. }
| Self::Binary { span, .. }
| Self::Paren { span, .. }
| Self::Unary { span, .. }
| Self::Const { span, .. }
| Self::VariableDeclaration { span, .. }
| Self::Defer { span, .. }
| Self::Assert { span, .. }
| Self::Reference { span, .. }
| Self::IndexedAccess { span, .. }
| Self::Task { span, .. }
| Self::Select { span, .. }
| Self::Loop { span, .. }
| Self::TypeAlias { span, .. }
| Self::PackageImport { span, .. }
| Self::Interface { span, .. }
| Self::Unit { span, .. }
| Self::While { span, .. }
| Self::WhileLet { span, .. }
| Self::For { span, .. }
| Self::Break { span, .. }
| Self::Continue { span, .. }
| Self::Range { span, .. }
| Self::Cast { span, .. } => *span,
}
}
pub fn set_span(&mut self, new_span: Span) {
match self {
Self::Literal { span, .. }
| Self::Function { span, .. }
| Self::Lambda { span, .. }
| Self::Block { span, .. }
| Self::Let { span, .. }
| Self::Identifier { span, .. }
| Self::Call { span, .. }
| Self::If { span, .. }
| Self::IfLet { span, .. }
| Self::Match { span, .. }
| Self::Tuple { span, .. }
| Self::Enum { span, .. }
| Self::Struct { span, .. }
| Self::StructCall { span, .. }
| Self::DotAccess { span, .. }
| Self::Assignment { span, .. }
| Self::Return { span, .. }
| Self::Propagate { span, .. }
| Self::TryBlock { span, .. }
| Self::RecoverBlock { span, .. }
| Self::ImplBlock { span, .. }
| Self::Binary { span, .. }
| Self::Paren { span, .. }
| Self::Unary { span, .. }
| Self::Const { span, .. }
| Self::VariableDeclaration { span, .. }
| Self::Defer { span, .. }
| Self::Assert { span, .. }
| Self::Reference { span, .. }
| Self::IndexedAccess { span, .. }
| Self::Task { span, .. }
| Self::Select { span, .. }
| Self::Loop { span, .. }
| Self::TypeAlias { span, .. }
| Self::PackageImport { span, .. }
| Self::Interface { span, .. }
| Self::Unit { span, .. }
| Self::While { span, .. }
| Self::WhileLet { span, .. }
| Self::For { span, .. }
| Self::Break { span, .. }
| Self::Continue { span, .. }
| Self::Range { span, .. }
| Self::Cast { span, .. } => *span = new_span,
}
}
pub fn contains_break(&self) -> bool {
match self {
Expression::Break { .. } => true,
Expression::Loop { .. }
| Expression::While { .. }
| Expression::WhileLet { .. }
| Expression::For { .. } => false,
Expression::Block { items, .. } => items.iter().any(Self::contains_break),
Expression::TryBlock { items, .. } => items.iter().any(Self::contains_break),
Expression::RecoverBlock { items, .. } => items.iter().any(Self::contains_break),
Expression::If {
condition,
consequence,
alternative,
..
} => {
condition.contains_break()
|| consequence.contains_break()
|| alternative.as_deref().is_some_and(Self::contains_break)
}
Expression::IfLet {
scrutinee,
consequence,
alternative,
..
} => {
scrutinee.contains_break()
|| consequence.contains_break()
|| alternative.expression().is_some_and(Self::contains_break)
}
Expression::Match { subject, arms, .. } => {
subject.contains_break() || arms.iter().any(|arm| arm.expression.contains_break())
}
Expression::Paren { expression, .. } => expression.contains_break(),
Expression::Binary { left, right, .. } => {
left.contains_break() || right.contains_break()
}
Expression::Unary { expression, .. } => expression.contains_break(),
Expression::Call {
expression,
args,
spread,
..
} => {
expression.contains_break()
|| args.iter().any(Self::contains_break)
|| spread.as_deref().is_some_and(Self::contains_break)
}
Expression::Function { .. } | Expression::Lambda { .. } => false,
Expression::Select { arms, .. } => arms.iter().any(|arm| match arm {
SelectArm::Receive { body, .. } => body.contains_break(),
SelectArm::Send { body, .. } => body.contains_break(),
SelectArm::MatchReceive { arms, .. } => {
arms.iter().any(|a| a.expression.contains_break())
}
SelectArm::WildCard { body, .. } => body.contains_break(),
}),
Expression::Cast { expression, .. } => expression.contains_break(),
Expression::Let { value, mode, .. } => {
value.contains_break() || mode.else_block().is_some_and(Self::contains_break)
}
Expression::Assignment { value, .. } => value.contains_break(),
_ => false,
}
}
pub fn diverges(&self) -> Option<DeadCodeCause> {
match self {
Expression::Return { .. } => Some(DeadCodeCause::Return),
Expression::Break { .. } => Some(DeadCodeCause::Break),
Expression::Continue { .. } => Some(DeadCodeCause::Continue),
Expression::If {
consequence,
alternative,
..
} => {
if consequence.diverges().is_some()
&& alternative
.as_deref()
.is_some_and(|alternative| alternative.diverges().is_some())
{
Some(DeadCodeCause::DivergingIf)
} else {
None
}
}
Expression::IfLet {
consequence,
alternative,
..
} => {
if consequence.diverges().is_some()
&& alternative
.expression()
.is_some_and(|alternative| alternative.diverges().is_some())
{
Some(DeadCodeCause::DivergingIf)
} else {
None
}
}
Expression::Match { arms, .. } => {
if !arms.is_empty() && arms.iter().all(|arm| arm.expression.diverges().is_some()) {
Some(DeadCodeCause::DivergingMatch)
} else {
None
}
}
Expression::Block { items, .. } => {
for item in items {
if let Some(cause) = item.diverges() {
return Some(cause);
}
}
None
}
Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
for item in items {
if let Some(cause) = item.diverges() {
return Some(cause);
}
}
None
}
Expression::Paren { expression, .. } | Expression::Cast { expression, .. } => {
expression.diverges()
}
Expression::Loop { body, .. } => {
if !body.contains_break() {
Some(DeadCodeCause::InfiniteLoop)
} else {
None
}
}
Expression::Call { ty, .. } if ty.is_never() => Some(DeadCodeCause::DivergingCall),
_ => None,
}
}
pub fn evaluation_children(&self) -> Vec<&Expression> {
match self {
Self::Function { .. } | Self::Lambda { .. } | Self::Task { .. } => Vec::new(),
_ => self.children(),
}
}
pub fn propagation_children(&self) -> Vec<&Expression> {
match self {
Self::TryBlock { .. } | Self::RecoverBlock { .. } => Vec::new(),
_ => self.evaluation_children(),
}
}
pub fn children(&self) -> Vec<&Expression> {
let mut children = Vec::new();
self.for_each_child(|child| children.push(child));
children
}
pub fn for_each_child<'a>(&'a self, mut f: impl FnMut(&'a Expression)) {
match self {
Expression::Literal { literal, .. } => match literal {
Literal::Slice(elements) => elements.iter().for_each(f),
Literal::FormatString(parts) => {
for part in parts {
if let FormatStringPart::Expression(e) = part {
f(e);
}
}
}
_ => {}
},
Expression::Function { body, .. } => body.definition().into_iter().for_each(f),
Expression::Lambda { body, .. } => f(body),
Expression::Block { items, .. } => items.iter().for_each(f),
Expression::Let { value, mode, .. } => {
f(value);
if let Some(else_block) = mode.else_block() {
f(else_block);
}
}
Expression::Identifier { .. } => {}
Expression::Call {
expression,
args,
spread,
..
} => {
f(expression);
args.iter().for_each(&mut f);
if let Some(spread) = spread.as_ref() {
f(spread);
}
}
Expression::If {
condition,
consequence,
alternative,
..
} => {
f(condition);
f(consequence);
if let Some(alternative) = alternative {
f(alternative);
}
}
Expression::IfLet {
scrutinee,
consequence,
alternative,
..
} => {
f(scrutinee);
f(consequence);
if let Some(alternative) = alternative.expression() {
f(alternative);
}
}
Expression::Match { subject, arms, .. } => {
f(subject);
for arm in arms {
if let Some(guard) = &arm.guard {
f(guard);
}
f(&arm.expression);
}
}
Expression::Tuple { elements, .. } => elements.iter().for_each(f),
Expression::StructCall {
field_assignments,
spread,
..
} => {
for field in field_assignments {
f(&field.value);
}
if let Some(spread) = spread.as_expression() {
f(spread);
}
}
Expression::DotAccess { expression, .. }
| Expression::Return { expression, .. }
| Expression::Propagate { expression, .. }
| Expression::Unary { expression, .. }
| Expression::Paren { expression, .. }
| Expression::Reference { expression, .. }
| Expression::Task { expression, .. }
| Expression::Defer { expression, .. }
| Expression::Assert { expression, .. }
| Expression::Cast { expression, .. } => f(expression),
Expression::Assignment { target, value, .. } => {
f(target);
f(value);
}
Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
items.iter().for_each(f)
}
Expression::ImplBlock { methods, .. } => methods.iter().for_each(f),
Expression::Binary { left, right, .. } => {
f(left);
f(right);
}
Expression::Const { expression, .. } => expression.value().into_iter().for_each(f),
Expression::Loop { body, .. } => f(body),
Expression::While {
condition, body, ..
} => {
f(condition);
f(body);
}
Expression::WhileLet {
scrutinee, body, ..
} => {
f(scrutinee);
f(body);
}
Expression::For { iterable, body, .. } => {
f(iterable);
f(body);
}
Expression::Break { value, .. } => {
if let Some(value) = value {
f(value);
}
}
Expression::IndexedAccess {
expression, index, ..
} => {
f(expression);
f(index);
}
Expression::Select { arms, .. } => {
for arm in arms {
match arm {
SelectArm::Receive {
receive_expression,
body,
..
} => {
f(receive_expression);
f(body);
}
SelectArm::Send {
send_expression,
body,
} => {
f(send_expression);
f(body);
}
SelectArm::MatchReceive {
receive_expression,
arms: match_arms,
} => {
f(receive_expression);
for match_arm in match_arms {
match_arm.guard.as_deref().into_iter().for_each(&mut f);
f(&match_arm.expression);
}
}
SelectArm::WildCard { body, .. } => f(body),
}
}
}
Expression::Range { start, end, .. } => {
if let Some(start) = start {
f(start);
}
if let Some(end) = end {
f(end);
}
}
Expression::Interface {
method_signatures, ..
} => method_signatures.iter().for_each(f),
Expression::Unit { .. }
| Expression::Continue { .. }
| Expression::Enum { .. }
| Expression::Struct { .. }
| Expression::TypeAlias { .. }
| Expression::VariableDeclaration { .. }
| Expression::PackageImport { .. } => {}
}
}
pub fn introduced_patterns<'a>(&'a self, mut f: impl FnMut(&'a Pattern, PatternSite)) {
match self {
Expression::Function { params, .. } | Expression::Lambda { params, .. } => {
for param in params {
f(¶m.pattern, PatternSite::Parameter);
}
}
Expression::Let { binding, .. } | Expression::For { binding, .. } => {
f(&binding.pattern, PatternSite::Binding);
}
Expression::IfLet { pattern, .. } | Expression::WhileLet { pattern, .. } => {
f(pattern, PatternSite::Binding);
}
Expression::Match { arms, .. } => {
for arm in arms {
f(&arm.pattern, arm.pattern_site());
}
}
Expression::Select { arms, .. } => {
for select_arm in arms {
match select_arm {
SelectArm::Receive { binding, .. } => f(binding, PatternSite::Binding),
SelectArm::MatchReceive { arms, .. } => arms
.iter()
.for_each(|arm| f(&arm.pattern, arm.pattern_site())),
SelectArm::Send { .. } | SelectArm::WildCard { .. } => {}
}
}
}
_ => {}
}
}
pub fn for_each_child_mut<'a>(&'a mut self, mut f: impl FnMut(&'a mut Expression)) {
match self {
Expression::Literal { literal, .. } => match literal {
Literal::Slice(elements) => elements.iter_mut().for_each(f),
Literal::FormatString(parts) => {
for part in parts {
if let FormatStringPart::Expression(e) = part {
f(e);
}
}
}
_ => {}
},
Expression::Function { body, .. } => body.definition_mut().into_iter().for_each(f),
Expression::Lambda { body, .. } => f(body),
Expression::Block { items, .. } => items.iter_mut().for_each(f),
Expression::Let { value, mode, .. } => {
f(value);
if let Some(else_block) = mode.else_block_mut() {
f(else_block);
}
}
Expression::Identifier { .. } => {}
Expression::Call {
expression,
args,
spread,
..
} => {
f(expression);
args.iter_mut().for_each(&mut f);
if let Some(spread) = spread.as_mut() {
f(spread);
}
}
Expression::If {
condition,
consequence,
alternative,
..
} => {
f(condition);
f(consequence);
if let Some(alternative) = alternative {
f(alternative);
}
}
Expression::IfLet {
scrutinee,
consequence,
alternative,
..
} => {
f(scrutinee);
f(consequence);
if let Some(alternative) = alternative.expression_mut() {
f(alternative);
}
}
Expression::Match { subject, arms, .. } => {
f(subject);
for arm in arms {
if let Some(guard) = &mut arm.guard {
f(guard);
}
f(&mut arm.expression);
}
}
Expression::Tuple { elements, .. } => elements.iter_mut().for_each(f),
Expression::StructCall {
field_assignments,
spread,
..
} => {
for field in field_assignments {
f(&mut field.value);
}
if let Some(spread) = spread.as_expression_mut() {
f(spread);
}
}
Expression::DotAccess { expression, .. }
| Expression::Return { expression, .. }
| Expression::Propagate { expression, .. }
| Expression::Unary { expression, .. }
| Expression::Paren { expression, .. }
| Expression::Reference { expression, .. }
| Expression::Task { expression, .. }
| Expression::Defer { expression, .. }
| Expression::Assert { expression, .. }
| Expression::Cast { expression, .. } => f(expression),
Expression::Assignment { target, value, .. } => {
f(target);
f(value);
}
Expression::TryBlock { items, .. } | Expression::RecoverBlock { items, .. } => {
items.iter_mut().for_each(f)
}
Expression::ImplBlock { methods, .. } => methods.iter_mut().for_each(f),
Expression::Binary { left, right, .. } => {
f(left);
f(right);
}
Expression::Const { expression, .. } => expression.value_mut().into_iter().for_each(f),
Expression::Loop { body, .. } => f(body),
Expression::While {
condition, body, ..
} => {
f(condition);
f(body);
}
Expression::WhileLet {
scrutinee, body, ..
} => {
f(scrutinee);
f(body);
}
Expression::For { iterable, body, .. } => {
f(iterable);
f(body);
}
Expression::Break { value, .. } => {
if let Some(value) = value {
f(value);
}
}
Expression::IndexedAccess {
expression, index, ..
} => {
f(expression);
f(index);
}
Expression::Select { arms, .. } => {
for arm in arms {
match arm {
SelectArm::Receive {
receive_expression,
body,
..
} => {
f(receive_expression);
f(body);
}
SelectArm::Send {
send_expression,
body,
} => {
f(send_expression);
f(body);
}
SelectArm::MatchReceive {
receive_expression,
arms: match_arms,
} => {
f(receive_expression);
for match_arm in match_arms {
match_arm.guard.as_deref_mut().into_iter().for_each(&mut f);
f(&mut match_arm.expression);
}
}
SelectArm::WildCard { body, .. } => f(body),
}
}
}
Expression::Range { start, end, .. } => {
if let Some(start) = start {
f(start);
}
if let Some(end) = end {
f(end);
}
}
Expression::Interface {
method_signatures, ..
} => method_signatures.iter_mut().for_each(f),
Expression::Unit { .. }
| Expression::Continue { .. }
| Expression::Enum { .. }
| Expression::Struct { .. }
| Expression::TypeAlias { .. }
| Expression::VariableDeclaration { .. }
| Expression::PackageImport { .. } => {}
}
}
pub fn strip_wrappers(&mut self) {
self.peel_wrappers(None);
self.strip_child_wrappers();
}
fn strip_child_wrappers(&mut self) {
let slots = self.block_slots();
let keeps_block: Vec<bool> = if slots.is_empty() {
Vec::new()
} else {
self.children()
.into_iter()
.map(|child| slots.iter().any(|slot| ptr::eq(*slot, child)))
.collect()
};
let is_statement_list = self.is_block();
let mut index = 0;
self.for_each_child_mut(|child| {
let keeps_block = keeps_block.get(index).copied().unwrap_or(false);
index += 1;
child.peel_wrappers((!keeps_block).then_some(is_statement_list));
child.strip_child_wrappers();
});
}
pub fn contains_wrapper(&self) -> bool {
let slots = self.block_slots();
let is_statement_list = self.is_block();
self.reads_reference_once()
|| self.children().into_iter().any(|child| {
let keeps_block = slots.iter().any(|slot| ptr::eq(*slot, child));
(!keeps_block && child.removable_block(is_statement_list))
|| child.contains_wrapper()
})
}
fn removable_block(&self, is_statement: bool) -> bool {
match self {
Expression::Block { items, .. } => match items.as_slice() {
[item] => item.is_plain_block_item() && (is_statement || item.is_value_form()),
_ => false,
},
_ => false,
}
}
fn peel_wrappers(&mut self, blocks: Option<bool>) {
loop {
let removes_block =
blocks.is_some_and(|is_statement| self.removable_block(is_statement));
let inner = match self {
Expression::Block { items, .. } if removes_block => &mut items[0],
_ => return,
};
let placeholder = Expression::Unit {
ty: Type::unit(),
span: inner.get_span(),
id: inner.id(),
};
*self = mem::replace(inner, placeholder);
}
}
fn is_plain_block_item(&self) -> bool {
!matches!(
self,
Expression::Let { .. }
| Expression::Const { .. }
| Expression::Function { .. }
| Expression::Struct { .. }
| Expression::Enum { .. }
| Expression::Interface { .. }
| Expression::TypeAlias { .. }
| Expression::ImplBlock { .. }
| Expression::VariableDeclaration { .. }
| Expression::PackageImport { .. }
| Expression::Defer { .. }
)
}
fn is_value_form(&self) -> bool {
!matches!(
self,
Expression::For { .. }
| Expression::While { .. }
| Expression::WhileLet { .. }
| Expression::Assignment { .. }
| Expression::Return { .. }
| Expression::Break { .. }
| Expression::Continue { .. }
| Expression::Task { .. }
| Expression::Assert { .. }
| Expression::Select { .. }
)
}
fn block_slots(&self) -> Vec<&Expression> {
match self {
Expression::Function { body, .. } => body.definition().into_iter().collect(),
Expression::If {
consequence,
alternative,
..
} => {
let mut slots = vec![consequence.as_ref()];
slots.extend(alternative.as_deref());
slots
}
Expression::IfLet {
consequence,
alternative,
..
} => {
let mut slots = vec![consequence.as_ref()];
slots.extend(alternative.expression());
slots
}
Expression::Let { mode, .. } => mode.else_block().into_iter().collect(),
Expression::Loop { body, .. }
| Expression::While { body, .. }
| Expression::WhileLet { body, .. }
| Expression::For { body, .. } => vec![body],
Expression::Task { expression, .. } | Expression::Defer { expression, .. } => {
vec![expression]
}
Expression::Select { .. } => self.children(),
_ => Vec::new(),
}
}
pub fn reads_reference_once(&self) -> bool {
match self {
Expression::Reference { expression, ty, .. } => *ty == expression.get_type(),
Expression::Unary {
operator: UnaryOperator::Deref,
expression,
..
} => matches!(expression.unwrap_parens(), Expression::Reference { .. }),
Expression::DotAccess {
expression,
resolution,
..
} => resolution.reads_receiver() && expression.is_reference_receiver(),
_ => false,
}
}
pub fn is_reference_receiver(&self) -> bool {
matches!(
self.unwrap_parens(),
Expression::Reference { expression, .. } if !expression.is_fresh_value()
)
}
pub fn is_fresh_reference(&self) -> bool {
matches!(
self.unwrap_parens(),
Expression::Reference { expression, .. } if expression.is_fresh_value()
)
}
fn is_fresh_value(&self) -> bool {
matches!(
self.unwrap_parens(),
Expression::Call { .. } | Expression::StructCall { .. }
)
}
pub fn unwrap_parens(&self) -> &Expression {
match self {
Expression::Paren { expression, .. } => expression.unwrap_parens(),
other => other,
}
}
pub fn unwrap_value_wrappers(&self) -> &Expression {
match self {
Expression::Paren { expression, .. } => expression.unwrap_value_wrappers(),
Expression::Block { items, .. } if self.removable_block(false) => {
items[0].unwrap_value_wrappers()
}
other => other,
}
}
pub fn is_piped_call(&self) -> bool {
let Expression::Call {
expression: callee,
args,
spread,
..
} = self
else {
return false;
};
let callee_start = callee.get_span().byte_offset;
args.iter()
.chain(spread.as_deref())
.any(|arg| arg.get_span().byte_offset < callee_start)
}
pub fn binding_id(&self) -> Option<BindingId> {
match self.unwrap_parens() {
Expression::Identifier { resolution, .. } => resolution.binding_id(),
_ => None,
}
}
pub fn as_integer(&self) -> Option<u64> {
match self.unwrap_parens() {
Expression::Literal {
literal: Literal::Integer { value, .. },
..
} => Some(*value),
_ => None,
}
}
#[inline]
pub fn deref_inner(&self) -> Option<&Expression> {
match self.unwrap_parens() {
Expression::Unary {
operator: UnaryOperator::Deref,
expression,
..
} => Some(expression),
_ => None,
}
}
pub fn as_dotted_path(&self) -> Option<String> {
match self {
Expression::Identifier { value, .. } => Some(value.to_string()),
Expression::DotAccess {
expression, member, ..
} => Some(format!("{}.{}", expression.as_dotted_path()?, member)),
_ => None,
}
}
pub fn root_identifier(&self) -> Option<&str> {
match self {
Expression::Identifier { value, .. } => Some(value),
Expression::DotAccess { expression, .. } => expression.root_identifier(),
_ => None,
}
}
pub fn root_binding_id(&self) -> Option<BindingId> {
match self.unwrap_parens() {
Expression::Identifier {
resolution: IdentifierResolution::Binding(id),
..
} => Some(*id),
Expression::DotAccess { expression, .. }
| Expression::IndexedAccess { expression, .. } => expression.root_binding_id(),
_ => None,
}
}
pub fn is_empty_collection(&self) -> bool {
matches!(
self.unwrap_parens(),
Expression::Literal {
literal: Literal::Slice(elements),
..
} if elements.is_empty()
)
}
pub fn is_all_literals(&self) -> bool {
match self.unwrap_parens() {
Expression::Literal { literal, .. } => match literal {
Literal::Slice(elements) => elements.iter().all(|e| e.is_all_literals()),
Literal::FormatString(parts) => parts.iter().all(|p| match p {
FormatStringPart::Text(_) => true,
FormatStringPart::Expression(e) => e.is_all_literals(),
}),
_ => true,
},
Expression::Tuple { elements, .. } => elements.iter().all(|e| e.is_all_literals()),
Expression::Unit { .. } => true,
_ => false,
}
}
pub fn get_var_name(&self) -> Option<String> {
match self {
Expression::Identifier { value, .. } => Some(value.to_string()),
Expression::DotAccess { expression, .. } => expression.get_var_name(),
Expression::Assignment { target, .. } => target.get_var_name(),
Expression::IndexedAccess { expression, .. } => expression.get_var_name(),
Expression::Paren { expression, .. } => expression.get_var_name(),
Expression::Reference { expression, .. } => expression.get_var_name(),
Expression::Unary {
operator,
expression,
..
} => {
if operator == &UnaryOperator::Deref {
expression.get_var_name()
} else {
None
}
}
_ => None,
}
}
pub(crate) fn set_public(mut self) -> Self {
match &mut self {
Expression::Struct {
fields, visibility, ..
} => {
if let StructFields::Tuple(fields) = fields {
for field in fields {
field.visibility = Visibility::Public;
}
}
*visibility = Visibility::Public;
}
Expression::Enum { visibility, .. }
| Expression::Function { visibility, .. }
| Expression::Const { visibility, .. }
| Expression::VariableDeclaration { visibility, .. }
| Expression::TypeAlias { visibility, .. }
| Expression::Interface { visibility, .. } => *visibility = Visibility::Public,
_ => {}
}
self
}
pub fn has_else(&self) -> bool {
match self {
Self::Block { items, .. } if items.is_empty() => false,
Self::Unit { .. } => false,
Self::If { alternative, .. } => alternative.as_deref().is_some_and(Self::has_else),
Self::IfLet { alternative, .. } => alternative.expression().is_some_and(Self::has_else),
_ => true,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
Integer {
value: u64,
text: Option<String>,
},
Float {
value: f64,
text: Option<String>,
},
Imaginary(f64),
Boolean(bool),
String {
value: String,
raw: bool,
},
FormatString(Vec<FormatStringPart>),
Char(String),
Slice(Vec<Expression>),
}
impl Literal {
pub fn diagnostic_text(&self) -> String {
match self {
Literal::Integer { text, value } => text.as_ref().unwrap_or(&value.to_string()).clone(),
Literal::Float { text, value } => text.as_ref().unwrap_or(&value.to_string()).clone(),
Literal::Imaginary(v) => format!("{}i", v),
Literal::Boolean(b) => b.to_string(),
Literal::String { value, raw: true } => format!("r\"{}\"", value),
Literal::String { value, raw: false } => format!("\"{}\"", value),
Literal::Char(c) => format!("'{}'", c),
Literal::FormatString(_) => "f\"...\"".to_string(),
Literal::Slice(_) => "[...]".to_string(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum FormatStringPart {
Text(String),
Expression(Box<Expression>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum UnaryOperator {
Negative,
Not,
BitwiseNot,
Deref,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BinaryOperator {
Addition,
Subtraction,
Multiplication,
Division,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
BitwiseAndNot,
ShiftLeft,
ShiftRight,
LessThan,
LessThanOrEqual,
GreaterThan,
GreaterThanOrEqual,
Remainder,
Equal,
NotEqual,
And,
Or,
Pipeline,
}
impl BinaryOperator {
pub fn compound_assignment_symbol(&self) -> Option<&'static str> {
match self {
BinaryOperator::Addition => Some("+="),
BinaryOperator::Subtraction => Some("-="),
BinaryOperator::Multiplication => Some("*="),
BinaryOperator::Division => Some("/="),
BinaryOperator::Remainder => Some("%="),
BinaryOperator::BitwiseAnd => Some("&="),
BinaryOperator::BitwiseOr => Some("|="),
BinaryOperator::BitwiseXor => Some("^="),
BinaryOperator::BitwiseAndNot => Some("&^="),
BinaryOperator::ShiftLeft => Some("<<="),
BinaryOperator::ShiftRight => Some(">>="),
_ => None,
}
}
pub fn is_comparison(&self) -> bool {
matches!(
self,
BinaryOperator::Equal
| BinaryOperator::NotEqual
| BinaryOperator::LessThan
| BinaryOperator::LessThanOrEqual
| BinaryOperator::GreaterThan
| BinaryOperator::GreaterThanOrEqual
)
}
}
impl Display for BinaryOperator {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let symbol = match self {
BinaryOperator::Addition => "+",
BinaryOperator::Subtraction => "-",
BinaryOperator::Multiplication => "*",
BinaryOperator::Division => "/",
BinaryOperator::Remainder => "%",
BinaryOperator::BitwiseAnd => "&",
BinaryOperator::BitwiseOr => "|",
BinaryOperator::BitwiseXor => "^",
BinaryOperator::BitwiseAndNot => "&^",
BinaryOperator::ShiftLeft => "<<",
BinaryOperator::ShiftRight => ">>",
BinaryOperator::Equal => "==",
BinaryOperator::NotEqual => "!=",
BinaryOperator::LessThan => "<",
BinaryOperator::LessThanOrEqual => "<=",
BinaryOperator::GreaterThan => ">",
BinaryOperator::GreaterThanOrEqual => ">=",
BinaryOperator::And => "&&",
BinaryOperator::Or => "||",
BinaryOperator::Pipeline => "|>",
};
write!(f, "{}", symbol)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParentInterface {
pub annotation: Annotation,
pub ty: Type,
pub span: Span,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Visibility {
Public,
Private,
Local,
}
impl Visibility {
pub fn is_public(&self) -> bool {
matches!(self, Visibility::Public)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ImportAlias {
Named(EcoString, Span),
Blank(Span),
}