repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/asm_lang/allocated_ops.rs | sway-core/src/asm_lang/allocated_ops.rs | //! This module contains abstracted versions of bytecode primitives that the compiler uses to
//! ensure correctness and safety.
//!
//! These ops are different from [VirtualOp]s in that they contain allocated registers, i.e. at
//! most 48 free registers plus reserved registers. These ops can be safely directly converted to
//! bytecode.
//!
//!
//! It is unfortunate that there are copies of our opcodes in multiple places, but this ensures the
//! best type safety. It can be macro'd someday.
use super::*;
use crate::{
asm_generation::fuel::{
compiler_constants::DATA_SECTION_REGISTER,
data_section::{DataId, DataSection},
},
fuel_prelude::fuel_asm::{self, op},
};
use fuel_vm::fuel_asm::{
op::{ADD, MOVI},
Imm18,
};
use std::fmt::{self, Write};
use sway_types::span::Span;
const COMMENT_START_COLUMN: usize = 30;
/// Represents registers that have gone through register allocation. The value in the [Allocated]
/// variant is guaranteed to be between 0 and [compiler_constants::NUM_ALLOCATABLE_REGISTERS].
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Debug, Clone)]
pub enum AllocatedRegister {
Allocated(u8),
Constant(super::ConstantRegister),
}
impl fmt::Display for AllocatedRegister {
fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AllocatedRegister::Allocated(name) => write!(fmtr, "$r{name}"),
AllocatedRegister::Constant(name) => {
write!(fmtr, "{name}")
}
}
}
}
impl AllocatedRegister {
pub(crate) fn to_reg_id(&self) -> fuel_asm::RegId {
match self {
AllocatedRegister::Allocated(a) => fuel_asm::RegId::new(a + 16),
AllocatedRegister::Constant(constant) => constant.to_reg_id(),
}
}
pub fn is_zero(&self) -> bool {
matches!(self, Self::Constant(ConstantRegister::Zero))
}
}
/// This enum is unfortunately a redundancy of the [fuel_asm::Opcode] and [crate::VirtualOp] enums. This variant, however,
/// allows me to use the compiler's internal [AllocatedRegister] types and maintain type safety
/// between virtual ops and those which have gone through register allocation.
/// A bit of copy/paste seemed worth it for that safety,
/// so here it is.
#[allow(clippy::upper_case_acronyms)]
#[derive(Clone, Debug)]
pub(crate) enum AllocatedInstruction {
/* Arithmetic/Logic (ALU) Instructions */
ADD(AllocatedRegister, AllocatedRegister, AllocatedRegister),
ADDI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
AND(AllocatedRegister, AllocatedRegister, AllocatedRegister),
ANDI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
DIV(AllocatedRegister, AllocatedRegister, AllocatedRegister),
DIVI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
EQ(AllocatedRegister, AllocatedRegister, AllocatedRegister),
EXP(AllocatedRegister, AllocatedRegister, AllocatedRegister),
EXPI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
GT(AllocatedRegister, AllocatedRegister, AllocatedRegister),
LT(AllocatedRegister, AllocatedRegister, AllocatedRegister),
MLOG(AllocatedRegister, AllocatedRegister, AllocatedRegister),
MOD(AllocatedRegister, AllocatedRegister, AllocatedRegister),
MODI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
MOVE(AllocatedRegister, AllocatedRegister),
MOVI(AllocatedRegister, VirtualImmediate18),
MROO(AllocatedRegister, AllocatedRegister, AllocatedRegister),
MUL(AllocatedRegister, AllocatedRegister, AllocatedRegister),
MULI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
NOOP,
NOT(AllocatedRegister, AllocatedRegister),
OR(AllocatedRegister, AllocatedRegister, AllocatedRegister),
ORI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
SLL(AllocatedRegister, AllocatedRegister, AllocatedRegister),
SLLI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
SRL(AllocatedRegister, AllocatedRegister, AllocatedRegister),
SRLI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
SUB(AllocatedRegister, AllocatedRegister, AllocatedRegister),
SUBI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
XOR(AllocatedRegister, AllocatedRegister, AllocatedRegister),
XORI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
WQOP(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
VirtualImmediate06,
),
WQML(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
VirtualImmediate06,
),
WQDV(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
VirtualImmediate06,
),
WQMD(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
WQCM(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
VirtualImmediate06,
),
WQAM(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
WQMM(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
/* Control Flow Instructions */
JMP(AllocatedRegister),
JI(VirtualImmediate24),
JNE(AllocatedRegister, AllocatedRegister, AllocatedRegister),
JNEI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
JNZI(AllocatedRegister, VirtualImmediate18),
JMPB(AllocatedRegister, VirtualImmediate18),
JMPF(AllocatedRegister, VirtualImmediate18),
JNZB(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
JNZF(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
JNEB(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
VirtualImmediate06,
),
JNEF(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
VirtualImmediate06,
),
JAL(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
RET(AllocatedRegister),
/* Memory Instructions */
ALOC(AllocatedRegister),
CFEI(VirtualImmediate24),
CFSI(VirtualImmediate24),
CFE(AllocatedRegister),
CFS(AllocatedRegister),
LB(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
LW(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
MCL(AllocatedRegister, AllocatedRegister),
MCLI(AllocatedRegister, VirtualImmediate18),
MCP(AllocatedRegister, AllocatedRegister, AllocatedRegister),
MCPI(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
MEQ(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
PSHH(VirtualImmediate24),
PSHL(VirtualImmediate24),
POPH(VirtualImmediate24),
POPL(VirtualImmediate24),
SB(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
SW(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
/* Contract Instructions */
BAL(AllocatedRegister, AllocatedRegister, AllocatedRegister),
BHEI(AllocatedRegister),
BHSH(AllocatedRegister, AllocatedRegister),
BURN(AllocatedRegister, AllocatedRegister),
CALL(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
CB(AllocatedRegister),
CCP(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
CROO(AllocatedRegister, AllocatedRegister),
CSIZ(AllocatedRegister, AllocatedRegister),
BSIZ(AllocatedRegister, AllocatedRegister),
LDC(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
VirtualImmediate06,
),
BLDD(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
LOG(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
LOGD(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
MINT(AllocatedRegister, AllocatedRegister),
RETD(AllocatedRegister, AllocatedRegister),
RVRT(AllocatedRegister),
SMO(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
SCWQ(AllocatedRegister, AllocatedRegister, AllocatedRegister),
SRW(AllocatedRegister, AllocatedRegister, AllocatedRegister),
SRWQ(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
SWW(AllocatedRegister, AllocatedRegister, AllocatedRegister),
SWWQ(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
TIME(AllocatedRegister, AllocatedRegister),
TR(AllocatedRegister, AllocatedRegister, AllocatedRegister),
TRO(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
/* Cryptographic Instructions */
ECK1(AllocatedRegister, AllocatedRegister, AllocatedRegister),
ECR1(AllocatedRegister, AllocatedRegister, AllocatedRegister),
ED19(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
K256(AllocatedRegister, AllocatedRegister, AllocatedRegister),
S256(AllocatedRegister, AllocatedRegister, AllocatedRegister),
ECOP(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
EPAR(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
/* Other Instructions */
ECAL(
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
AllocatedRegister,
),
FLAG(AllocatedRegister),
GM(AllocatedRegister, VirtualImmediate18),
GTF(AllocatedRegister, AllocatedRegister, VirtualImmediate12),
/* Non-VM Instructions */
BLOB(VirtualImmediate24),
ConfigurablesOffsetPlaceholder,
DataSectionOffsetPlaceholder,
LoadDataId(AllocatedRegister, DataId),
AddrDataId(AllocatedRegister, DataId),
Undefined,
}
impl AllocatedInstruction {
/// Returns a list of all registers *written* by instruction `self`.
pub(crate) fn def_registers(&self) -> BTreeSet<&AllocatedRegister> {
use AllocatedInstruction::*;
(match self {
/* Arithmetic/Logic (ALU) Instructions */
ADD(r1, _r2, _r3) => vec![r1],
ADDI(r1, _r2, _i) => vec![r1],
AND(r1, _r2, _r3) => vec![r1],
ANDI(r1, _r2, _i) => vec![r1],
DIV(r1, _r2, _r3) => vec![r1],
DIVI(r1, _r2, _i) => vec![r1],
EQ(r1, _r2, _r3) => vec![r1],
EXP(r1, _r2, _r3) => vec![r1],
EXPI(r1, _r2, _i) => vec![r1],
GT(r1, _r2, _r3) => vec![r1],
LT(r1, _r2, _r3) => vec![r1],
MLOG(r1, _r2, _r3) => vec![r1],
MOD(r1, _r2, _r3) => vec![r1],
MODI(r1, _r2, _i) => vec![r1],
MOVE(r1, _r2) => vec![r1],
MOVI(r1, _i) => vec![r1],
MROO(r1, _r2, _r3) => vec![r1],
MUL(r1, _r2, _r3) => vec![r1],
MULI(r1, _r2, _i) => vec![r1],
NOOP => vec![],
NOT(r1, _r2) => vec![r1],
OR(r1, _r2, _r3) => vec![r1],
ORI(r1, _r2, _i) => vec![r1],
SLL(r1, _r2, _r3) => vec![r1],
SLLI(r1, _r2, _i) => vec![r1],
SRL(r1, _r2, _r3) => vec![r1],
SRLI(r1, _r2, _i) => vec![r1],
SUB(r1, _r2, _r3) => vec![r1],
SUBI(r1, _r2, _i) => vec![r1],
XOR(r1, _r2, _r3) => vec![r1],
XORI(r1, _r2, _i) => vec![r1],
WQOP(_, _, _, _) => vec![],
WQML(_, _, _, _) => vec![],
WQDV(_, _, _, _) => vec![],
WQMD(_, _, _, _) => vec![],
WQCM(r1, _, _, _) => vec![r1],
WQAM(_, _, _, _) => vec![],
WQMM(_, _, _, _) => vec![],
/* Control Flow Instructions */
JMP(_r1) => vec![],
JI(_im) => vec![],
JNE(_r1, _r2, _r3) => vec![],
JNEI(_r1, _r2, _i) => vec![],
JNZI(_r1, _i) => vec![],
JMPB(_r1, _i) => vec![],
JMPF(_r1, _i) => vec![],
JNZB(_r1, _r2, _i) => vec![],
JNZF(_r1, _r2, _i) => vec![],
JNEB(_r1, _r2, _r3, _i) => vec![],
JNEF(_r1, _r2, _r3, _i) => vec![],
JAL(r1, _r2, _i) => vec![r1],
RET(_r1) => vec![],
/* Memory Instructions */
ALOC(_r1) => vec![],
CFEI(_imm) => vec![],
CFSI(_imm) => vec![],
CFE(_r1) => vec![],
CFS(_r1) => vec![],
LB(r1, _r2, _i) => vec![r1],
LW(r1, _r2, _i) => vec![r1],
MCL(_r1, _r2) => vec![],
MCLI(_r1, _imm) => vec![],
MCP(_r1, _r2, _r3) => vec![],
MCPI(_r1, _r2, _imm) => vec![],
MEQ(r1, _r2, _r3, _r4) => vec![r1],
PSHH(_mask) | PSHL(_mask) | POPH(_mask) | POPL(_mask) => {
panic!("Cannot determine defined registers for register PUSH/POP instructions")
}
SB(_r1, _r2, _i) => vec![],
SW(_r1, _r2, _i) => vec![],
/* Contract Instructions */
BAL(r1, _r2, _r3) => vec![r1],
BHEI(r1) => vec![r1],
BHSH(_r1, _r2) => vec![],
BURN(_r1, _r2) => vec![],
CALL(_r1, _r2, _r3, _r4) => vec![],
CB(_r1) => vec![],
CCP(_r1, _r2, _r3, _r4) => vec![],
CROO(_r1, _r2) => vec![],
CSIZ(r1, _r2) => vec![r1],
BSIZ(r1, _r2) => vec![r1],
LDC(_r1, _r2, _r3, _i0) => vec![],
BLDD(_r1, _r2, _r3, _r4) => vec![],
LOG(_r1, _r2, _r3, _r4) => vec![],
LOGD(_r1, _r2, _r3, _r4) => vec![],
MINT(_r1, _r2) => vec![],
RETD(_r1, _r2) => vec![],
RVRT(_r1) => vec![],
SMO(_r1, _r2, _r3, _r4) => vec![],
SCWQ(_r1, r2, _r3) => vec![r2],
SRW(r1, r2, _r3) => vec![r1, r2],
SRWQ(_r1, r2, _r3, _r4) => vec![r2],
SWW(_r1, r2, _r3) => vec![r2],
SWWQ(_r1, r2, _r3, _r4) => vec![r2],
TIME(r1, _r2) => vec![r1],
TR(_r1, _r2, _r3) => vec![],
TRO(_r1, _r2, _r3, _r4) => vec![],
/* Cryptographic Instructions */
ECK1(_r1, _r2, _r3) => vec![],
ECR1(_r1, _r2, _r3) => vec![],
ED19(_r1, _r2, _r3, _r4) => vec![],
K256(_r1, _r2, _r3) => vec![],
S256(_r1, _r2, _r3) => vec![],
ECOP(_r1, _r2, _r3, _r4) => vec![],
EPAR(r1, _r2, _r3, _r4) => vec![r1],
/* Other Instructions */
ECAL(_r1, _r2, _r3, _r4) => vec![],
FLAG(_r1) => vec![],
GM(r1, _imm) => vec![r1],
GTF(r1, _r2, _i) => vec![r1],
/* Non-VM Instructions */
BLOB(_imm) => vec![],
ConfigurablesOffsetPlaceholder => vec![],
DataSectionOffsetPlaceholder => vec![],
LoadDataId(r1, _i) => vec![r1],
AddrDataId(r1, _i) => vec![r1],
Undefined => vec![],
})
.into_iter()
.collect()
}
}
impl fmt::Display for AllocatedInstruction {
fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {
use AllocatedInstruction::*;
match self {
/* Arithmetic/Logic (ALU) Instructions */
ADD(a, b, c) => write!(fmtr, "add {a} {b} {c}"),
ADDI(a, b, c) => write!(fmtr, "addi {a} {b} {c}"),
AND(a, b, c) => write!(fmtr, "and {a} {b} {c}"),
ANDI(a, b, c) => write!(fmtr, "andi {a} {b} {c}"),
DIV(a, b, c) => write!(fmtr, "div {a} {b} {c}"),
DIVI(a, b, c) => write!(fmtr, "divi {a} {b} {c}"),
EQ(a, b, c) => write!(fmtr, "eq {a} {b} {c}"),
EXP(a, b, c) => write!(fmtr, "exp {a} {b} {c}"),
EXPI(a, b, c) => write!(fmtr, "expi {a} {b} {c}"),
GT(a, b, c) => write!(fmtr, "gt {a} {b} {c}"),
LT(a, b, c) => write!(fmtr, "lt {a} {b} {c}"),
MLOG(a, b, c) => write!(fmtr, "mlog {a} {b} {c}"),
MOD(a, b, c) => write!(fmtr, "mod {a} {b} {c}"),
MODI(a, b, c) => write!(fmtr, "modi {a} {b} {c}"),
MOVE(a, b) => write!(fmtr, "move {a} {b}"),
MOVI(a, b) => write!(fmtr, "movi {a} {b}"),
MROO(a, b, c) => write!(fmtr, "mroo {a} {b} {c}"),
MUL(a, b, c) => write!(fmtr, "mul {a} {b} {c}"),
MULI(a, b, c) => write!(fmtr, "muli {a} {b} {c}"),
NOOP => write!(fmtr, "noop"),
NOT(a, b) => write!(fmtr, "not {a} {b}"),
OR(a, b, c) => write!(fmtr, "or {a} {b} {c}"),
ORI(a, b, c) => write!(fmtr, "ori {a} {b} {c}"),
SLL(a, b, c) => write!(fmtr, "sll {a} {b} {c}"),
SLLI(a, b, c) => write!(fmtr, "slli {a} {b} {c}"),
SRL(a, b, c) => write!(fmtr, "srl {a} {b} {c}"),
SRLI(a, b, c) => write!(fmtr, "srli {a} {b} {c}"),
SUB(a, b, c) => write!(fmtr, "sub {a} {b} {c}"),
SUBI(a, b, c) => write!(fmtr, "subi {a} {b} {c}"),
XOR(a, b, c) => write!(fmtr, "xor {a} {b} {c}"),
XORI(a, b, c) => write!(fmtr, "xori {a} {b} {c}"),
WQOP(a, b, c, d) => write!(fmtr, "wqop {a} {b} {c} {d}"),
WQML(a, b, c, d) => write!(fmtr, "wqml {a} {b} {c} {d}"),
WQDV(a, b, c, d) => write!(fmtr, "wqdv {a} {b} {c} {d}"),
WQMD(a, b, c, d) => write!(fmtr, "wqmd {a} {b} {c} {d}"),
WQCM(a, b, c, d) => write!(fmtr, "wqcm {a} {b} {c} {d}"),
WQAM(a, b, c, d) => write!(fmtr, "wqam {a} {b} {c} {d}"),
WQMM(a, b, c, d) => write!(fmtr, "wqmm {a} {b} {c} {d}"),
/* Control Flow Instructions */
JMP(a) => write!(fmtr, "jmp {a}"),
JI(a) => write!(fmtr, "ji {a}"),
JNE(a, b, c) => write!(fmtr, "jne {a} {b} {c}"),
JNEI(a, b, c) => write!(fmtr, "jnei {a} {b} {c}"),
JNZI(a, b) => write!(fmtr, "jnzi {a} {b}"),
JMPB(a, b) => write!(fmtr, "jmpb {a} {b}"),
JMPF(a, b) => write!(fmtr, "jmpf {a} {b}"),
JNZB(a, b, c) => write!(fmtr, "jnzb {a} {b} {c}"),
JNZF(a, b, c) => write!(fmtr, "jnzf {a} {b} {c}"),
JNEB(a, b, c, d) => write!(fmtr, "jneb {a} {b} {c} {d}"),
JNEF(a, b, c, d) => write!(fmtr, "jnef {a} {b} {c} {d}"),
JAL(a, b, c) => write!(fmtr, "jal {a} {b} {c}"),
RET(a) => write!(fmtr, "ret {a}"),
/* Memory Instructions */
ALOC(a) => write!(fmtr, "aloc {a}"),
CFEI(a) => write!(fmtr, "cfei {a}"),
CFSI(a) => write!(fmtr, "cfsi {a}"),
CFE(a) => write!(fmtr, "cfe {a}"),
CFS(a) => write!(fmtr, "cfs {a}"),
LB(a, b, c) => write!(fmtr, "lb {a} {b} {c}"),
LW(a, b, c) => write!(fmtr, "lw {a} {b} {c}"),
MCL(a, b) => write!(fmtr, "mcl {a} {b}"),
MCLI(a, b) => write!(fmtr, "mcli {a} {b}"),
MCP(a, b, c) => write!(fmtr, "mcp {a} {b} {c}"),
MCPI(a, b, c) => write!(fmtr, "mcpi {a} {b} {c}"),
MEQ(a, b, c, d) => write!(fmtr, "meq {a} {b} {c} {d}"),
PSHH(mask) => write!(fmtr, "pshh {mask}"),
PSHL(mask) => write!(fmtr, "pshl {mask}"),
POPH(mask) => write!(fmtr, "poph {mask}"),
POPL(mask) => write!(fmtr, "popl {mask}"),
SB(a, b, c) => write!(fmtr, "sb {a} {b} {c}"),
SW(a, b, c) => write!(fmtr, "sw {a} {b} {c}"),
/* Contract Instructions */
BAL(a, b, c) => write!(fmtr, "bal {a} {b} {c}"),
BHEI(a) => write!(fmtr, "bhei {a}"),
BHSH(a, b) => write!(fmtr, "bhsh {a} {b}"),
BURN(a, b) => write!(fmtr, "burn {a} {b}"),
CALL(a, b, c, d) => write!(fmtr, "call {a} {b} {c} {d}"),
CB(a) => write!(fmtr, "cb {a}"),
CCP(a, b, c, d) => write!(fmtr, "ccp {a} {b} {c} {d}"),
CROO(a, b) => write!(fmtr, "croo {a} {b}"),
CSIZ(a, b) => write!(fmtr, "csiz {a} {b}"),
BSIZ(a, b) => write!(fmtr, "bsiz {a} {b}"),
LDC(a, b, c, d) => write!(fmtr, "ldc {a} {b} {c} {d}"),
BLDD(a, b, c, d) => write!(fmtr, "bldd {a} {b} {c} {d}"),
LOG(a, b, c, d) => write!(fmtr, "log {a} {b} {c} {d}"),
LOGD(a, b, c, d) => write!(fmtr, "logd {a} {b} {c} {d}"),
MINT(a, b) => write!(fmtr, "mint {a} {b}"),
RETD(a, b) => write!(fmtr, "retd {a} {b}"),
RVRT(a) => write!(fmtr, "rvrt {a}"),
SMO(a, b, c, d) => write!(fmtr, "smo {a} {b} {c} {d}"),
SCWQ(a, b, c) => write!(fmtr, "scwq {a} {b} {c}"),
SRW(a, b, c) => write!(fmtr, "srw {a} {b} {c}"),
SRWQ(a, b, c, d) => write!(fmtr, "srwq {a} {b} {c} {d}"),
SWW(a, b, c) => write!(fmtr, "sww {a} {b} {c}"),
SWWQ(a, b, c, d) => write!(fmtr, "swwq {a} {b} {c} {d}"),
TIME(a, b) => write!(fmtr, "time {a} {b}"),
TR(a, b, c) => write!(fmtr, "tr {a} {b} {c}"),
TRO(a, b, c, d) => write!(fmtr, "tro {a} {b} {c} {d}"),
/* Cryptographic Instructions */
ECK1(a, b, c) => write!(fmtr, "eck1 {a} {b} {c}"),
ECR1(a, b, c) => write!(fmtr, "ecr1 {a} {b} {c}"),
ED19(a, b, c, d) => write!(fmtr, "ed19 {a} {b} {c} {d}"),
K256(a, b, c) => write!(fmtr, "k256 {a} {b} {c}"),
S256(a, b, c) => write!(fmtr, "s256 {a} {b} {c}"),
ECOP(a, b, c, d) => write!(fmtr, "ecop {a} {b} {c} {d}"),
EPAR(a, b, c, d) => write!(fmtr, "epar {a} {b} {c} {d}"),
/* Other Instructions */
ECAL(a, b, c, d) => write!(fmtr, "ecal {a} {b} {c} {d}"),
FLAG(a) => write!(fmtr, "flag {a}"),
GM(a, b) => write!(fmtr, "gm {a} {b}"),
GTF(a, b, c) => write!(fmtr, "gtf {a} {b} {c}"),
/* Non-VM Instructions */
BLOB(a) => write!(fmtr, "blob {a}"),
ConfigurablesOffsetPlaceholder => write!(
fmtr,
"CONFIGURABLES_OFFSET[0..32]\nCONFIGURABLES_OFFSET[32..64]"
),
DataSectionOffsetPlaceholder => {
write!(
fmtr,
"DATA_SECTION_OFFSET[0..32]\nDATA_SECTION_OFFSET[32..64]"
)
}
LoadDataId(a, b) => write!(fmtr, "load {a} {b}"),
AddrDataId(a, b) => write!(fmtr, "addr {a} {b}"),
Undefined => write!(fmtr, "undefined op"),
}
}
}
#[derive(Clone, Debug)]
pub struct AllocatedOp {
pub(crate) opcode: AllocatedInstruction,
/// A descriptive comment for ASM readability
pub(crate) comment: String,
pub(crate) owning_span: Option<Span>,
}
impl fmt::Display for AllocatedOp {
fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {
// We want the comment to always be COMMENT_START_COLUMN characters offset to the right to
// not interfere with the ASM but to be aligned.
let mut op_and_comment = self.opcode.to_string();
if !self.comment.is_empty() {
while op_and_comment.len() < COMMENT_START_COLUMN {
op_and_comment.push(' ');
}
write!(op_and_comment, "; {}", self.comment)?;
}
write!(fmtr, "{op_and_comment}")
}
}
pub(crate) enum FuelAsmData {
ConfigurablesOffset([u8; 8]),
DatasectionOffset([u8; 8]),
Instructions(Vec<fuel_asm::Instruction>),
}
impl AllocatedOp {
pub(crate) fn to_fuel_asm(
&self,
offset_to_data_section: u64,
offset_from_instr_start: u64,
data_section: &DataSection,
) -> FuelAsmData {
use AllocatedInstruction::*;
FuelAsmData::Instructions(vec![match &self.opcode {
/* Arithmetic/Logic (ALU) Instructions */
ADD(a, b, c) => op::ADD::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
ADDI(a, b, c) => op::ADDI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
AND(a, b, c) => op::AND::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
ANDI(a, b, c) => op::ANDI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
DIV(a, b, c) => op::DIV::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
DIVI(a, b, c) => op::DIVI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
EQ(a, b, c) => op::EQ::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
EXP(a, b, c) => op::EXP::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
EXPI(a, b, c) => op::EXPI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
GT(a, b, c) => op::GT::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
LT(a, b, c) => op::LT::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
MLOG(a, b, c) => op::MLOG::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
MOD(a, b, c) => op::MOD::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
MODI(a, b, c) => op::MODI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
MOVE(a, b) => op::MOVE::new(a.to_reg_id(), b.to_reg_id()).into(),
MOVI(a, b) => op::MOVI::new(a.to_reg_id(), b.as_imm18().unwrap()).into(),
MROO(a, b, c) => op::MROO::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
MUL(a, b, c) => op::MUL::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
MULI(a, b, c) => op::MULI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
NOOP => op::NOOP::new().into(),
NOT(a, b) => op::NOT::new(a.to_reg_id(), b.to_reg_id()).into(),
OR(a, b, c) => op::OR::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
ORI(a, b, c) => op::ORI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
SLL(a, b, c) => op::SLL::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
SLLI(a, b, c) => op::SLLI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
SRL(a, b, c) => op::SRL::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
SRLI(a, b, c) => op::SRLI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
SUB(a, b, c) => op::SUB::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
SUBI(a, b, c) => op::SUBI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
XOR(a, b, c) => op::XOR::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
XORI(a, b, c) => op::XORI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
WQOP(a, b, c, d) => op::WQOP::new(
a.to_reg_id(),
b.to_reg_id(),
c.to_reg_id(),
d.value().into(),
)
.into(),
WQML(a, b, c, d) => op::WQML::new(
a.to_reg_id(),
b.to_reg_id(),
c.to_reg_id(),
d.value().into(),
)
.into(),
WQDV(a, b, c, d) => op::WQDV::new(
a.to_reg_id(),
b.to_reg_id(),
c.to_reg_id(),
d.value().into(),
)
.into(),
WQMD(a, b, c, d) => {
op::WQMD::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id(), d.to_reg_id()).into()
}
WQCM(a, b, c, d) => op::WQCM::new(
a.to_reg_id(),
b.to_reg_id(),
c.to_reg_id(),
d.value().into(),
)
.into(),
WQAM(a, b, c, d) => {
op::WQAM::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id(), d.to_reg_id()).into()
}
WQMM(a, b, c, d) => {
op::WQMM::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id(), d.to_reg_id()).into()
}
/* Control Flow Instructions */
JMP(a) => op::JMP::new(a.to_reg_id()).into(),
JI(a) => op::JI::new(a.value().into()).into(),
JNE(a, b, c) => op::JNE::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
JNEI(a, b, c) => op::JNEI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
JNZI(a, b) => op::JNZI::new(a.to_reg_id(), b.as_imm18().unwrap()).into(),
JMPB(a, b) => op::JMPB::new(a.to_reg_id(), b.as_imm18().unwrap()).into(),
JMPF(a, b) => op::JMPF::new(a.to_reg_id(), b.as_imm18().unwrap()).into(),
JNZB(a, b, c) => op::JNZB::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
JNZF(a, b, c) => op::JNZF::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
JNEB(a, b, c, d) => op::JNEB::new(
a.to_reg_id(),
b.to_reg_id(),
c.to_reg_id(),
d.value().into(),
)
.into(),
JNEF(a, b, c, d) => op::JNEF::new(
a.to_reg_id(),
b.to_reg_id(),
c.to_reg_id(),
d.value().into(),
)
.into(),
JAL(a, b, c) => op::JAL::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
RET(a) => op::RET::new(a.to_reg_id()).into(),
/* Memory Instructions */
ALOC(a) => op::ALOC::new(a.to_reg_id()).into(),
CFEI(a) if a.value() == 0 => return FuelAsmData::Instructions(vec![]),
CFEI(a) => op::CFEI::new(a.value().into()).into(),
CFSI(a) if a.value() == 0 => return FuelAsmData::Instructions(vec![]),
CFSI(a) => op::CFSI::new(a.value().into()).into(),
CFE(a) => op::CFE::new(a.to_reg_id()).into(),
CFS(a) => op::CFS::new(a.to_reg_id()).into(),
LB(a, b, c) => op::LB::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
LW(a, b, c) => op::LW::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
MCL(a, b) => op::MCL::new(a.to_reg_id(), b.to_reg_id()).into(),
MCLI(a, b) => op::MCLI::new(a.to_reg_id(), b.as_imm18().unwrap()).into(),
MCP(a, b, c) => op::MCP::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
MCPI(a, b, c) => op::MCPI::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
MEQ(a, b, c, d) => {
op::MEQ::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id(), d.to_reg_id()).into()
}
PSHH(mask) => op::PSHH::new(mask.value().into()).into(),
PSHL(mask) => op::PSHL::new(mask.value().into()).into(),
POPH(mask) => op::POPH::new(mask.value().into()).into(),
POPL(mask) => op::POPL::new(mask.value().into()).into(),
SB(a, b, c) => op::SB::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
SW(a, b, c) => op::SW::new(a.to_reg_id(), b.to_reg_id(), c.value().into()).into(),
/* Contract Instructions */
BAL(a, b, c) => op::BAL::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id()).into(),
BHEI(a) => op::BHEI::new(a.to_reg_id()).into(),
BHSH(a, b) => op::BHSH::new(a.to_reg_id(), b.to_reg_id()).into(),
BURN(a, b) => op::BURN::new(a.to_reg_id(), b.to_reg_id()).into(),
CALL(a, b, c, d) => {
op::CALL::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id(), d.to_reg_id()).into()
}
CB(a) => op::CB::new(a.to_reg_id()).into(),
CCP(a, b, c, d) => {
op::CCP::new(a.to_reg_id(), b.to_reg_id(), c.to_reg_id(), d.to_reg_id()).into()
}
CROO(a, b) => op::CROO::new(a.to_reg_id(), b.to_reg_id()).into(),
CSIZ(a, b) => op::CSIZ::new(a.to_reg_id(), b.to_reg_id()).into(),
BSIZ(a, b) => op::BSIZ::new(a.to_reg_id(), b.to_reg_id()).into(),
LDC(a, b, c, d) => op::LDC::new(
a.to_reg_id(),
b.to_reg_id(),
c.to_reg_id(),
d.value().into(),
)
.into(),
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/asm_lang/mod.rs | sway-core/src/asm_lang/mod.rs | //! This module contains things that I need from the VM to build that we will eventually import
//! from the VM when it is ready.
//! Basically this is copy-pasted until things are public and it can be properly imported.
//!
//! Only things needed for opcode serialization and generation are included here.
#![allow(dead_code)]
pub(crate) mod allocated_ops;
pub(crate) mod virtual_immediate;
pub(crate) mod virtual_ops;
pub(crate) mod virtual_register;
use indexmap::IndexMap;
pub(crate) use virtual_immediate::*;
pub(crate) use virtual_ops::*;
pub(crate) use virtual_register::*;
use crate::{
asm_generation::fuel::{data_section::DataId, register_allocator::RegisterPool},
asm_lang::allocated_ops::{AllocatedInstruction, AllocatedRegister},
language::AsmRegister,
Ident,
};
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::{span::Span, Spanned};
use either::Either;
use std::{
collections::{BTreeSet, HashMap},
fmt::{self, Write},
hash::Hash,
};
/// The column where the ; for comments starts
const COMMENT_START_COLUMN: usize = 40;
fn fmt_opcode_and_comment(
opcode: String,
comment: &str,
fmtr: &mut fmt::Formatter<'_>,
) -> fmt::Result {
// We want the comment to be at the `COMMENT_START_COLUMN` offset to the right,
// to not interfere with the ASM but to be aligned.
// Some operations like, e.g., data section offset, can span multiple lines.
// In that case, we put the comment at the end of the last line, aligned.
let mut op_and_comment = opcode;
if !comment.is_empty() {
let mut op_length = match op_and_comment.rfind('\n') {
Some(new_line_index) => op_and_comment.len() - new_line_index - 1,
None => op_and_comment.len(),
};
while op_length < COMMENT_START_COLUMN {
op_and_comment.push(' ');
op_length += 1;
}
write!(op_and_comment, "; {comment}")?;
}
write!(fmtr, "{op_and_comment}")
}
impl From<&AsmRegister> for VirtualRegister {
fn from(o: &AsmRegister) -> Self {
VirtualRegister::Virtual(o.name.clone())
}
}
#[derive(Debug, Clone)]
pub(crate) struct Op {
pub(crate) opcode: Either<VirtualOp, OrganizationalOp>,
/// A descriptive comment for ASM readability.
///
/// Comments are a part of the compiler output and meant to
/// help both Sway developers interested in the generated ASM
/// and the Sway compiler developers.
///
/// Comments follow these guidelines:
/// - they start with an imperative verb. E.g.: "allocate" and not "allocating".
/// - they start with a lowercase letter. E.g.: "allocate" and not "Allocate".
/// - they do not end in punctuation. E.g.: "store value" and not "store value.".
/// - they use full words. E.g.: "load return address" and not "load reta" or "load return addr".
/// - abbreviations are written in upper-case. E.g.: "ABI" and not "abi".
/// - names (e.g., function, argument, etc.) are written without quotes. E.g. "main" and not "'main'".
/// - assembly operations are written in lowercase. E.g.: "move" and not "MOVE".
/// - they are short and concise.
/// - if an operation is a part of a logical group of operations, start the comment
/// by a descriptive group name enclosed in square brackets and followed by colon.
/// The remaining part of the comment follows the above guidelines. E.g.:
/// "[bitcast to bool]: convert value to inverted boolean".
pub(crate) comment: String,
pub(crate) owning_span: Option<Span>,
}
#[derive(Clone, Debug)]
pub(crate) struct AllocatedAbstractOp {
pub(crate) opcode: Either<AllocatedInstruction, ControlFlowOp<AllocatedRegister>>,
/// A descriptive comment for ASM readability.
///
/// For writing guidelines, see [Op::comment].
pub(crate) comment: String,
pub(crate) owning_span: Option<Span>,
}
#[derive(Clone, Debug)]
pub(crate) struct RealizedOp {
pub(crate) opcode: AllocatedInstruction,
/// A descriptive comment for ASM readability.
///
/// For writing guidelines, see [Op::comment].
pub(crate) comment: String,
pub(crate) owning_span: Option<Span>,
}
impl Op {
/// Moves the stack pointer by the given amount (i.e. allocates stack memory)
pub(crate) fn unowned_stack_allocate_memory(
size_to_allocate_in_bytes: VirtualImmediate24,
) -> Self {
Op {
opcode: Either::Left(VirtualOp::CFEI(
VirtualRegister::Constant(ConstantRegister::StackPointer),
size_to_allocate_in_bytes,
)),
comment: String::new(),
owning_span: None,
}
}
pub(crate) fn unowned_new_with_comment(opcode: VirtualOp, comment: impl Into<String>) -> Self {
Op {
opcode: Either::Left(opcode),
comment: comment.into(),
owning_span: None,
}
}
pub(crate) fn new(opcode: VirtualOp, owning_span: Span) -> Self {
Op {
opcode: Either::Left(opcode),
comment: String::new(),
owning_span: Some(owning_span),
}
}
pub(crate) fn new_with_comment(
opcode: VirtualOp,
owning_span: Span,
comment: impl Into<String>,
) -> Self {
let comment = comment.into();
Op {
opcode: Either::Left(opcode),
comment,
owning_span: Some(owning_span),
}
}
/// Given a label, creates the actual asm line to put in the ASM which represents a label
pub(crate) fn jump_label(label: Label, owning_span: Span) -> Self {
Op {
opcode: Either::Right(OrganizationalOp::Label(label)),
comment: String::new(),
owning_span: Some(owning_span),
}
}
/// Loads the data from [DataId] `data` into [VirtualRegister] `reg`.
pub(crate) fn unowned_load_data_comment(
reg: VirtualRegister,
data: DataId,
comment: impl Into<String>,
) -> Self {
Op {
opcode: Either::Left(VirtualOp::LoadDataId(reg, data)),
comment: comment.into(),
owning_span: None,
}
}
/// Given a label, creates the actual asm line to put in the ASM which represents a label.
/// Also attaches a comment to it.
pub(crate) fn unowned_jump_label_comment(label: Label, comment: impl Into<String>) -> Self {
Op {
opcode: Either::Right(OrganizationalOp::Label(label)),
comment: comment.into(),
owning_span: None,
}
}
/// Given a label, creates the actual asm line to put in the ASM which represents a label.
/// Also attaches a comment to it.
pub(crate) fn jump_label_comment(
label: Label,
owning_span: Span,
comment: impl Into<String>,
) -> Self {
Op {
opcode: Either::Right(OrganizationalOp::Label(label)),
comment: comment.into(),
owning_span: Some(owning_span),
}
}
/// Given a label, creates the actual asm line to put in the ASM which represents a label
pub(crate) fn unowned_jump_label(label: Label) -> Self {
Op {
opcode: Either::Right(OrganizationalOp::Label(label)),
comment: String::new(),
owning_span: None,
}
}
/// Moves the register in the second argument into the register in the first argument
pub(crate) fn register_move(
r1: VirtualRegister,
r2: VirtualRegister,
comment: impl Into<String>,
owning_span: Option<Span>,
) -> Self {
Op {
opcode: Either::Left(VirtualOp::MOVE(r1, r2)),
comment: comment.into(),
owning_span,
}
}
pub(crate) fn new_comment(comm: impl Into<String>) -> Self {
Op {
opcode: Either::Right(OrganizationalOp::Comment),
comment: comm.into(),
owning_span: None,
}
}
pub(crate) fn jump_to_label(label: Label) -> Self {
Op {
opcode: Either::Right(OrganizationalOp::Jump {
to: label,
type_: JumpType::Unconditional,
}),
comment: String::new(),
owning_span: None,
}
}
pub(crate) fn jump_to_label_comment(label: Label, comment: impl Into<String>) -> Self {
Op {
opcode: Either::Right(OrganizationalOp::Jump {
to: label,
type_: JumpType::Unconditional,
}),
comment: comment.into(),
owning_span: None,
}
}
/// Jumps to [Label] `label` if the given [VirtualRegister] `reg0` is not equal to zero.
pub(crate) fn jump_if_not_zero(reg0: VirtualRegister, label: Label) -> Self {
Op {
opcode: Either::Right(OrganizationalOp::Jump {
to: label,
type_: JumpType::NotZero(reg0),
}),
comment: String::new(),
owning_span: None,
}
}
/// Jumps to [Label] `label` if the given [VirtualRegister] `reg0` is not equal to zero.
pub(crate) fn jump_if_not_zero_comment(
reg0: VirtualRegister,
label: Label,
comment: impl Into<String>,
) -> Self {
Op {
opcode: Either::Right(OrganizationalOp::Jump {
to: label,
type_: JumpType::NotZero(reg0),
}),
comment: comment.into(),
owning_span: None,
}
}
pub(crate) fn parse_opcode(
handler: &Handler,
name: &Ident,
args: &[VirtualRegister],
immediate: &Option<Ident>,
whole_op_span: Span,
) -> Result<VirtualOp, ErrorEmitted> {
Ok(match name.as_str() {
/* Arithmetic/Logic (ALU) Instructions */
"add" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::ADD(r1, r2, r3)
}
"addi" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::ADDI(r1, r2, imm)
}
"and" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::AND(r1, r2, r3)
}
"andi" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::ANDI(r1, r2, imm)
}
"div" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::DIV(r1, r2, r3)
}
"divi" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::DIVI(r1, r2, imm)
}
"eq" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::EQ(r1, r2, r3)
}
"exp" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::EXP(r1, r2, r3)
}
"expi" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::EXPI(r1, r2, imm)
}
"gt" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::GT(r1, r2, r3)
}
"lt" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::LT(r1, r2, r3)
}
"mlog" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::MLOG(r1, r2, r3)
}
"mod" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::MOD(r1, r2, r3)
}
"modi" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::MODI(r1, r2, imm)
}
"move" => {
let (r1, r2) = two_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::MOVE(r1, r2)
}
"movi" => {
let (r1, imm) = single_reg_imm_18(handler, args, immediate, whole_op_span)?;
VirtualOp::MOVI(r1, imm)
}
"mroo" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::MROO(r1, r2, r3)
}
"mul" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::MUL(r1, r2, r3)
}
"muli" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::MULI(r1, r2, imm)
}
"noop" => VirtualOp::NOOP,
"not" => {
let (r1, r2) = two_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::NOT(r1, r2)
}
"or" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::OR(r1, r2, r3)
}
"ori" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::ORI(r1, r2, imm)
}
"sll" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::SLL(r1, r2, r3)
}
"slli" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::SLLI(r1, r2, imm)
}
"srl" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::SRL(r1, r2, r3)
}
"srli" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::SRLI(r1, r2, imm)
}
"sub" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::SUB(r1, r2, r3)
}
"subi" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::SUBI(r1, r2, imm)
}
"wqcm" => {
let (r1, r2, r3, imm) = three_regs_imm_06(handler, args, immediate, whole_op_span)?;
VirtualOp::WQCM(r1, r2, r3, imm)
}
"wqop" => {
let (r1, r2, r3, imm) = three_regs_imm_06(handler, args, immediate, whole_op_span)?;
VirtualOp::WQOP(r1, r2, r3, imm)
}
"wqml" => {
let (r1, r2, r3, imm) = three_regs_imm_06(handler, args, immediate, whole_op_span)?;
VirtualOp::WQML(r1, r2, r3, imm)
}
"wqdv" => {
let (r1, r2, r3, imm) = three_regs_imm_06(handler, args, immediate, whole_op_span)?;
VirtualOp::WQDV(r1, r2, r3, imm)
}
"wqmd" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::WQMD(r1, r2, r3, r4)
}
"wqam" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::WQAM(r1, r2, r3, r4)
}
"wqmm" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::WQMM(r1, r2, r3, r4)
}
"xor" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::XOR(r1, r2, r3)
}
"xori" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::XORI(r1, r2, imm)
}
/* Control Flow Instructions */
"jmp" => {
let r1 = single_reg(handler, args, immediate, whole_op_span)?;
VirtualOp::JMP(r1)
}
"ji" => {
let imm = single_imm_24(handler, args, immediate, whole_op_span)?;
VirtualOp::JI(imm)
}
"jne" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::JNE(r1, r2, r3)
}
"jnei" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::JNEI(r1, r2, imm)
}
"jnzi" => {
let (r1, imm) = single_reg_imm_18(handler, args, immediate, whole_op_span)?;
VirtualOp::JNZI(r1, imm)
}
"jmpb" => {
let (r1, imm) = single_reg_imm_18(handler, args, immediate, whole_op_span)?;
VirtualOp::JMPB(r1, imm)
}
"jmpf" => {
let (r1, imm) = single_reg_imm_18(handler, args, immediate, whole_op_span)?;
VirtualOp::JMPF(r1, imm)
}
"jnzb" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::JNZB(r1, r2, imm)
}
"jnzf" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::JNZF(r1, r2, imm)
}
"jneb" => {
let (r1, r2, r3, imm) = three_regs_imm_06(handler, args, immediate, whole_op_span)?;
VirtualOp::JNEB(r1, r2, r3, imm)
}
"jnef" => {
let (r1, r2, r3, imm) = three_regs_imm_06(handler, args, immediate, whole_op_span)?;
VirtualOp::JNEF(r1, r2, r3, imm)
}
"jal" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::JAL(r1, r2, imm)
}
"ret" => {
let r1 = single_reg(handler, args, immediate, whole_op_span)?;
VirtualOp::RET(r1)
}
/* Memory Instructions */
"aloc" => {
let r1 = single_reg(handler, args, immediate, whole_op_span)?;
VirtualOp::ALOC(VirtualRegister::Constant(ConstantRegister::HeapPointer), r1)
}
"cfei" => {
let imm = single_imm_24(handler, args, immediate, whole_op_span)?;
VirtualOp::CFEI(
VirtualRegister::Constant(ConstantRegister::StackPointer),
imm,
)
}
"cfsi" => {
let imm = single_imm_24(handler, args, immediate, whole_op_span)?;
VirtualOp::CFSI(
VirtualRegister::Constant(ConstantRegister::StackPointer),
imm,
)
}
"cfe" => {
let r1 = single_reg(handler, args, immediate, whole_op_span)?;
VirtualOp::CFE(
VirtualRegister::Constant(ConstantRegister::StackPointer),
r1,
)
}
"cfs" => {
let r1 = single_reg(handler, args, immediate, whole_op_span)?;
VirtualOp::CFS(
VirtualRegister::Constant(ConstantRegister::StackPointer),
r1,
)
}
"lb" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::LB(r1, r2, imm)
}
"lw" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::LW(r1, r2, imm)
}
"mcl" => {
let (r1, r2) = two_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::MCL(r1, r2)
}
"mcli" => {
let (r1, imm) = single_reg_imm_18(handler, args, immediate, whole_op_span)?;
VirtualOp::MCLI(r1, imm)
}
"mcp" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::MCP(r1, r2, r3)
}
"mcpi" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::MCPI(r1, r2, imm)
}
"meq" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::MEQ(r1, r2, r3, r4)
}
"sb" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::SB(r1, r2, imm)
}
"sw" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::SW(r1, r2, imm)
}
/* Contract Instructions */
"bal" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::BAL(r1, r2, r3)
}
"bhei" => {
let r1 = single_reg(handler, args, immediate, whole_op_span)?;
VirtualOp::BHEI(r1)
}
"bhsh" => {
let (r1, r2) = two_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::BHSH(r1, r2)
}
"burn" => {
let (r1, r2) = two_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::BURN(r1, r2)
}
"call" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::CALL(r1, r2, r3, r4)
}
"cb" => {
let r1 = single_reg(handler, args, immediate, whole_op_span)?;
VirtualOp::CB(r1)
}
"ccp" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::CCP(r1, r2, r3, r4)
}
"croo" => {
let (r1, r2) = two_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::CROO(r1, r2)
}
"csiz" => {
let (r1, r2) = two_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::CSIZ(r1, r2)
}
"bsiz" => {
let (r1, r2) = two_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::BSIZ(r1, r2)
}
"ldc" => {
let (r1, r2, r3, i0) = three_regs_imm_06(handler, args, immediate, whole_op_span)?;
VirtualOp::LDC(r1, r2, r3, i0)
}
"bldd" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::BLDD(r1, r2, r3, r4)
}
"log" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::LOG(r1, r2, r3, r4)
}
"logd" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::LOGD(r1, r2, r3, r4)
}
"mint" => {
let (r1, r2) = two_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::MINT(r1, r2)
}
"retd" => {
let (r1, r2) = two_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::RETD(r1, r2)
}
"rvrt" => {
let r1 = single_reg(handler, args, immediate, whole_op_span)?;
VirtualOp::RVRT(r1)
}
"smo" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::SMO(r1, r2, r3, r4)
}
"scwq" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::SCWQ(r1, r2, r3)
}
"srw" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::SRW(r1, r2, r3)
}
"srwq" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::SRWQ(r1, r2, r3, r4)
}
"sww" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::SWW(r1, r2, r3)
}
"swwq" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::SWWQ(r1, r2, r3, r4)
}
"time" => {
let (r1, r2) = two_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::TIME(r1, r2)
}
"tr" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::TR(r1, r2, r3)
}
"tro" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::TRO(r1, r2, r3, r4)
}
/* Cryptographic Instructions */
"eck1" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::ECK1(r1, r2, r3)
}
"ecr1" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::ECR1(r1, r2, r3)
}
"ed19" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::ED19(r1, r2, r3, r4)
}
"k256" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::K256(r1, r2, r3)
}
"s256" => {
let (r1, r2, r3) = three_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::S256(r1, r2, r3)
}
"ecop" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::ECOP(r1, r2, r3, r4)
}
"epar" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::EPAR(r1, r2, r3, r4)
}
/* Other Instructions */
"ecal" => {
let (r1, r2, r3, r4) = four_regs(handler, args, immediate, whole_op_span)?;
VirtualOp::ECAL(r1, r2, r3, r4)
}
"flag" => {
let r1 = single_reg(handler, args, immediate, whole_op_span)?;
VirtualOp::FLAG(r1)
}
"gm" => {
let (r1, imm) = single_reg_imm_18(handler, args, immediate, whole_op_span)?;
VirtualOp::GM(r1, imm)
}
"gtf" => {
let (r1, r2, imm) = two_regs_imm_12(handler, args, immediate, whole_op_span)?;
VirtualOp::GTF(r1, r2, imm)
}
/* Non-VM Instructions */
"blob" => {
let imm = single_imm_24(handler, args, immediate, whole_op_span)?;
VirtualOp::BLOB(imm)
}
_ => {
return Err(handler.emit_err(CompileError::UnrecognizedOp {
op_name: name.clone(),
span: name.span(),
}));
}
})
}
pub(crate) fn registers(&self) -> BTreeSet<&VirtualRegister> {
match &self.opcode {
Either::Left(virt_op) => virt_op.registers(),
Either::Right(org_op) => org_op.registers(),
}
}
pub(crate) fn use_registers(&self) -> BTreeSet<&VirtualRegister> {
match &self.opcode {
Either::Left(virt_op) => virt_op.use_registers(),
Either::Right(org_op) => org_op.use_registers(),
}
}
pub(crate) fn use_registers_mut(&mut self) -> BTreeSet<&mut VirtualRegister> {
match &mut self.opcode {
Either::Left(virt_op) => virt_op.use_registers_mut(),
Either::Right(org_op) => org_op.use_registers_mut(),
}
}
pub(crate) fn def_registers(&self) -> BTreeSet<&VirtualRegister> {
match &self.opcode {
Either::Left(virt_op) => virt_op.def_registers(),
Either::Right(org_op) => org_op.def_registers(),
}
}
pub(crate) fn def_const_registers(&self) -> BTreeSet<&VirtualRegister> {
match &self.opcode {
Either::Left(virt_op) => virt_op.def_const_registers(),
Either::Right(org_op) => org_op.def_const_registers(),
}
}
pub(crate) fn successors(
&self,
index: usize,
ops: &[Op],
label_to_index: &HashMap<Label, usize>,
) -> Vec<usize> {
match &self.opcode {
Either::Left(virt_op) => virt_op.successors(index, ops),
Either::Right(org_op) => org_op.successors(index, ops, label_to_index),
}
}
pub(crate) fn update_register(
&self,
reg_to_reg_map: &IndexMap<&VirtualRegister, &VirtualRegister>,
) -> Self {
Op {
opcode: match &self.opcode {
Either::Left(virt_op) => Either::Left(virt_op.update_register(reg_to_reg_map)),
Either::Right(org_op) => Either::Right(org_op.update_register(reg_to_reg_map)),
},
comment: self.comment.clone(),
owning_span: self.owning_span.clone(),
}
}
pub(crate) fn allocate_registers(
&self,
pool: &RegisterPool,
) -> Either<AllocatedInstruction, ControlFlowOp<AllocatedRegister>> {
match &self.opcode {
Either::Left(virt_op) => Either::Left(virt_op.allocate_registers(pool)),
Either::Right(org_op) => Either::Right(org_op.allocate_registers(pool)),
}
}
}
fn single_reg(
handler: &Handler,
args: &[VirtualRegister],
immediate: &Option<Ident>,
whole_op_span: Span,
) -> Result<VirtualRegister, ErrorEmitted> {
if args.len() > 1 {
handler.emit_err(CompileError::IncorrectNumberOfAsmRegisters {
expected: 1,
received: args.len(),
span: whole_op_span.clone(),
});
}
let reg = match args.first() {
Some(reg) => reg,
_ => {
return Err(
handler.emit_err(CompileError::IncorrectNumberOfAsmRegisters {
span: whole_op_span,
expected: 1,
received: args.len(),
}),
);
}
};
match immediate {
None => (),
Some(i) => {
handler.emit_err(CompileError::UnnecessaryImmediate { span: i.span() });
}
};
Ok(reg.clone())
}
fn two_regs(
handler: &Handler,
args: &[VirtualRegister],
immediate: &Option<Ident>,
whole_op_span: Span,
) -> Result<(VirtualRegister, VirtualRegister), ErrorEmitted> {
if args.len() > 2 {
handler.emit_err(CompileError::IncorrectNumberOfAsmRegisters {
span: whole_op_span.clone(),
expected: 2,
received: args.len(),
});
}
let (reg, reg2) = match (args.first(), args.get(1)) {
(Some(reg), Some(reg2)) => (reg, reg2),
_ => {
return Err(
handler.emit_err(CompileError::IncorrectNumberOfAsmRegisters {
span: whole_op_span,
expected: 2,
received: args.len(),
}),
);
}
};
match immediate {
None => (),
Some(i) => {
handler.emit_err(CompileError::UnnecessaryImmediate { span: i.span() });
}
};
Ok((reg.clone(), reg2.clone()))
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/asm_lang/virtual_register.rs | sway-core/src/asm_lang/virtual_register.rs | use crate::fuel_prelude::fuel_asm;
use std::fmt;
/// Represents virtual registers that have yet to be allocated.
/// Note that only the Virtual variant will be allocated, and the Constant variant refers to
/// reserved registers.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Debug, Clone)]
pub enum VirtualRegister {
Virtual(String),
Constant(ConstantRegister),
}
impl VirtualRegister {
pub fn is_virtual(&self) -> bool {
matches!(self, Self::Virtual(_))
}
}
impl From<&VirtualRegister> for VirtualRegister {
fn from(register: &VirtualRegister) -> VirtualRegister {
register.clone()
}
}
impl From<ConstantRegister> for VirtualRegister {
fn from(constant_register: ConstantRegister) -> Self {
VirtualRegister::Constant(constant_register)
}
}
impl fmt::Display for VirtualRegister {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
VirtualRegister::Virtual(name) => write!(f, "$r{name}"),
VirtualRegister::Constant(name) => {
write!(f, "{name}")
}
}
}
}
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
/// These are the special registers defined in the spec
pub enum ConstantRegister {
// Below are VM-reserved registers
Zero,
One,
Overflow,
ProgramCounter,
StackStartPointer,
StackPointer,
FramePointer,
HeapPointer,
Error,
GlobalGas,
ContextGas,
Balance,
InstructionStart,
ReturnValue,
ReturnLength,
Flags,
// Below are compiler-reserved registers
DataSectionStart,
CallReturnAddress,
CallReturnValue,
Scratch,
LocalsBase,
// Registers for the first NUM_ARG_REGISTERS function arguments.
FuncArg0,
FuncArg1,
FuncArg2,
FuncArg3,
FuncArg4,
FuncArg5,
}
impl ConstantRegister {
pub(crate) fn parse_register_name(raw: &str) -> Option<ConstantRegister> {
use ConstantRegister::*;
Some(match raw {
"zero" => Zero,
"one" => One,
"of" => Overflow,
"pc" => ProgramCounter,
"ssp" => StackStartPointer,
"sp" => StackPointer,
"fp" => FramePointer,
"hp" => HeapPointer,
"err" => Error,
"ggas" => GlobalGas,
"cgas" => ContextGas,
"bal" => Balance,
"is" => InstructionStart,
"flag" => Flags,
"retl" => ReturnLength,
"ret" => ReturnValue,
"ds" => DataSectionStart,
_ => return None,
})
}
}
use crate::asm_generation::fuel::compiler_constants;
impl ConstantRegister {
pub(crate) fn to_reg_id(self) -> fuel_asm::RegId {
use ConstantRegister::*;
match self {
Zero => fuel_asm::RegId::ZERO,
One => fuel_asm::RegId::ONE,
Overflow => fuel_asm::RegId::OF,
ProgramCounter => fuel_asm::RegId::PC,
StackStartPointer => fuel_asm::RegId::SSP,
StackPointer => fuel_asm::RegId::SP,
FramePointer => fuel_asm::RegId::FP,
HeapPointer => fuel_asm::RegId::HP,
Error => fuel_asm::RegId::ERR,
GlobalGas => fuel_asm::RegId::GGAS,
ContextGas => fuel_asm::RegId::CGAS,
Balance => fuel_asm::RegId::BAL,
InstructionStart => fuel_asm::RegId::IS,
ReturnValue => fuel_asm::RegId::RET,
ReturnLength => fuel_asm::RegId::RETL,
Flags => fuel_asm::RegId::FLAG,
DataSectionStart => fuel_asm::RegId::new(compiler_constants::DATA_SECTION_REGISTER),
CallReturnAddress => fuel_asm::RegId::new(compiler_constants::RETURN_ADDRESS_REGISTER),
CallReturnValue => fuel_asm::RegId::new(compiler_constants::RETURN_VALUE_REGISTER),
Scratch => fuel_asm::RegId::new(compiler_constants::SCRATCH_REGISTER),
LocalsBase => fuel_asm::RegId::new(compiler_constants::LOCALS_BASE),
FuncArg0 => fuel_asm::RegId::new(compiler_constants::ARG_REG0),
FuncArg1 => fuel_asm::RegId::new(compiler_constants::ARG_REG1),
FuncArg2 => fuel_asm::RegId::new(compiler_constants::ARG_REG2),
FuncArg3 => fuel_asm::RegId::new(compiler_constants::ARG_REG3),
FuncArg4 => fuel_asm::RegId::new(compiler_constants::ARG_REG4),
FuncArg5 => fuel_asm::RegId::new(compiler_constants::ARG_REG5),
}
}
pub(crate) const ARG_REGS: [ConstantRegister; compiler_constants::NUM_ARG_REGISTERS as usize] = [
ConstantRegister::FuncArg0,
ConstantRegister::FuncArg1,
ConstantRegister::FuncArg2,
ConstantRegister::FuncArg3,
ConstantRegister::FuncArg4,
ConstantRegister::FuncArg5,
];
}
impl fmt::Display for ConstantRegister {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use ConstantRegister::*;
let text = match self {
Zero => "$zero",
One => "$one",
Overflow => "$of",
ProgramCounter => "$pc",
StackStartPointer => "$ssp",
StackPointer => "$sp",
FramePointer => "$fp",
HeapPointer => "$hp",
Error => "$err",
GlobalGas => "$ggas",
ContextGas => "$cgas",
Balance => "$bal",
InstructionStart => "$is",
ReturnValue => "$ret",
ReturnLength => "$retl",
Flags => "$flag",
// two `$` signs denotes this is a compiler-reserved register and not a
// VM-reserved register
DataSectionStart => "$$ds",
CallReturnAddress => "$$reta",
CallReturnValue => "$$retv",
Scratch => "$$tmp",
LocalsBase => "$$locbase",
FuncArg0 => "$$arg0",
FuncArg1 => "$$arg1",
FuncArg2 => "$$arg2",
FuncArg3 => "$$arg3",
FuncArg4 => "$$arg4",
FuncArg5 => "$$arg5",
};
write!(f, "{text}")
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/visibility.rs | sway-core/src/language/visibility.rs | use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Visibility {
Private,
Public,
}
impl Visibility {
pub fn is_public(&self) -> bool {
matches!(self, &Visibility::Public)
}
pub fn is_private(&self) -> bool {
!self.is_public()
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/asm.rs | sway-core/src/language/asm.rs | use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use sway_types::{BaseIdent, Ident, Span};
#[derive(Debug, Clone, Eq, Serialize, Deserialize)]
pub struct AsmOp {
pub(crate) op_name: Ident,
pub(crate) op_args: Vec<Ident>,
pub(crate) span: Span,
pub(crate) immediate: Option<Ident>,
}
impl AsmOp {
pub fn retd(ptr: BaseIdent, len: BaseIdent) -> Self {
AsmOp {
op_name: Ident::new_no_span("retd".to_string()),
op_args: vec![ptr, len],
span: Span::dummy(),
immediate: None,
}
}
}
impl Hash for AsmOp {
fn hash<H: Hasher>(&self, state: &mut H) {
self.op_name.hash(state);
self.op_args.hash(state);
if let Some(immediate) = self.immediate.clone() {
immediate.hash(state);
}
}
}
impl PartialEq for AsmOp {
fn eq(&self, other: &Self) -> bool {
self.op_name == other.op_name
&& self.op_args == other.op_args
&& if let (Some(l), Some(r)) = (self.immediate.clone(), other.immediate.clone()) {
l == r
} else {
true
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AsmRegister {
pub(crate) name: String,
}
impl From<AsmRegister> for String {
fn from(register: AsmRegister) -> String {
register.name
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/module.rs | sway-core/src/language/module.rs | use sway_types::Ident;
/// The name used within a module to refer to one of its submodules.
///
/// If an alias was given to the `mod`, this will be the alias. If not, this is the submodule's
/// library name.
pub type ModName = Ident;
pub trait HasModule<T>
where
T: HasSubmodules<Self>,
Self: Sized,
{
/// Returns the module of this submodule.
fn module(&self) -> &T;
}
pub trait HasSubmodules<E>
where
E: HasModule<Self>,
Self: Sized,
{
/// Returns the submodules of this module.
fn submodules(&self) -> &[(ModName, E)];
/// An iterator yielding all submodules recursively, depth-first.
fn submodules_recursive(&self) -> SubmodulesRecursive<Self, E> {
SubmodulesRecursive {
_module_type: std::marker::PhantomData,
submods: self.submodules().iter(),
current: None,
}
}
}
type NamedSubmodule<E> = (ModName, E);
type SubmoduleItem<'module, T, E> = (
&'module NamedSubmodule<E>,
Box<SubmodulesRecursive<'module, T, E>>,
);
/// Iterator type for iterating over submodules.
///
/// Used rather than `impl Iterator` to enable recursive submodule iteration.
pub struct SubmodulesRecursive<'module, T, E> {
_module_type: std::marker::PhantomData<T>,
submods: std::slice::Iter<'module, NamedSubmodule<E>>,
current: Option<SubmoduleItem<'module, T, E>>,
}
impl<'module, T, E> Iterator for SubmodulesRecursive<'module, T, E>
where
T: HasSubmodules<E> + 'module,
E: HasModule<T>,
{
type Item = &'module (ModName, E);
fn next(&mut self) -> Option<Self::Item> {
loop {
self.current = match self.current.take() {
None => match self.submods.next() {
None => return None,
Some(submod) => {
Some((submod, Box::new(submod.1.module().submodules_recursive())))
}
},
Some((submod, mut submods)) => match submods.next() {
Some(next) => {
self.current = Some((submod, submods));
return Some(next);
}
None => return Some(submod),
},
}
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/lazy_op.rs | sway-core/src/language/lazy_op.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum LazyOp {
And,
Or,
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/trace.rs | sway-core/src/language/trace.rs | /// The trace of a function suggests to the compiler whether or not a function should be backtraced.
#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash)]
pub enum Trace {
Always,
Never,
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/inline.rs | sway-core/src/language/inline.rs | /// The inline of a function suggests to the compiler whether or not a function should be inlined.
#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash)]
pub enum Inline {
Always,
Never,
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/literal.rs | sway-core/src/language/literal.rs | use crate::{type_system::*, Engines};
use serde::{Deserialize, Serialize};
use std::{
fmt,
hash::{Hash, Hasher},
num::{IntErrorKind, ParseIntError},
};
use sway_error::error::CompileError;
use sway_types::{integer_bits::IntegerBits, span, u256::U256};
#[derive(Debug, Clone, Eq, Serialize, Deserialize)]
pub enum Literal {
U8(u8),
U16(u16),
U32(u32),
U64(u64),
U256(U256),
String(span::Span),
Numeric(u64),
Boolean(bool),
B256([u8; 32]),
Binary(Vec<u8>),
}
impl Literal {
pub fn cast_value_to_u64(&self) -> Option<u64> {
match self {
Literal::U8(v) => Some(*v as u64),
Literal::U16(v) => Some(*v as u64),
Literal::U32(v) => Some(*v as u64),
Literal::U64(v) => Some(*v),
Literal::Numeric(v) => Some(*v),
_ => None,
}
}
}
impl Hash for Literal {
fn hash<H: Hasher>(&self, state: &mut H) {
use Literal::*;
match self {
U8(x) => {
state.write_u8(1);
x.hash(state);
}
U16(x) => {
state.write_u8(2);
x.hash(state);
}
U32(x) => {
state.write_u8(3);
x.hash(state);
}
U64(x) => {
state.write_u8(4);
x.hash(state);
}
U256(x) => {
state.write_u8(4);
x.hash(state);
}
Numeric(x) => {
state.write_u8(5);
x.hash(state);
}
String(inner) => {
state.write_u8(6);
inner.as_str().hash(state);
}
Boolean(x) => {
state.write_u8(7);
x.hash(state);
}
B256(x) => {
state.write_u8(8);
x.hash(state);
}
Binary(x) => {
state.write_u8(9);
x.hash(state);
}
}
}
}
impl PartialEq for Literal {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::U8(l0), Self::U8(r0)) => l0 == r0,
(Self::U16(l0), Self::U16(r0)) => l0 == r0,
(Self::U32(l0), Self::U32(r0)) => l0 == r0,
(Self::U64(l0), Self::U64(r0)) => l0 == r0,
(Self::U256(l0), Self::U256(r0)) => l0 == r0,
(Self::String(l0), Self::String(r0)) => *l0.as_str() == *r0.as_str(),
(Self::Numeric(l0), Self::Numeric(r0)) => l0 == r0,
(Self::Boolean(l0), Self::Boolean(r0)) => l0 == r0,
(Self::B256(l0), Self::B256(r0)) => l0 == r0,
(Self::Binary(l0), Self::Binary(r0)) => l0 == r0,
_ => false,
}
}
}
impl fmt::Display for Literal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Literal::U8(content) => content.to_string(),
Literal::U16(content) => content.to_string(),
Literal::U32(content) => content.to_string(),
Literal::U64(content) => content.to_string(),
Literal::U256(content) => content.to_string(),
Literal::Numeric(content) => content.to_string(),
Literal::String(content) => content.as_str().to_string(),
Literal::Boolean(content) => content.to_string(),
Literal::B256(content) => content
.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", "),
Literal::Binary(content) => content
.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", "),
};
write!(f, "{s}")
}
}
impl Literal {
#[allow(clippy::wildcard_in_or_patterns)]
pub(crate) fn handle_parse_int_error(
engines: &Engines,
e: ParseIntError,
ty: TypeInfo,
span: sway_types::Span,
) -> CompileError {
match e.kind() {
IntErrorKind::PosOverflow => CompileError::IntegerTooLarge {
ty: engines.help_out(ty).to_string(),
span,
},
IntErrorKind::NegOverflow => CompileError::IntegerTooSmall {
ty: engines.help_out(ty).to_string(),
span,
},
IntErrorKind::InvalidDigit => CompileError::IntegerContainsInvalidDigit {
ty: engines.help_out(ty).to_string(),
span,
},
IntErrorKind::Zero | IntErrorKind::Empty | _ => {
CompileError::Internal("Called incorrect internal sway-core on literal type.", span)
}
}
}
pub(crate) fn to_typeinfo(&self) -> TypeInfo {
match self {
Literal::String(_) => TypeInfo::StringSlice,
Literal::Numeric(_) => TypeInfo::Numeric,
Literal::U8(_) => TypeInfo::UnsignedInteger(IntegerBits::Eight),
Literal::U16(_) => TypeInfo::UnsignedInteger(IntegerBits::Sixteen),
Literal::U32(_) => TypeInfo::UnsignedInteger(IntegerBits::ThirtyTwo),
Literal::U64(_) => TypeInfo::UnsignedInteger(IntegerBits::SixtyFour),
Literal::U256(_) => TypeInfo::UnsignedInteger(IntegerBits::V256),
Literal::Boolean(_) => TypeInfo::Boolean,
Literal::B256(_) => TypeInfo::B256,
Literal::Binary(_) => TypeInfo::RawUntypedSlice,
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/mod.rs | sway-core/src/language/mod.rs | mod asm;
mod call_path;
mod inline;
mod lazy_op;
pub mod lexed;
mod literal;
mod module;
pub mod parsed;
pub mod programs;
mod purity;
mod trace;
pub mod ty;
mod visibility;
pub use asm::*;
pub use call_path::*;
pub use inline::*;
pub use lazy_op::*;
pub use literal::*;
pub use module::*;
pub use programs::*;
pub use purity::*;
pub use trace::*;
pub use visibility::*;
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/call_path.rs | sway-core/src/language/call_path.rs | use crate::{
engine_threading::{
DebugWithEngines, DisplayWithEngines, EqWithEngines, HashWithEngines, OrdWithEngines,
OrdWithEnginesContext, PartialEqWithEngines, PartialEqWithEnginesContext,
},
parsed::QualifiedPathType,
Engines, GenericArgument, Ident, Namespace,
};
use serde::{Deserialize, Serialize};
use std::{
cmp::Ordering,
fmt,
hash::{Hash, Hasher},
sync::Arc,
};
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::{span::Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CallPathTree {
pub qualified_call_path: QualifiedCallPath,
pub children: Vec<CallPathTree>,
}
impl HashWithEngines for CallPathTree {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let CallPathTree {
qualified_call_path,
children,
} = self;
qualified_call_path.hash(state, engines);
children.hash(state, engines);
}
}
impl EqWithEngines for CallPathTree {}
impl PartialEqWithEngines for CallPathTree {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let CallPathTree {
qualified_call_path,
children,
} = self;
qualified_call_path.eq(&other.qualified_call_path, ctx) && children.eq(&other.children, ctx)
}
}
impl<T: PartialEqWithEngines> EqWithEngines for Vec<T> {}
impl<T: PartialEqWithEngines> PartialEqWithEngines for Vec<T> {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
if self.len() != other.len() {
return false;
}
self.iter().zip(other.iter()).all(|(a, b)| a.eq(b, ctx))
}
}
impl OrdWithEngines for CallPathTree {
fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering {
let CallPathTree {
qualified_call_path: l_call_path,
children: l_children,
} = self;
let CallPathTree {
qualified_call_path: r_call_path,
children: r_children,
} = other;
l_call_path
.cmp(r_call_path, ctx)
.then_with(|| l_children.cmp(r_children, ctx))
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct QualifiedCallPath {
pub call_path: CallPath,
pub qualified_path_root: Option<Box<QualifiedPathType>>,
}
impl std::convert::From<Ident> for QualifiedCallPath {
fn from(other: Ident) -> Self {
QualifiedCallPath {
call_path: CallPath {
prefixes: vec![],
suffix: other,
callpath_type: CallPathType::Ambiguous,
},
qualified_path_root: None,
}
}
}
impl std::convert::From<CallPath> for QualifiedCallPath {
fn from(other: CallPath) -> Self {
QualifiedCallPath {
call_path: other,
qualified_path_root: None,
}
}
}
impl QualifiedCallPath {
pub fn to_call_path(self, handler: &Handler) -> Result<CallPath, ErrorEmitted> {
if let Some(qualified_path_root) = self.qualified_path_root {
Err(handler.emit_err(CompileError::Internal(
"Unexpected qualified path.",
qualified_path_root.as_trait_span,
)))
} else {
Ok(self.call_path)
}
}
}
impl HashWithEngines for QualifiedCallPath {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let QualifiedCallPath {
call_path,
qualified_path_root,
} = self;
call_path.hash(state);
qualified_path_root.hash(state, engines);
}
}
impl EqWithEngines for QualifiedCallPath {}
impl PartialEqWithEngines for QualifiedCallPath {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let QualifiedCallPath {
call_path,
qualified_path_root,
} = self;
PartialEqWithEngines::eq(call_path, &other.call_path, ctx)
&& qualified_path_root.eq(&other.qualified_path_root, ctx)
}
}
impl OrdWithEngines for QualifiedCallPath {
fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering {
let QualifiedCallPath {
call_path: l_call_path,
qualified_path_root: l_qualified_path_root,
} = self;
let QualifiedCallPath {
call_path: r_call_path,
qualified_path_root: r_qualified_path_root,
} = other;
l_call_path
.cmp(r_call_path)
.then_with(|| l_qualified_path_root.cmp(r_qualified_path_root, ctx))
}
}
impl DisplayWithEngines for QualifiedCallPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
if let Some(qualified_path_root) = &self.qualified_path_root {
write!(
f,
"{}::{}",
engines.help_out(qualified_path_root),
&self.call_path
)
} else {
write!(f, "{}", &self.call_path)
}
}
}
impl DebugWithEngines for QualifiedCallPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(f, "{}", engines.help_out(self))
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub enum CallPathType {
/// An unresolved path on the form `::X::Y::Z`. The path must be resolved relative to the
/// current package root module.
/// The path can be converted to a full path by prepending the package name, so if the path
/// `::X::Y::Z` occurs in package `A`, then the corresponding full path will be `A::X::Y::Z`.
RelativeToPackageRoot,
/// An unresolved path on the form `X::Y::Z`. The path must either be resolved relative to the
/// current module, in which case `X` is either a submodule or a name bound in the current
/// module, or as a full path, in which case `X` is the name of an external package.
/// If the path is resolved relative to the current module, and the current module has a module
/// path `A::B::C`, then the corresponding full path is `A::B::C::X::Y::Z`.
/// If the path is resolved as a full path, then the full path is `X::Y::Z`.
Ambiguous,
/// A full path on the form `X::Y::Z`. The first identifier `X` is the name of either the
/// current package or an external package.
/// After that comes a (possibly empty) series of names of submodules. Then comes the name of an
/// item (a type, a trait, a function, or something else declared in that module). Additionally,
/// there may be additional names such as the name of an enum variant or associated types.
Full,
}
/// In the expression `a::b::c()`, `a` and `b` are the prefixes and `c` is the suffix.
/// `c` can be any type `T`, but in practice `c` is either an `Ident` or a `TypeInfo`.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub struct CallPath<T = Ident> {
pub prefixes: Vec<Ident>,
pub suffix: T,
pub callpath_type: CallPathType,
}
impl EqWithEngines for CallPath {}
impl PartialEqWithEngines for CallPath {
fn eq(&self, other: &Self, _ctx: &PartialEqWithEnginesContext) -> bool {
self.prefixes == other.prefixes
&& self.suffix == other.suffix
&& self.callpath_type == other.callpath_type
}
}
impl<T: EqWithEngines> EqWithEngines for CallPath<T> {}
impl<T: PartialEqWithEngines> PartialEqWithEngines for CallPath<T> {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.prefixes == other.prefixes
&& self.suffix.eq(&other.suffix, ctx)
&& self.callpath_type == other.callpath_type
}
}
impl<T: OrdWithEngines> OrdWithEngines for CallPath<T> {
fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering {
self.prefixes
.cmp(&other.prefixes)
.then_with(|| self.suffix.cmp(&other.suffix, ctx))
.then_with(|| self.callpath_type.cmp(&other.callpath_type))
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct ResolvedCallPath<T, U = Ident> {
pub decl: T,
pub unresolved_call_path: CallPath<U>,
}
impl std::convert::From<Ident> for CallPath {
fn from(other: Ident) -> Self {
CallPath {
prefixes: vec![],
suffix: other,
callpath_type: CallPathType::Ambiguous,
}
}
}
impl<T> fmt::Display for CallPath<T>
where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// TODO: Remove this workaround once https://github.com/FuelLabs/sway/issues/7304 is fixed
// and uncomment the original code below.
if let Some((first_prefix, rest_prefixes)) = self.prefixes.split_first() {
let first_prefix = if !first_prefix.as_str().contains('-') {
first_prefix.as_str()
} else {
&first_prefix.as_str().replace('-', "_")
};
write!(f, "{first_prefix}::")?;
for prefix in rest_prefixes {
write!(f, "{}::", prefix.as_str())?;
}
}
write!(f, "{}", &self.suffix)
// for prefix in self.prefixes.iter() {
// write!(f, "{}::", prefix.as_str())?;
// }
// write!(f, "{}", &self.suffix)
}
}
impl<T: DisplayWithEngines> DisplayWithEngines for CallPath<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
// TODO: Remove this workaround once https://github.com/FuelLabs/sway/issues/7304 is fixed
// and uncomment the original code below.
if let Some((first_prefix, rest_prefixes)) = self.prefixes.split_first() {
let first_prefix = if !first_prefix.as_str().contains('-') {
first_prefix.as_str()
} else {
&first_prefix.as_str().replace('-', "_")
};
write!(f, "{first_prefix}::")?;
for prefix in rest_prefixes {
write!(f, "{}::", prefix.as_str())?;
}
}
write!(f, "{}", engines.help_out(&self.suffix))
// for prefix in self.prefixes.iter() {
// write!(f, "{}::", prefix.as_str())?;
// }
// write!(f, "{}", engines.help_out(&self.suffix))
}
}
impl<T: DisplayWithEngines> DebugWithEngines for CallPath<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
for prefix in self.prefixes.iter() {
write!(f, "{}::", prefix.as_str())?;
}
write!(f, "{}", engines.help_out(&self.suffix))
}
}
impl<T: Spanned> Spanned for CallPath<T> {
fn span(&self) -> Span {
if self.prefixes.is_empty() {
self.suffix.span()
} else {
let suffix_span = self.suffix.span();
let mut prefixes_spans = self
.prefixes
.iter()
.map(|x| x.span())
// Depending on how the call path is constructed, we
// might have a situation that the parts do not belong
// to the same source and do not have the same source id.
// In that case, we will take only the suffix' span, as
// the span for the whole call path. Otherwise, we join
// the spans of all the parts.
.filter(|x| {
Arc::ptr_eq(&x.src().text, &suffix_span.src().text)
&& x.source_id() == suffix_span.source_id()
})
.peekable();
if prefixes_spans.peek().is_some() {
Span::join(Span::join_all(prefixes_spans), &suffix_span)
} else {
suffix_span
}
}
}
}
/// This controls the type of display type for call path display string conversions.
pub enum CallPathDisplayType {
/// Prints the regular call path as exists internally.
Regular,
/// Strips the current root package if it exists as prefix.
StripPackagePrefix,
}
impl CallPath {
pub fn fullpath(path: &[&str]) -> Self {
assert!(!path.is_empty());
CallPath {
prefixes: path
.iter()
.take(path.len() - 1)
.map(|&x| Ident::new_no_span(x.into()))
.collect(),
suffix: path.last().map(|&x| Ident::new_no_span(x.into())).unwrap(),
callpath_type: CallPathType::Full,
}
}
/// Shifts the last prefix into the suffix, and removes the old suffix.
/// Does nothing if prefixes are empty, or if the path is a full path and there is only a single prefix (which must be the package name, which is obligatory for full paths)
pub fn rshift(&self) -> CallPath {
if self.prefixes.is_empty()
|| (matches!(self.callpath_type, CallPathType::Full) && self.prefixes.len() == 1)
{
self.clone()
} else {
CallPath {
prefixes: self.prefixes[0..self.prefixes.len() - 1].to_vec(),
suffix: self.prefixes.last().unwrap().clone(),
callpath_type: self.callpath_type,
}
}
}
/// Removes the first prefix. Does nothing if prefixes are empty.
pub fn lshift(&self) -> CallPath {
if self.prefixes.is_empty() {
self.clone()
} else {
let new_callpath_type = match self.callpath_type {
CallPathType::RelativeToPackageRoot | CallPathType::Ambiguous => {
CallPathType::Ambiguous
}
CallPathType::Full => CallPathType::RelativeToPackageRoot,
};
CallPath {
prefixes: self.prefixes[1..self.prefixes.len()].to_vec(),
suffix: self.suffix.clone(),
callpath_type: new_callpath_type,
}
}
}
pub fn as_vec_string(&self) -> Vec<String> {
self.prefixes
.iter()
.map(|p| p.to_string())
.chain(std::iter::once(self.suffix.to_string()))
.collect::<Vec<_>>()
}
pub fn as_vec_ident(&self) -> Vec<Ident> {
self.as_vec_string()
.iter()
.map(|s| Ident::new_no_span(s.clone()))
.collect::<Vec<_>>()
}
/// Create a full [CallPath] from a given [Ident] and the [Namespace] in which the [Ident] is
/// declared.
///
/// This function is intended to be used while typechecking the identifier declaration, i.e.,
/// before the identifier is added to the environment.
pub fn ident_to_fullpath(suffix: Ident, namespace: &Namespace) -> CallPath {
let mut res: Self = suffix.clone().into();
for mod_path in namespace.current_mod_path() {
res.prefixes.push(mod_path.clone())
}
res.callpath_type = CallPathType::Full;
res
}
/// Convert a given [CallPath] into a call path suitable for a `use` statement.
///
/// For example, given a path `pkga::SOME_CONST` where `pkga` is an _internal_ library of a package named
/// `my_project`, the corresponding call path is `pkga::SOME_CONST`.
///
/// Paths to _external_ libraries such `std::lib1::lib2::my_obj` are left unchanged.
pub fn to_import_path(&self, engines: &Engines, namespace: &Namespace) -> CallPath {
let converted = self.to_fullpath(engines, namespace);
if let Some(first) = converted.prefixes.first() {
if namespace.current_package_name() == first {
return converted.lshift();
}
}
converted
}
pub fn to_display_path(
&self,
display_type: CallPathDisplayType,
namespace: &Namespace,
) -> CallPath {
let mut display_path = self.clone();
match display_type {
CallPathDisplayType::Regular => {}
CallPathDisplayType::StripPackagePrefix => {
if let Some(first) = self.prefixes.first() {
if namespace.current_package_name() == first {
display_path = display_path.lshift();
}
}
}
};
display_path
}
/// Create a string form of the given [CallPath] and zero or more [TypeArgument]s.
/// The returned string is convenient for displaying full names, including generic arguments, in help messages.
/// E.g.:
/// - `some::module::SomeType`
/// - `some::module::SomeGenericType<T, u64>`
///
/// Note that the trailing arguments are never separated by `::` from the suffix.
pub(crate) fn to_string_with_args(
&self,
engines: &Engines,
args: &[GenericArgument],
) -> String {
let args = args
.iter()
.map(|type_arg| engines.help_out(type_arg).to_string())
.collect::<Vec<_>>()
.join(", ");
format!(
"{}{}",
// TODO: Replace with a context aware string representation of the path
// once https://github.com/FuelLabs/sway/issues/6873 is fixed.
&self,
if args.is_empty() {
String::new()
} else {
format!("<{args}>")
}
)
}
}
impl<T: Clone> CallPath<T> {
/// Convert a given [CallPath] to a symbol to a full [CallPath] to a program point in which the
/// symbol can be resolved (assuming the given [CallPath] is a legal Sway path).
///
/// The resulting [CallPath] is not guaranteed to be located in the package where the symbol is
/// declared. To obtain the path to the declaration, use [to_canonical_path].
///
/// The [CallPath] is converted within the current module of the supplied namespace.
///
/// For example, given a path `pkga::SOME_CONST` where `pkga` is an _internal_ module of a
/// package named `my_project`, the corresponding call path is
/// `my_project::pkga::SOME_CONST`. This does not imply that `SOME_CONST` is declared in the
/// `my_project::pkga`, but only that the name `SOME_CONST` is bound in `my_project::pkga`.
///
/// Paths to _external_ libraries such `std::lib1::lib2::my_obj` are considered full already
/// and are left unchanged since `std` is a root of the package `std`.
pub fn to_fullpath(&self, engines: &Engines, namespace: &Namespace) -> CallPath<T> {
self.to_fullpath_from_mod_path(engines, namespace, namespace.current_mod_path())
}
/// Convert a given [CallPath] to a symbol to a full [CallPath] to a program point in which the
/// symbol can be resolved (assuming the given [CallPath] is a legal Sway path).
///
/// The resulting [CallPath] is not guaranteed to be located in the package where the symbol is
/// declared. To obtain the path to the declaration, use [to_canonical_path].
///
/// The [CallPath] is converted within the module given by `mod_path`, which must be a legal
/// path to a module.
///
/// For example, given a path `pkga::SOME_CONST` where `pkga` is an _internal_ module of a
/// package named `my_project`, the corresponding call path is
/// `my_project::pkga::SOME_CONST`. This does not imply that `SOME_CONST` is declared in the
/// `my_project::pkga`, but only that the name `SOME_CONST` is bound in `my_project::pkga`.
///
/// Paths to _external_ libraries such `std::lib1::lib2::my_obj` are considered full already
/// and are left unchanged since `std` is a root of the package `std`.
pub fn to_fullpath_from_mod_path(
&self,
engines: &Engines,
namespace: &Namespace,
mod_path: &Vec<Ident>,
) -> CallPath<T> {
let mod_path_module = namespace.module_from_absolute_path(mod_path);
match self.callpath_type {
CallPathType::Full => self.clone(),
CallPathType::RelativeToPackageRoot => {
let mut prefixes = vec![mod_path[0].clone()];
for ident in self.prefixes.iter() {
prefixes.push(ident.clone());
}
Self {
prefixes,
suffix: self.suffix.clone(),
callpath_type: CallPathType::Full,
}
}
CallPathType::Ambiguous => {
if self.prefixes.is_empty() {
// Given a path to a symbol that has no prefixes, discover the path to the symbol as a
// combination of the package name in which the symbol is defined and the path to the
// current submodule.
CallPath {
prefixes: mod_path.clone(),
suffix: self.suffix.clone(),
callpath_type: CallPathType::Full,
}
} else if mod_path_module.is_some()
&& (mod_path_module.unwrap().has_submodule(&self.prefixes[0])
|| namespace.module_has_binding(engines, mod_path, &self.prefixes[0]))
{
// The first identifier in the prefix is a submodule of the current
// module.
//
// The path is a qualified path relative to the current module
//
// Complete the path by prepending the package name and the path to the current module.
CallPath {
prefixes: mod_path.iter().chain(&self.prefixes).cloned().collect(),
suffix: self.suffix.clone(),
callpath_type: CallPathType::Full,
}
} else if namespace.package_exists(&self.prefixes[0])
&& namespace.module_is_external(&self.prefixes)
{
// The first identifier refers to an external package. The path is already fully qualified.
CallPath {
prefixes: self.prefixes.clone(),
suffix: self.suffix.clone(),
callpath_type: CallPathType::Full,
}
} else {
// The first identifier in the prefix is neither a submodule of the current module nor the name of an external package.
// This is probably an illegal path, so let it fail by assuming it is bound in the current module.
CallPath {
prefixes: mod_path.iter().chain(&self.prefixes).cloned().collect(),
suffix: self.suffix.clone(),
callpath_type: CallPathType::Full,
}
}
}
}
}
}
impl CallPath {
/// Convert a given [CallPath] to a symbol to a full [CallPath] to where the symbol is declared
/// (assuming the given [CallPath] is a legal Sway path).
///
/// The [CallPath] is converted within the current module of the supplied namespace.
///
/// For example, given a path `pkga::SOME_CONST` where `pkga` is an _internal_ module of a
/// package named `my_project`, and `SOME_CONST` is bound in the module `my_project::pkga`, then
/// the corresponding call path is the full callpath to the declaration that `SOME_CONST` is
/// bound to. This does not imply that `SOME_CONST` is declared in the `my_project::pkga`, since
/// the binding may be the result of an import.
///
/// Paths to _external_ libraries such `std::lib1::lib2::my_obj` are considered full already
/// and are left unchanged since `std` is a root of the package `std`.
pub fn to_canonical_path(&self, engines: &Engines, namespace: &Namespace) -> CallPath {
// Generate a full path to a module where the suffix can be resolved
let full_path = self.to_fullpath(engines, namespace);
match namespace.module_from_absolute_path(&full_path.prefixes) {
Some(module) => {
// Resolve the path suffix in the found module
match module.resolve_symbol(&Handler::default(), engines, &full_path.suffix) {
Ok((decl, decl_path)) => {
let name = decl.expect_typed().get_name(engines);
let suffix = if name.as_str() != full_path.suffix.as_str() {
name
} else {
full_path.suffix
};
// Replace the resolvable path with the declaration's path
CallPath {
prefixes: decl_path,
suffix,
callpath_type: full_path.callpath_type,
}
}
Err(_) => {
// The symbol does not resolve. The symbol isn't bound, so the best bet is
// the full path.
full_path
}
}
}
None => {
// The resolvable module doesn't exist. The symbol probably doesn't exist, so
// the best bet is the full path.
full_path
}
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/programs.rs | sway-core/src/language/programs.rs | use std::sync::Arc;
use super::{lexed::LexedProgram, parsed::ParseProgram, ty::TyProgram};
use crate::semantic_analysis::program::TypeCheckFailed;
use sway_utils::PerformanceData;
/// Contains the lexed, parsed, typed compilation stages of a program, as well
/// as compilation metrics.
#[derive(Clone, Debug)]
pub struct Programs {
pub lexed: Arc<LexedProgram>,
pub parsed: Arc<ParseProgram>,
pub typed: Result<Arc<TyProgram>, TypeCheckFailed>,
pub metrics: PerformanceData,
}
impl Programs {
pub fn new(
lexed: Arc<LexedProgram>,
parsed: Arc<ParseProgram>,
typed: Result<Arc<TyProgram>, TypeCheckFailed>,
metrics: PerformanceData,
) -> Programs {
Programs {
lexed,
parsed,
typed,
metrics,
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/purity.rs | sway-core/src/language/purity.rs | use serde::{Deserialize, Serialize};
use sway_ast::attribute::{STORAGE_READ_ARG_NAME, STORAGE_WRITE_ARG_NAME};
/// The purity of a function is related to its access of contract storage. If a function accesses
/// or could potentially access contract storage, it is [Purity::Impure]. If a function does not utilize any
/// any accesses (reads _or_ writes) of storage, then it is [Purity::Pure].
#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub enum Purity {
#[default]
Pure,
Reads,
Writes,
ReadsWrites,
}
impl Purity {
pub fn can_call(&self, other: Purity) -> bool {
match self {
Purity::Pure => other == Purity::Pure,
Purity::Reads => other == Purity::Pure || other == Purity::Reads,
Purity::Writes => true, // storage(write) allows reading as well
Purity::ReadsWrites => true,
}
}
// Useful for error messages, show the syntax needed in the #[storage(...)] attribute.
pub fn to_attribute_syntax(&self) -> String {
match self {
Purity::Pure => "".to_owned(),
Purity::Reads => STORAGE_READ_ARG_NAME.to_owned(),
Purity::Writes => STORAGE_WRITE_ARG_NAME.to_owned(),
Purity::ReadsWrites => {
format!("{STORAGE_READ_ARG_NAME}, {STORAGE_WRITE_ARG_NAME}")
}
}
}
}
/// Utility to find the union of purities. To 'promote' Reads to Writes we want ReadsWrites, and
/// the same for Writes to Reads.
pub fn promote_purity(from: Purity, to: Purity) -> Purity {
match (from, to) {
(Purity::Reads, Purity::Writes)
| (Purity::Writes, Purity::Reads)
| (Purity::ReadsWrites, _) => Purity::ReadsWrites,
_otherwise => to,
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration.rs | sway-core/src/language/parsed/declaration.rs | mod abi;
mod configurable;
mod const_generic;
mod constant;
mod r#enum;
pub mod function;
mod impl_trait;
mod storage;
mod r#struct;
mod r#trait;
mod type_alias;
mod variable;
use std::fmt;
pub use abi::*;
pub use configurable::*;
pub use const_generic::*;
pub use constant::*;
pub use function::*;
pub use impl_trait::*;
pub use r#enum::*;
pub use r#struct::*;
pub use r#trait::*;
pub use storage::*;
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::{Ident, Span, Spanned};
pub use type_alias::*;
pub use variable::*;
use crate::{
decl_engine::{
parsed_engine::{ParsedDeclEngine, ParsedDeclEngineGet},
parsed_id::ParsedDeclId,
DeclEngineGetParsedDeclId,
},
engine_threading::{
DebugWithEngines, DisplayWithEngines, EqWithEngines, PartialEqWithEngines,
PartialEqWithEnginesContext,
},
language::Visibility,
Engines,
};
#[derive(Debug, Clone)]
pub enum Declaration {
VariableDeclaration(ParsedDeclId<VariableDeclaration>),
FunctionDeclaration(ParsedDeclId<FunctionDeclaration>),
TraitDeclaration(ParsedDeclId<TraitDeclaration>),
StructDeclaration(ParsedDeclId<StructDeclaration>),
EnumDeclaration(ParsedDeclId<EnumDeclaration>),
EnumVariantDeclaration(EnumVariantDeclaration),
ImplSelfOrTrait(ParsedDeclId<ImplSelfOrTrait>),
AbiDeclaration(ParsedDeclId<AbiDeclaration>),
ConstantDeclaration(ParsedDeclId<ConstantDeclaration>),
ConfigurableDeclaration(ParsedDeclId<ConfigurableDeclaration>),
StorageDeclaration(ParsedDeclId<StorageDeclaration>),
TypeAliasDeclaration(ParsedDeclId<TypeAliasDeclaration>),
TraitTypeDeclaration(ParsedDeclId<TraitTypeDeclaration>),
TraitFnDeclaration(ParsedDeclId<TraitFn>),
ConstGenericDeclaration(ParsedDeclId<ConstGenericDeclaration>),
}
#[derive(Debug, Clone)]
pub struct EnumVariantDeclaration {
pub enum_ref: ParsedDeclId<EnumDeclaration>,
pub variant_name: Ident,
pub variant_decl_span: Span,
}
impl Declaration {
/// Checks if this `Declaration` is a test.
pub(crate) fn is_test(&self, engines: &Engines) -> bool {
if let Declaration::FunctionDeclaration(fn_decl) = self {
let fn_decl = engines.pe().get_function(fn_decl);
fn_decl.is_test()
} else {
false
}
}
/// Friendly type name string used for error reporting,
/// which consists of the type name of the declaration AST node.
pub fn friendly_type_name(&self) -> &'static str {
use Declaration::*;
match self {
VariableDeclaration(_) => "variable",
ConstantDeclaration(_) => "constant",
ConfigurableDeclaration(_) => "configurable",
TraitTypeDeclaration(_) => "type",
FunctionDeclaration(_) => "function",
TraitDeclaration(_) => "trait",
TraitFnDeclaration(_) => "trait fn",
StructDeclaration(_) => "struct",
EnumDeclaration(_) => "enum",
EnumVariantDeclaration(_) => "enum variant",
ImplSelfOrTrait(_) => "impl self/trait",
AbiDeclaration(_) => "abi",
StorageDeclaration(_) => "contract storage",
TypeAliasDeclaration(_) => "type alias",
ConstGenericDeclaration(_) => "const generic",
}
}
pub fn span(&self, engines: &Engines) -> sway_types::Span {
use Declaration::*;
let pe = engines.pe();
match self {
VariableDeclaration(decl_id) => pe.get_variable(decl_id).span(),
FunctionDeclaration(decl_id) => pe.get_function(decl_id).span(),
TraitDeclaration(decl_id) => pe.get_trait(decl_id).span(),
StructDeclaration(decl_id) => pe.get_struct(decl_id).span(),
EnumDeclaration(decl_id) => pe.get_enum(decl_id).span(),
EnumVariantDeclaration(decl) => decl.variant_decl_span.clone(),
ImplSelfOrTrait(decl_id) => pe.get_impl_self_or_trait(decl_id).span(),
AbiDeclaration(decl_id) => pe.get_abi(decl_id).span(),
ConstantDeclaration(decl_id) => pe.get_constant(decl_id).span(),
ConfigurableDeclaration(decl_id) => pe.get_configurable(decl_id).span(),
StorageDeclaration(decl_id) => pe.get_storage(decl_id).span(),
TypeAliasDeclaration(decl_id) => pe.get_type_alias(decl_id).span(),
TraitTypeDeclaration(decl_id) => pe.get_trait_type(decl_id).span(),
TraitFnDeclaration(decl_id) => pe.get_trait_fn(decl_id).span(),
ConstGenericDeclaration(decl_id) => pe.get_const_generic(decl_id).span(),
}
}
pub(crate) fn to_fn_ref(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<ParsedDeclId<FunctionDeclaration>, ErrorEmitted> {
match self {
Declaration::FunctionDeclaration(decl_id) => Ok(*decl_id),
decl => Err(handler.emit_err(CompileError::DeclIsNotAFunction {
actually: decl.friendly_type_name().to_string(),
span: decl.span(engines),
})),
}
}
pub(crate) fn to_struct_decl(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<ParsedDeclId<StructDeclaration>, ErrorEmitted> {
match self {
Declaration::StructDeclaration(decl_id) => Ok(*decl_id),
Declaration::TypeAliasDeclaration(decl_id) => {
let alias = engines.pe().get_type_alias(decl_id);
let struct_decl_id = engines.te().get(alias.ty.type_id).expect_struct(
handler,
engines,
&self.span(engines),
)?;
let parsed_decl_id = engines.de().get_parsed_decl_id(&struct_decl_id);
parsed_decl_id.ok_or_else(|| {
handler.emit_err(CompileError::InternalOwned(
"Cannot get parsed decl id from decl id".to_string(),
self.span(engines),
))
})
}
decl => Err(handler.emit_err(CompileError::DeclIsNotAStruct {
actually: decl.friendly_type_name().to_string(),
span: decl.span(engines),
})),
}
}
pub(crate) fn to_enum_decl(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<ParsedDeclId<EnumDeclaration>, ErrorEmitted> {
match self {
Declaration::EnumDeclaration(decl_id) => Ok(*decl_id),
Declaration::TypeAliasDeclaration(decl_id) => {
let alias = engines.pe().get_type_alias(decl_id);
let enum_decl_id = engines.te().get(alias.ty.type_id).expect_enum(
handler,
engines,
String::default(),
&self.span(engines),
)?;
let parsed_decl_id = engines.de().get_parsed_decl_id(&enum_decl_id);
parsed_decl_id.ok_or_else(|| {
handler.emit_err(CompileError::InternalOwned(
"Cannot get parsed decl id from decl id".to_string(),
self.span(engines),
))
})
}
decl => Err(handler.emit_err(CompileError::DeclIsNotAnEnum {
actually: decl.friendly_type_name().to_string(),
span: decl.span(engines),
})),
}
}
#[allow(unused)]
pub(crate) fn visibility(&self, decl_engine: &ParsedDeclEngine) -> Visibility {
match self {
Declaration::TraitDeclaration(decl_id) => decl_engine.get_trait(decl_id).visibility,
Declaration::ConstantDeclaration(decl_id) => {
decl_engine.get_constant(decl_id).visibility
}
Declaration::ConfigurableDeclaration(decl_id) => {
decl_engine.get_configurable(decl_id).visibility
}
Declaration::StructDeclaration(decl_id) => decl_engine.get_struct(decl_id).visibility,
Declaration::EnumDeclaration(decl_id) => decl_engine.get_enum(decl_id).visibility,
Declaration::EnumVariantDeclaration(decl) => {
decl_engine.get_enum(&decl.enum_ref).visibility
}
Declaration::FunctionDeclaration(decl_id) => {
decl_engine.get_function(decl_id).visibility
}
Declaration::TypeAliasDeclaration(decl_id) => {
decl_engine.get_type_alias(decl_id).visibility
}
Declaration::VariableDeclaration(_decl_id) => Visibility::Private,
Declaration::ImplSelfOrTrait(_)
| Declaration::StorageDeclaration(_)
| Declaration::AbiDeclaration(_)
| Declaration::TraitTypeDeclaration(_)
| Declaration::TraitFnDeclaration(_) => Visibility::Public,
Declaration::ConstGenericDeclaration(_) => {
unreachable!("Const generics do not have visibility")
}
}
}
}
impl DisplayWithEngines for Declaration {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> std::fmt::Result {
write!(
f,
"{} parsed declaration ({})",
self.friendly_type_name(),
match self {
Declaration::VariableDeclaration(decl_id) => {
engines.pe().get(decl_id).name.as_str().into()
}
Declaration::FunctionDeclaration(decl_id) => {
engines.pe().get(decl_id).name.as_str().into()
}
Declaration::TraitDeclaration(decl_id) => {
engines.pe().get(decl_id).name.as_str().into()
}
Declaration::StructDeclaration(decl_id) => {
engines.pe().get(decl_id).name.as_str().into()
}
Declaration::EnumDeclaration(decl_id) => {
engines.pe().get(decl_id).name.as_str().into()
}
Declaration::ImplSelfOrTrait(decl_id) => {
engines
.pe()
.get(decl_id)
.trait_name
.as_vec_string()
.join("::")
.as_str()
.into()
}
Declaration::TypeAliasDeclaration(decl_id) =>
engines.pe().get(decl_id).name.as_str().into(),
_ => String::new(),
}
)
}
}
impl DebugWithEngines for Declaration {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> std::fmt::Result {
DisplayWithEngines::fmt(&self, f, engines)
}
}
impl EqWithEngines for Declaration {}
impl PartialEqWithEngines for Declaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let decl_engine = ctx.engines().pe();
match (self, other) {
(Declaration::VariableDeclaration(lid), Declaration::VariableDeclaration(rid)) => {
decl_engine.get(lid).eq(&decl_engine.get(rid), ctx)
}
(Declaration::FunctionDeclaration(lid), Declaration::FunctionDeclaration(rid)) => {
decl_engine.get(lid).eq(&decl_engine.get(rid), ctx)
}
(Declaration::TraitDeclaration(lid), Declaration::TraitDeclaration(rid)) => {
decl_engine.get(lid).eq(&decl_engine.get(rid), ctx)
}
(Declaration::StructDeclaration(lid), Declaration::StructDeclaration(rid)) => {
decl_engine.get(lid).eq(&decl_engine.get(rid), ctx)
}
(Declaration::EnumDeclaration(lid), Declaration::EnumDeclaration(rid)) => {
decl_engine.get(lid).eq(&decl_engine.get(rid), ctx)
}
(Declaration::ImplSelfOrTrait(lid), Declaration::ImplSelfOrTrait(rid)) => {
decl_engine.get(lid).eq(&decl_engine.get(rid), ctx)
}
(Declaration::AbiDeclaration(lid), Declaration::AbiDeclaration(rid)) => {
decl_engine.get(lid).eq(&decl_engine.get(rid), ctx)
}
(Declaration::ConstantDeclaration(lid), Declaration::ConstantDeclaration(rid)) => {
decl_engine.get(lid).eq(&decl_engine.get(rid), ctx)
}
(Declaration::StorageDeclaration(lid), Declaration::StorageDeclaration(rid)) => {
decl_engine.get(lid).eq(&decl_engine.get(rid), ctx)
}
(Declaration::TypeAliasDeclaration(lid), Declaration::TypeAliasDeclaration(rid)) => {
decl_engine.get(lid).eq(&decl_engine.get(rid), ctx)
}
(Declaration::TraitTypeDeclaration(lid), Declaration::TraitTypeDeclaration(rid)) => {
decl_engine.get(lid).eq(&decl_engine.get(rid), ctx)
}
_ => false,
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/program.rs | sway-core/src/language/parsed/program.rs | use strum::EnumString;
use crate::Engines;
use super::ParseModule;
/// A parsed, but not yet type-checked, Sway program.
///
/// Includes all modules in the form of a `ParseModule` tree accessed via the `root`.
#[derive(Debug, Clone)]
pub struct ParseProgram {
pub kind: TreeType,
pub root: ParseModule,
}
/// A Sway program can be either a contract, script, predicate, or a library.
///
/// A submodule declared with `mod` can be only a [TreeType::Library].
#[derive(Copy, Clone, Debug, PartialEq, Eq, EnumString)]
pub enum TreeType {
#[strum(serialize = "predicate")]
Predicate,
#[strum(serialize = "script")]
Script,
#[strum(serialize = "contract")]
Contract,
#[strum(serialize = "library")]
Library,
}
impl TreeType {
pub const CFG: &'static [&'static str] = &["contract", "library", "predicate", "script"];
}
impl std::fmt::Display for TreeType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::Predicate => "predicate",
Self::Script => "script",
Self::Contract => "contract",
Self::Library => "library",
}
)
}
}
impl ParseProgram {
/// Excludes all test functions from the parse tree.
pub(crate) fn exclude_tests(&mut self, engines: &Engines) {
self.root.tree.exclude_tests(engines)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/module.rs | sway-core/src/language/parsed/module.rs | use crate::{
language::{HasModule, HasSubmodules, ModName, Visibility},
transform,
};
use super::ParseTree;
use sway_types::Span;
pub type ModuleHash = u64;
pub type ModuleEvaluationOrder = Vec<ModName>;
/// A module and its submodules in the form of a tree.
#[derive(Debug, Clone)]
pub struct ParseModule {
/// The content of this module in the form of a `ParseTree`.
pub tree: ParseTree,
/// Submodules introduced within this module using the `dep` syntax in order of declaration.
pub submodules: Vec<(ModName, ParseSubmodule)>,
pub attributes: transform::Attributes,
/// The span of the module kind.
pub module_kind_span: Span,
/// Evaluation order for the submodules
pub module_eval_order: ModuleEvaluationOrder,
/// an empty span at the beginning of the file containing the module
pub span: Span,
/// an hash used for caching the module
pub hash: ModuleHash,
}
/// A library module that was declared as a `mod` of another module.
///
/// Only submodules are guaranteed to be a `library`.
#[derive(Debug, Clone)]
pub struct ParseSubmodule {
pub module: ParseModule,
pub mod_name_span: Span,
pub visibility: Visibility,
}
impl HasModule<ParseModule> for ParseSubmodule {
fn module(&self) -> &ParseModule {
&self.module
}
}
impl HasSubmodules<ParseSubmodule> for ParseModule {
fn submodules(&self) -> &[(ModName, ParseSubmodule)] {
&self.submodules
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/mod.rs | sway-core/src/language/parsed/mod.rs | //! Contains all the code related to parsing Sway source code.
mod code_block;
pub mod declaration;
mod expression;
mod include_statement;
mod module;
mod program;
mod use_statement;
pub use code_block::*;
pub use declaration::*;
pub use expression::*;
pub use include_statement::IncludeStatement;
pub use module::{ModuleEvaluationOrder, ParseModule, ParseSubmodule};
pub use program::{ParseProgram, TreeType};
use sway_error::handler::ErrorEmitted;
use sway_types::span::Span;
pub use use_statement::{ImportType, UseStatement};
use crate::{
engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
Engines,
};
/// Represents some exportable information that results from compiling some
/// Sway source code.
#[derive(Debug, Clone)]
pub struct ParseTree {
/// The untyped AST nodes that constitute this tree's root nodes.
pub root_nodes: Vec<AstNode>,
/// The [Span] of the entire tree.
pub span: Span,
}
/// A single [AstNode] represents a node in the parse tree. Note that [AstNode]
/// is a recursive type and can contain other [AstNode], thus populating the tree.
#[derive(Debug, Clone)]
pub struct AstNode {
/// The content of this ast node, which could be any control flow structure or other
/// basic organizational component.
pub content: AstNodeContent,
/// The [Span] representing this entire [AstNode].
pub span: Span,
}
impl EqWithEngines for AstNode {}
impl PartialEqWithEngines for AstNode {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.content.eq(&other.content, ctx)
}
}
/// Represents the various structures that constitute a Sway program.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum AstNodeContent {
/// A statement of the form `use foo::bar;` or `use ::foo::bar;`
UseStatement(UseStatement),
/// Any type of declaration, of which there are quite a few. See [Declaration] for more details
/// on the possible variants.
Declaration(Declaration),
/// Any type of expression, of which there are quite a few. See [Expression] for more details.
Expression(Expression),
/// A statement of the form `mod foo::bar;` which imports/includes another source file.
IncludeStatement(IncludeStatement),
/// A malformed statement.
///
/// Used for parser recovery when we cannot form a more specific node.
/// The list of `Span`s are for consumption by the LSP and are,
/// when joined, the same as that stored in `statement.span`.
Error(Box<[Span]>, ErrorEmitted),
}
impl EqWithEngines for AstNodeContent {}
impl PartialEqWithEngines for AstNodeContent {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(AstNodeContent::UseStatement(lhs), AstNodeContent::UseStatement(rhs)) => lhs.eq(rhs),
(AstNodeContent::Declaration(lhs), AstNodeContent::Declaration(rhs)) => {
lhs.eq(rhs, ctx)
}
(AstNodeContent::Expression(lhs), AstNodeContent::Expression(rhs)) => lhs.eq(rhs, ctx),
(AstNodeContent::IncludeStatement(lhs), AstNodeContent::IncludeStatement(rhs)) => {
lhs.eq(rhs)
}
(AstNodeContent::Error(lhs, ..), AstNodeContent::Error(rhs, ..)) => lhs.eq(rhs),
_ => false,
}
}
}
impl ParseTree {
/// Excludes all test functions from the parse tree.
pub(crate) fn exclude_tests(&mut self, engines: &Engines) {
self.root_nodes.retain(|node| !node.is_test(engines));
}
}
impl AstNode {
/// Checks if this `AstNode` is a test.
pub(crate) fn is_test(&self, engines: &Engines) -> bool {
if let AstNodeContent::Declaration(decl) = &self.content {
decl.is_test(engines)
} else {
false
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/include_statement.rs | sway-core/src/language/parsed/include_statement.rs | use sway_types::{span::Span, Ident};
use crate::language::Visibility;
#[derive(Clone, Debug, PartialEq)]
pub struct IncludeStatement {
// this span may be used for errors in the future, although it is not right now.
pub span: Span,
pub mod_name: Ident,
pub visibility: Visibility,
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/use_statement.rs | sway-core/src/language/parsed/use_statement.rs | use crate::{language::Visibility, parsed::Span};
use serde::{Deserialize, Serialize};
use sway_types::ident::Ident;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ImportType {
Star,
SelfImport(Span),
Item(Ident),
}
/// A [UseStatement] is a statement that imports something from a module into the local namespace.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UseStatement {
pub call_path: Vec<Ident>,
pub span: Span,
pub import_type: ImportType,
// If `is_relative_to_package_root` is true, then this use statement is a path relative to the
// project root. For example, if the path is `::X::Y` and occurs in package `P`, then the path
// refers to the full path `P::X::Y`.
// If `is_relative_to_package_root` is false, then there are two options:
// - The path refers to a path relative to the current namespace. For example, if the path is
// `X::Y` and it occurs in a module whose path is `P::M`, then the path refers to the full
// path `P::M::X::Y`.
// - The path refers to a path in an external package. For example, the path `X::Y` refers to an
// entity `Y` in the external package `X`.
pub is_relative_to_package_root: bool,
// If `reexport` is Visibility::Public, then this use statement reexports its imported binding.
// If not, then the import binding is private to the importing module.
pub reexport: Visibility,
pub alias: Option<Ident>,
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/code_block.rs | sway-core/src/language/parsed/code_block.rs | use crate::{
engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
language::parsed::AstNode,
};
use sway_types::{span::Span, Spanned};
#[derive(Debug, Clone)]
pub struct CodeBlock {
pub contents: Vec<AstNode>,
pub(crate) whole_block_span: Span,
}
impl EqWithEngines for CodeBlock {}
impl PartialEqWithEngines for CodeBlock {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.contents.eq(&other.contents, ctx)
}
}
impl Spanned for CodeBlock {
fn span(&self) -> Span {
self.whole_block_span.clone()
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/struct.rs | sway-core/src/language/parsed/declaration/struct.rs | use crate::{
ast_elements::type_argument::GenericTypeArgument,
engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
language::Visibility,
transform,
type_system::TypeParameter,
};
use sway_types::{ident::Ident, span::Span, Named, Spanned};
#[derive(Debug, Clone)]
pub struct StructDeclaration {
pub name: Ident,
pub attributes: transform::Attributes,
pub fields: Vec<StructField>,
pub type_parameters: Vec<TypeParameter>,
pub visibility: Visibility,
pub(crate) span: Span,
}
impl EqWithEngines for StructDeclaration {}
impl PartialEqWithEngines for StructDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.type_parameters.eq(&other.type_parameters, ctx)
&& self.attributes == other.attributes
&& self.fields.eq(&other.fields, ctx)
&& self.type_parameters.eq(&other.type_parameters, ctx)
&& self.visibility == other.visibility
&& self.span == other.span
}
}
impl Named for StructDeclaration {
fn name(&self) -> &sway_types::BaseIdent {
&self.name
}
}
impl Spanned for StructDeclaration {
fn span(&self) -> sway_types::Span {
self.span.clone()
}
}
#[derive(Debug, Clone)]
pub struct StructField {
pub visibility: Visibility,
pub name: Ident,
pub attributes: transform::Attributes,
pub(crate) span: Span,
pub type_argument: GenericTypeArgument,
}
impl EqWithEngines for StructField {}
impl PartialEqWithEngines for StructField {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.visibility == other.visibility
&& self.name == other.name
&& self.attributes == other.attributes
&& self.span == other.span
&& self.type_argument.eq(&other.type_argument, ctx)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/variable.rs | sway-core/src/language/parsed/declaration/variable.rs | use sway_types::{Named, Spanned};
use crate::{
ast_elements::type_argument::GenericTypeArgument,
engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
language::parsed::Expression,
Ident,
};
#[derive(Debug, Clone)]
pub struct VariableDeclaration {
pub name: Ident,
pub type_ascription: GenericTypeArgument,
pub body: Expression, // will be codeblock variant
pub is_mutable: bool,
}
impl EqWithEngines for VariableDeclaration {}
impl PartialEqWithEngines for VariableDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.type_ascription.eq(&other.type_ascription, ctx)
&& self.body.eq(&other.body, ctx)
&& self.is_mutable == other.is_mutable
}
}
impl Named for VariableDeclaration {
fn name(&self) -> &sway_types::BaseIdent {
&self.name
}
}
impl Spanned for VariableDeclaration {
fn span(&self) -> sway_types::Span {
self.name.span()
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/trait.rs | sway-core/src/language/parsed/declaration/trait.rs | use super::{ConstantDeclaration, FunctionDeclaration, FunctionParameter};
use crate::{
ast_elements::type_argument::GenericTypeArgument,
decl_engine::{parsed_id::ParsedDeclId, DeclRefTrait},
engine_threading::*,
language::*,
transform,
type_system::*,
};
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use sway_error::handler::ErrorEmitted;
use sway_types::{ident::Ident, span::Span, Named, Spanned};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TraitItem {
TraitFn(ParsedDeclId<TraitFn>),
Constant(ParsedDeclId<ConstantDeclaration>),
Type(ParsedDeclId<TraitTypeDeclaration>),
// to handle parser recovery: Error represents an incomplete trait item
Error(Box<[Span]>, #[serde(skip)] ErrorEmitted),
}
impl EqWithEngines for TraitItem {}
impl PartialEqWithEngines for TraitItem {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(TraitItem::TraitFn(lhs), TraitItem::TraitFn(rhs)) => {
PartialEqWithEngines::eq(lhs, rhs, ctx)
}
(TraitItem::Constant(lhs), TraitItem::Constant(rhs)) => {
PartialEqWithEngines::eq(lhs, rhs, ctx)
}
(TraitItem::Type(lhs), TraitItem::Type(rhs)) => PartialEqWithEngines::eq(lhs, rhs, ctx),
(TraitItem::Error(lhs, _), TraitItem::Error(rhs, _)) => lhs.eq(rhs),
_ => false,
}
}
}
#[derive(Debug, Clone)]
pub struct TraitDeclaration {
pub name: Ident,
pub(crate) type_parameters: Vec<TypeParameter>,
pub attributes: transform::Attributes,
pub interface_surface: Vec<TraitItem>,
pub methods: Vec<ParsedDeclId<FunctionDeclaration>>,
pub supertraits: Vec<Supertrait>,
pub visibility: Visibility,
pub span: Span,
}
impl EqWithEngines for TraitDeclaration {}
impl PartialEqWithEngines for TraitDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name.eq(&other.name)
&& self.type_parameters.eq(&other.type_parameters, ctx)
&& self.attributes.eq(&other.attributes)
&& self.interface_surface.eq(&other.interface_surface, ctx)
&& PartialEqWithEngines::eq(&self.methods, &other.methods, ctx)
&& self.supertraits.eq(&other.supertraits, ctx)
&& self.visibility.eq(&other.visibility)
}
}
impl Named for TraitDeclaration {
fn name(&self) -> &sway_types::BaseIdent {
&self.name
}
}
impl Spanned for TraitDeclaration {
fn span(&self) -> sway_types::Span {
self.span.clone()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Supertrait {
pub name: CallPath,
pub decl_ref: Option<DeclRefTrait>,
}
impl Spanned for Supertrait {
fn span(&self) -> Span {
self.name.span()
}
}
impl EqWithEngines for Supertrait {}
impl PartialEqWithEngines for Supertrait {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let Supertrait {
name: ln,
decl_ref: ldr,
} = self;
let Supertrait {
name: rn,
decl_ref: rdr,
} = other;
ln == rn && ldr.eq(rdr, ctx)
}
}
impl HashWithEngines for Supertrait {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let Supertrait { name, decl_ref } = self;
name.hash(state);
decl_ref.hash(state, engines);
}
}
#[derive(Debug, Clone)]
pub struct TraitFn {
pub name: Ident,
pub span: Span,
pub attributes: transform::Attributes,
pub purity: Purity,
pub parameters: Vec<FunctionParameter>,
pub return_type: GenericTypeArgument,
}
impl Spanned for TraitFn {
fn span(&self) -> sway_types::Span {
self.span.clone()
}
}
#[derive(Debug, Clone)]
pub struct TraitTypeDeclaration {
pub name: Ident,
pub attributes: transform::Attributes,
pub ty_opt: Option<GenericArgument>,
pub span: Span,
}
impl EqWithEngines for TraitTypeDeclaration {}
impl PartialEqWithEngines for TraitTypeDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.attributes == other.attributes
&& self.ty_opt.eq(&other.ty_opt, ctx)
}
}
impl Named for TraitTypeDeclaration {
fn name(&self) -> &sway_types::BaseIdent {
&self.name
}
}
impl Spanned for TraitTypeDeclaration {
fn span(&self) -> sway_types::Span {
self.span.clone()
}
}
impl DebugWithEngines for TraitTypeDeclaration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>, _engines: &Engines) -> std::fmt::Result {
f.write_fmt(format_args!("{}", self.name))
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/abi.rs | sway-core/src/language/parsed/declaration/abi.rs | use crate::{
decl_engine::parsed_id::ParsedDeclId,
engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
transform,
};
use super::{FunctionDeclaration, Supertrait, TraitItem};
use sway_types::{ident::Ident, span::Span, Named, Spanned};
/// An `abi` declaration, which declares an interface for a contract
/// to implement or for a caller to use to call a contract.
#[derive(Debug, Clone)]
pub struct AbiDeclaration {
/// The name of the abi trait (also known as a "contract trait")
pub name: Ident,
/// The methods a contract is required to implement in order opt in to this interface
pub interface_surface: Vec<TraitItem>,
pub supertraits: Vec<Supertrait>,
/// The methods provided to a contract "for free" upon opting in to this interface
pub methods: Vec<ParsedDeclId<FunctionDeclaration>>,
pub(crate) span: Span,
pub attributes: transform::Attributes,
}
impl EqWithEngines for AbiDeclaration {}
impl PartialEqWithEngines for AbiDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.interface_surface.eq(&other.interface_surface, ctx)
&& self.supertraits.eq(&other.supertraits, ctx)
&& PartialEqWithEngines::eq(&self.methods, &other.methods, ctx)
&& self.span == other.span
&& self.attributes == other.attributes
}
}
impl Named for AbiDeclaration {
fn name(&self) -> &sway_types::BaseIdent {
&self.name
}
}
impl Spanned for AbiDeclaration {
fn span(&self) -> sway_types::Span {
self.span.clone()
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/function.rs | sway-core/src/language/parsed/declaration/function.rs | use crate::{
ast_elements::type_argument::GenericTypeArgument,
engine_threading::*,
language::{parsed::*, *},
transform::{self, AttributeKind},
type_system::*,
};
use sway_types::{ident::Ident, span::Span, Named, Spanned};
#[derive(Debug, Clone)]
pub enum FunctionDeclarationKind {
Default,
Entry,
Main,
Test,
}
#[derive(Debug, Clone)]
pub struct FunctionDeclaration {
pub purity: Purity,
pub attributes: transform::Attributes,
pub name: Ident,
pub visibility: Visibility,
pub body: CodeBlock,
pub parameters: Vec<FunctionParameter>,
pub span: Span,
pub return_type: GenericTypeArgument,
pub type_parameters: Vec<TypeParameter>,
pub where_clause: Vec<(Ident, Vec<TraitConstraint>)>,
pub kind: FunctionDeclarationKind,
pub implementing_type: Option<Declaration>,
}
impl EqWithEngines for FunctionDeclaration {}
impl PartialEqWithEngines for FunctionDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.purity == other.purity
&& self.attributes == other.attributes
&& self.name == other.name
&& self.visibility == other.visibility
&& self.body.eq(&other.body, ctx)
&& self.parameters.eq(&other.parameters, ctx)
&& self.return_type.eq(&other.return_type, ctx)
&& self.type_parameters.eq(&other.type_parameters, ctx)
}
}
impl DebugWithEngines for FunctionDeclaration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>, _engines: &Engines) -> std::fmt::Result {
f.write_fmt(format_args!("{}", self.name))
}
}
impl Named for FunctionDeclaration {
fn name(&self) -> &sway_types::BaseIdent {
&self.name
}
}
impl Spanned for FunctionDeclaration {
fn span(&self) -> sway_types::Span {
self.span.clone()
}
}
#[derive(Debug, Clone)]
pub struct FunctionParameter {
pub name: Ident,
pub is_reference: bool,
pub is_mutable: bool,
pub mutability_span: Span,
pub type_argument: GenericTypeArgument,
}
impl EqWithEngines for FunctionParameter {}
impl PartialEqWithEngines for FunctionParameter {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.is_reference == other.is_reference
&& self.is_mutable == other.is_mutable
&& self.mutability_span == other.mutability_span
&& self.type_argument.eq(&other.type_argument, ctx)
}
}
impl FunctionDeclaration {
/// Checks if this [FunctionDeclaration] is a test.
pub(crate) fn is_test(&self) -> bool {
self.attributes.has_any_of_kind(AttributeKind::Test)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/storage.rs | sway-core/src/language/parsed/declaration/storage.rs | use crate::{
engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
language::parsed::Expression,
transform,
type_system::*,
};
use sway_types::{ident::Ident, span::Span, Spanned};
#[derive(Debug, Clone)]
/// A declaration of contract storage. Only valid within contract contexts.
/// All values in this struct are mutable and persistent among executions of the same contract deployment.
pub struct StorageDeclaration {
pub attributes: transform::Attributes,
pub entries: Vec<StorageEntry>,
pub span: Span,
pub storage_keyword: Ident,
}
impl EqWithEngines for StorageDeclaration {}
impl PartialEqWithEngines for StorageDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.attributes == other.attributes
&& self.entries.eq(&other.entries, ctx)
&& self.span == other.span
&& self.storage_keyword == other.storage_keyword
}
}
impl Spanned for StorageDeclaration {
fn span(&self) -> sway_types::Span {
self.span.clone()
}
}
#[derive(Debug, Clone)]
pub struct StorageNamespace {
pub name: Ident,
pub entries: Vec<Box<StorageEntry>>,
}
impl EqWithEngines for StorageNamespace {}
impl PartialEqWithEngines for StorageNamespace {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name.eq(&other.name) && self.entries.eq(&other.entries, ctx)
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum StorageEntry {
Namespace(StorageNamespace),
Field(StorageField),
}
impl StorageEntry {
pub fn name(&self) -> Ident {
match self {
StorageEntry::Namespace(namespace) => namespace.name.clone(),
StorageEntry::Field(field) => field.name.clone(),
}
}
}
impl EqWithEngines for StorageEntry {}
impl PartialEqWithEngines for StorageEntry {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(StorageEntry::Namespace(n1), StorageEntry::Namespace(n2)) => n1.eq(n2, ctx),
(StorageEntry::Field(f1), StorageEntry::Field(f2)) => f1.eq(f2, ctx),
_ => false,
}
}
}
/// An individual field in a storage declaration.
/// A type annotation _and_ initializer value must be provided. The initializer value must be a
/// constant expression. For now, that basically means just a literal, but as constant folding
/// improves, we can update that.
#[derive(Debug, Clone)]
pub struct StorageField {
pub name: Ident,
pub key_expression: Option<Expression>,
pub attributes: transform::Attributes,
pub type_argument: GenericTypeArgument,
pub span: Span,
pub initializer: Expression,
}
impl EqWithEngines for StorageField {}
impl PartialEqWithEngines for StorageField {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.attributes == other.attributes
&& self.type_argument.eq(&other.type_argument, ctx)
&& self.span == other.span
&& self.initializer.eq(&other.initializer, ctx)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/configurable.rs | sway-core/src/language/parsed/declaration/configurable.rs | use crate::{
engine_threading::DebugWithEngines,
language::{parsed::Expression, Visibility},
transform, Engines, GenericTypeArgument,
};
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Debug, Clone)]
pub struct ConfigurableDeclaration {
pub name: Ident,
pub attributes: transform::Attributes,
pub type_ascription: GenericTypeArgument,
pub value: Option<Expression>,
pub visibility: Visibility,
pub span: Span,
pub block_keyword_span: Span,
}
impl Named for ConfigurableDeclaration {
fn name(&self) -> &sway_types::BaseIdent {
&self.name
}
}
impl Spanned for ConfigurableDeclaration {
fn span(&self) -> sway_types::Span {
self.span.clone()
}
}
impl DebugWithEngines for ConfigurableDeclaration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>, _engines: &Engines) -> std::fmt::Result {
f.write_fmt(format_args!("{}", self.name))
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/impl_trait.rs | sway-core/src/language/parsed/declaration/impl_trait.rs | use super::{ConstantDeclaration, FunctionDeclaration, TraitTypeDeclaration};
use crate::{
decl_engine::{parsed_id::ParsedDeclId, ParsedInterfaceDeclId},
engine_threading::{
DebugWithEngines, EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext,
},
language::CallPath,
type_system::GenericArgument,
Engines, GenericTypeArgument, TypeParameter,
};
use sway_types::{span::Span, Named, Spanned};
#[derive(Debug, Clone)]
pub enum ImplItem {
Fn(ParsedDeclId<FunctionDeclaration>),
Constant(ParsedDeclId<ConstantDeclaration>),
Type(ParsedDeclId<TraitTypeDeclaration>),
}
impl ImplItem {
pub fn span(&self, engines: &Engines) -> Span {
match self {
ImplItem::Fn(id) => engines.pe().get_function(id).span(),
ImplItem::Constant(id) => engines.pe().get_constant(id).span(),
ImplItem::Type(id) => engines.pe().get_trait_type(id).span(),
}
}
}
impl EqWithEngines for ImplItem {}
impl PartialEqWithEngines for ImplItem {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(ImplItem::Fn(lhs), ImplItem::Fn(rhs)) => PartialEqWithEngines::eq(lhs, rhs, ctx),
(ImplItem::Constant(lhs), ImplItem::Constant(rhs)) => {
PartialEqWithEngines::eq(lhs, rhs, ctx)
}
(ImplItem::Type(lhs), ImplItem::Type(rhs)) => PartialEqWithEngines::eq(lhs, rhs, ctx),
_ => false,
}
}
}
impl DebugWithEngines for ImplItem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>, engines: &Engines) -> std::fmt::Result {
match self {
ImplItem::Fn(decl_id) => {
let decl = engines.pe().get_function(decl_id);
f.write_fmt(format_args!("{:?}", engines.help_out(decl)))
}
ImplItem::Constant(decl_id) => {
let decl = engines.pe().get_constant(decl_id);
f.write_fmt(format_args!("{:?}", engines.help_out(decl)))
}
ImplItem::Type(decl_id) => {
let decl = engines.pe().get_trait_type(decl_id);
f.write_fmt(format_args!("{:?}", engines.help_out(decl)))
}
}
}
}
/// An impl trait, or impl self of methods without a trait.
/// like `impl MyType { fn foo { .. } }`
#[derive(Debug, Clone)]
pub struct ImplSelfOrTrait {
pub is_self: bool,
pub impl_type_parameters: Vec<TypeParameter>,
pub trait_name: CallPath,
pub trait_type_arguments: Vec<GenericArgument>,
pub trait_decl_ref: Option<ParsedInterfaceDeclId>,
pub implementing_for: GenericTypeArgument,
pub items: Vec<ImplItem>,
/// The [Span] of the whole impl trait and block.
pub(crate) block_span: Span,
}
impl EqWithEngines for ImplSelfOrTrait {}
impl PartialEqWithEngines for ImplSelfOrTrait {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.impl_type_parameters
.eq(&other.impl_type_parameters, ctx)
&& self.trait_name == other.trait_name
&& self
.trait_type_arguments
.eq(&other.trait_type_arguments, ctx)
&& self.implementing_for.eq(&other.implementing_for, ctx)
&& self.items.eq(&other.items, ctx)
&& self.block_span == other.block_span
}
}
impl Named for ImplSelfOrTrait {
fn name(&self) -> &sway_types::BaseIdent {
&self.trait_name.suffix
}
}
impl Spanned for ImplSelfOrTrait {
fn span(&self) -> sway_types::Span {
self.block_span.clone()
}
}
impl DebugWithEngines for ImplSelfOrTrait {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>, engines: &Engines) -> std::fmt::Result {
if self.is_self {
f.write_fmt(format_args!(
"impl {}",
engines.help_out(self.implementing_for.clone())
))
} else {
f.write_fmt(format_args!(
"impl {} for {:?}",
self.trait_name,
engines.help_out(self.implementing_for.clone())
))
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/const_generic.rs | sway-core/src/language/parsed/declaration/const_generic.rs | use crate::TypeId;
use sway_types::{Ident, Span};
#[derive(Debug, Clone)]
pub struct ConstGenericDeclaration {
pub name: Ident,
pub ty: TypeId,
pub span: Span,
}
impl ConstGenericDeclaration {
pub fn span(&self) -> Span {
self.span.clone()
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/constant.rs | sway-core/src/language/parsed/declaration/constant.rs | use crate::{
engine_threading::{
DebugWithEngines, EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext,
},
language::{parsed::Expression, Visibility},
transform, Engines, GenericTypeArgument,
};
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Debug, Clone)]
pub struct ConstantDeclaration {
pub name: Ident,
pub attributes: transform::Attributes,
pub type_ascription: GenericTypeArgument,
pub value: Option<Expression>,
pub visibility: Visibility,
pub span: Span,
}
impl EqWithEngines for ConstantDeclaration {}
impl PartialEqWithEngines for ConstantDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.attributes == other.attributes
&& self.type_ascription.eq(&other.type_ascription, ctx)
&& self.value.eq(&other.value, ctx)
&& self.visibility == other.visibility
&& self.span == other.span
}
}
impl Named for ConstantDeclaration {
fn name(&self) -> &sway_types::BaseIdent {
&self.name
}
}
impl Spanned for ConstantDeclaration {
fn span(&self) -> sway_types::Span {
self.span.clone()
}
}
impl DebugWithEngines for ConstantDeclaration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>, _engines: &Engines) -> std::fmt::Result {
f.write_fmt(format_args!("{}", self.name))
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/type_alias.rs | sway-core/src/language/parsed/declaration/type_alias.rs | use crate::{
ast_elements::type_argument::GenericTypeArgument,
engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
language::Visibility,
transform,
};
use sway_types::{ident::Ident, span::Span, Named, Spanned};
#[derive(Debug, Clone)]
pub struct TypeAliasDeclaration {
pub name: Ident,
pub attributes: transform::Attributes,
pub ty: GenericTypeArgument,
pub visibility: Visibility,
pub span: Span,
}
impl EqWithEngines for TypeAliasDeclaration {}
impl PartialEqWithEngines for TypeAliasDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.attributes == other.attributes
&& self.ty.eq(&other.ty, ctx)
&& self.visibility == other.visibility
&& self.span == other.span
}
}
impl Named for TypeAliasDeclaration {
fn name(&self) -> &sway_types::BaseIdent {
&self.name
}
}
impl Spanned for TypeAliasDeclaration {
fn span(&self) -> sway_types::Span {
self.span.clone()
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/declaration/enum.rs | sway-core/src/language/parsed/declaration/enum.rs | use crate::{
ast_elements::type_argument::GenericTypeArgument,
engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
language::Visibility,
transform,
type_system::*,
};
use sway_types::{ident::Ident, span::Span, Named, Spanned};
#[derive(Debug, Clone)]
pub struct EnumDeclaration {
pub name: Ident,
pub attributes: transform::Attributes,
pub type_parameters: Vec<TypeParameter>,
pub variants: Vec<EnumVariant>,
pub(crate) span: Span,
pub visibility: Visibility,
}
impl EqWithEngines for EnumDeclaration {}
impl PartialEqWithEngines for EnumDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.attributes == other.attributes
&& self.type_parameters.eq(&other.type_parameters, ctx)
&& self.variants.eq(&other.variants, ctx)
&& self.visibility == other.visibility
&& self.span == other.span
}
}
impl Named for EnumDeclaration {
fn name(&self) -> &sway_types::BaseIdent {
&self.name
}
}
impl Spanned for EnumDeclaration {
fn span(&self) -> sway_types::Span {
self.span.clone()
}
}
#[derive(Debug, Clone)]
pub struct EnumVariant {
pub name: Ident,
pub attributes: transform::Attributes,
pub type_argument: GenericTypeArgument,
pub(crate) tag: usize,
pub(crate) span: Span,
}
impl EqWithEngines for EnumVariant {}
impl PartialEqWithEngines for EnumVariant {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.attributes == other.attributes
&& self.type_argument.eq(&other.type_argument, ctx)
&& self.tag == other.tag
&& self.span == other.span
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/expression/asm.rs | sway-core/src/language/parsed/expression/asm.rs | use super::Expression;
use crate::{
engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
language::{AsmOp, AsmRegister},
TypeInfo,
};
use sway_types::{ident::Ident, span::Span};
#[derive(Debug, Clone)]
pub struct AsmExpression {
pub registers: Vec<AsmRegisterDeclaration>,
pub(crate) body: Vec<AsmOp>,
pub(crate) returns: Option<(AsmRegister, Span)>,
pub(crate) return_type: TypeInfo,
pub(crate) whole_block_span: Span,
}
impl AsmExpression {
/// True if the [AsmExpression] has neither assembly operations nor
/// the return register specified.
pub fn is_empty(&self) -> bool {
self.body.is_empty() && self.returns.is_none()
}
}
impl EqWithEngines for AsmExpression {}
impl PartialEqWithEngines for AsmExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.registers.eq(&other.registers, ctx)
&& self.body == other.body
&& self.returns == other.returns
&& self.return_type.eq(&other.return_type, ctx)
}
}
#[derive(Debug, Clone)]
pub struct AsmRegisterDeclaration {
pub(crate) name: Ident,
pub initializer: Option<Expression>,
}
impl EqWithEngines for AsmRegisterDeclaration {}
impl PartialEqWithEngines for AsmRegisterDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name && self.initializer.eq(&other.initializer, ctx)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/expression/method_name.rs | sway-core/src/language/parsed/expression/method_name.rs | use crate::engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext};
use crate::language::CallPath;
use crate::type_system::TypeBinding;
use crate::{GenericArgument, Ident, TypeId, TypeInfo};
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum MethodName {
/// Represents a method lookup with a type somewhere in the path
/// like `a::b::C::d()` with `C` being the type.
FromType {
call_path_binding: TypeBinding<CallPath<(TypeInfo, Ident)>>,
method_name: Ident,
},
/// Represents a method lookup that does not contain any types in the path
/// something like a.b(c)
/// in this case, the first argument defines where to look for the method
FromModule { method_name: Ident },
/// something like a::b::c()
/// in this case, the path defines where the fn symbol is defined
/// used for things like std::ops::add(a, b).
/// in this case, the first argument determines the type to look for
FromTrait { call_path: CallPath },
/// Represents a method lookup with a fully qualified path.
/// like <S as Trait>::method()
FromQualifiedPathRoot {
ty: GenericArgument,
as_trait: TypeId,
method_name: Ident,
},
}
impl EqWithEngines for MethodName {}
impl PartialEqWithEngines for MethodName {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(
MethodName::FromType {
call_path_binding,
method_name,
},
MethodName::FromType {
call_path_binding: r_call_path_binding,
method_name: r_method_name,
},
) => call_path_binding.eq(r_call_path_binding, ctx) && method_name == r_method_name,
(
MethodName::FromModule { method_name },
MethodName::FromModule {
method_name: r_method_name,
},
) => method_name == r_method_name,
(
MethodName::FromTrait { call_path },
MethodName::FromTrait {
call_path: r_call_path,
},
) => call_path == r_call_path,
(
MethodName::FromQualifiedPathRoot {
ty,
as_trait,
method_name,
},
MethodName::FromQualifiedPathRoot {
ty: r_ty,
as_trait: r_as_trait,
method_name: r_method_name,
},
) => ty.eq(r_ty, ctx) && as_trait.eq(r_as_trait) && method_name == r_method_name,
_ => false,
}
}
}
impl MethodName {
/// To be used for error messages and debug strings
pub fn easy_name(&self) -> Ident {
match self {
MethodName::FromType { method_name, .. } => method_name.clone(),
MethodName::FromTrait { call_path, .. } => call_path.suffix.clone(),
MethodName::FromModule { method_name, .. } => method_name.clone(),
MethodName::FromQualifiedPathRoot { method_name, .. } => method_name.clone(),
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/expression/scrutinee.rs | sway-core/src/language/parsed/expression/scrutinee.rs | use crate::{
engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
language::{CallPath, Literal},
TypeInfo,
};
use sway_error::handler::ErrorEmitted;
use sway_types::{ident::Ident, span::Span, Spanned};
/// A [Scrutinee] is on the left-hand-side of a pattern, and dictates whether or
/// not a pattern will succeed at pattern matching and what, if any, elements will
/// need to be implemented in a desugared if expression.
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone)]
pub enum Scrutinee {
Or {
elems: Vec<Scrutinee>,
span: Span,
},
CatchAll {
span: Span,
},
Literal {
value: Literal,
span: Span,
},
Variable {
name: Ident,
span: Span,
},
AmbiguousSingleIdent(Ident),
StructScrutinee {
struct_name: CallPath,
fields: Vec<StructScrutineeField>,
span: Span,
},
EnumScrutinee {
call_path: CallPath,
value: Box<Scrutinee>,
span: Span,
},
Tuple {
elems: Vec<Scrutinee>,
span: Span,
},
// this is to handle parser recovery
Error {
spans: Box<[Span]>,
err: ErrorEmitted,
},
}
impl EqWithEngines for Scrutinee {}
impl PartialEqWithEngines for Scrutinee {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(
Scrutinee::Or { elems, span },
Scrutinee::Or {
elems: r_elems,
span: r_span,
},
) => elems.eq(r_elems, ctx) && span.eq(r_span),
(
Scrutinee::Literal { value, span },
Scrutinee::Literal {
value: r_value,
span: r_span,
},
) => value.eq(r_value) && span.eq(r_span),
(
Scrutinee::Variable { name, span },
Scrutinee::Variable {
name: r_name,
span: r_span,
},
) => name.eq(r_name) && span.eq(r_span),
(Scrutinee::AmbiguousSingleIdent(ident), Scrutinee::AmbiguousSingleIdent(r_ident)) => {
ident.eq(r_ident)
}
(
Scrutinee::StructScrutinee {
struct_name,
fields,
span,
},
Scrutinee::StructScrutinee {
struct_name: r_struct_name,
fields: r_fields,
span: r_span,
},
) => {
PartialEqWithEngines::eq(struct_name, r_struct_name, ctx)
&& fields.eq(r_fields, ctx)
&& span.eq(r_span)
}
(
Scrutinee::EnumScrutinee {
call_path,
value,
span,
},
Scrutinee::EnumScrutinee {
call_path: r_call_path,
value: r_value,
span: r_span,
},
) => {
PartialEqWithEngines::eq(call_path, r_call_path, ctx)
&& value.eq(r_value, ctx)
&& span.eq(r_span)
}
(
Scrutinee::Tuple { elems, span },
Scrutinee::Tuple {
elems: r_elems,
span: r_span,
},
) => elems.eq(r_elems, ctx) && span.eq(r_span),
(
Scrutinee::Error { spans, err },
Scrutinee::Error {
spans: r_spans,
err: r_err,
},
) => spans.eq(r_spans) && err.eq(r_err),
_ => false,
}
}
}
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum StructScrutineeField {
Rest {
span: Span,
},
Field {
field: Ident,
scrutinee: Option<Scrutinee>,
span: Span,
},
}
impl EqWithEngines for StructScrutineeField {}
impl PartialEqWithEngines for StructScrutineeField {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(StructScrutineeField::Rest { span }, StructScrutineeField::Rest { span: r_span }) => {
span == r_span
}
(
StructScrutineeField::Field {
field,
scrutinee,
span,
},
StructScrutineeField::Field {
field: r_field,
scrutinee: r_scrutinee,
span: r_span,
},
) => field.eq(r_field) && scrutinee.eq(r_scrutinee, ctx) && span.eq(r_span),
_ => false,
}
}
}
impl Spanned for Scrutinee {
fn span(&self) -> Span {
match self {
Scrutinee::Or { span, .. } => span.clone(),
Scrutinee::CatchAll { span } => span.clone(),
Scrutinee::Literal { span, .. } => span.clone(),
Scrutinee::Variable { span, .. } => span.clone(),
Scrutinee::AmbiguousSingleIdent(ident) => ident.span(),
Scrutinee::StructScrutinee { span, .. } => span.clone(),
Scrutinee::EnumScrutinee { span, .. } => span.clone(),
Scrutinee::Tuple { span, .. } => span.clone(),
Scrutinee::Error { spans, .. } => spans
.iter()
.cloned()
.reduce(|s1: Span, s2: Span| Span::join(s1, &s2))
.unwrap(),
}
}
}
impl Scrutinee {
/// Given some `Scrutinee` `self`, analyze `self` and return all instances
/// of possible dependencies. A "possible dependency" is a `Scrutinee` that
/// resolves to one or more `TypeInfo::Custom`.
///
/// For example, this `Scrutinee`:
///
/// ```ignore
/// Scrutinee::EnumScrutinee {
/// call_path: CallPath {
/// prefixes: ["Data"]
/// suffix: "A"
/// },
/// value: Scrutinee::StructScrutinee {
/// struct_name: "Foo",
/// fields: [
/// StructScrutineeField {
/// scrutinee: Scrutinee::StructScrutinee {
/// struct_name: "Bar",
/// fields: [
/// StructScrutineeField {
/// scrutinee: Scrutinee::Literal { .. },
/// ..
/// }
/// ],
/// ..
/// },
/// ..
/// }
/// ],
/// ..
/// }
/// ..
/// }
/// ```
///
/// would resolve to this list of approximate `TypeInfo` dependencies:
///
/// ```ignore
/// [
/// TypeInfo::Custom {
/// name: "Data",
/// ..
/// },
/// TypeInfo::Custom {
/// name: "Foo",
/// ..
/// },
/// TypeInfo::Custom {
/// name: "Bar",
/// ..
/// },
/// ]
/// ```
pub(crate) fn gather_approximate_typeinfo_dependencies(&self) -> Vec<TypeInfo> {
match self {
Scrutinee::StructScrutinee {
struct_name,
fields,
..
} => {
let name = vec![TypeInfo::Custom {
qualified_call_path: struct_name.clone().into(),
type_arguments: None,
}];
let fields = fields
.iter()
.flat_map(|f| match f {
StructScrutineeField::Field {
scrutinee: Some(scrutinee),
..
} => scrutinee.gather_approximate_typeinfo_dependencies(),
_ => vec![],
})
.collect::<Vec<TypeInfo>>();
[name, fields].concat()
}
Scrutinee::EnumScrutinee {
call_path, value, ..
} => {
let enum_name = call_path.prefixes.last().unwrap_or(&call_path.suffix);
let name = vec![TypeInfo::Custom {
qualified_call_path: enum_name.clone().into(),
type_arguments: None,
}];
let value = value.gather_approximate_typeinfo_dependencies();
[name, value].concat()
}
Scrutinee::Tuple { elems, .. } | Scrutinee::Or { elems, .. } => elems
.iter()
.flat_map(|scrutinee| scrutinee.gather_approximate_typeinfo_dependencies())
.collect::<Vec<TypeInfo>>(),
Scrutinee::Literal { .. }
| Scrutinee::CatchAll { .. }
| Scrutinee::AmbiguousSingleIdent(..)
| Scrutinee::Variable { .. }
| Scrutinee::Error { .. } => {
vec![]
}
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/expression/match_branch.rs | sway-core/src/language/parsed/expression/match_branch.rs | use crate::engine_threading::{EqWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext};
use super::{Expression, Scrutinee};
use sway_types::span;
#[derive(Debug, Clone)]
pub struct MatchBranch {
pub scrutinee: Scrutinee,
pub result: Expression,
pub(crate) span: span::Span,
}
impl EqWithEngines for MatchBranch {}
impl PartialEqWithEngines for MatchBranch {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.scrutinee.eq(&other.scrutinee, ctx) && self.result.eq(&other.result, ctx)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/parsed/expression/mod.rs | sway-core/src/language/parsed/expression/mod.rs | use crate::{
decl_engine::parsed_id::ParsedDeclId,
engine_threading::{
DebugWithEngines, DisplayWithEngines, EqWithEngines, HashWithEngines, OrdWithEngines,
OrdWithEnginesContext, PartialEqWithEngines, PartialEqWithEnginesContext,
},
language::{parsed::CodeBlock, *},
type_system::TypeBinding,
Engines, GenericArgument, TypeId,
};
use serde::{Deserialize, Serialize};
use std::{cmp::Ordering, fmt, hash::Hasher};
use sway_error::handler::ErrorEmitted;
use sway_types::{ident::Ident, Span, Spanned};
mod asm;
mod match_branch;
mod method_name;
mod scrutinee;
pub(crate) use asm::*;
pub(crate) use match_branch::MatchBranch;
pub use method_name::MethodName;
pub use scrutinee::*;
use sway_ast::intrinsics::Intrinsic;
use super::{FunctionDeclaration, StructDeclaration};
/// Represents a parsed, but not yet type checked, [Expression](https://en.wikipedia.org/wiki/Expression_(computer_science)).
#[derive(Debug, Clone)]
pub struct Expression {
pub kind: ExpressionKind,
pub span: Span,
}
#[derive(Debug, Clone)]
pub struct FunctionApplicationExpression {
pub call_path_binding: TypeBinding<CallPath>,
pub resolved_call_path_binding:
Option<TypeBinding<ResolvedCallPath<ParsedDeclId<FunctionDeclaration>>>>,
pub arguments: Vec<Expression>,
}
impl EqWithEngines for FunctionApplicationExpression {}
impl PartialEqWithEngines for FunctionApplicationExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.call_path_binding.eq(&other.call_path_binding, ctx)
&& self.arguments.eq(&other.arguments, ctx)
}
}
#[derive(Debug, Clone)]
pub struct LazyOperatorExpression {
pub op: LazyOp,
pub lhs: Box<Expression>,
pub rhs: Box<Expression>,
}
impl EqWithEngines for LazyOperatorExpression {}
impl PartialEqWithEngines for LazyOperatorExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.op == other.op && self.lhs.eq(&other.lhs, ctx) && self.rhs.eq(&other.rhs, ctx)
}
}
#[derive(Debug, Clone)]
pub struct TupleIndexExpression {
pub prefix: Box<Expression>,
pub index: usize,
pub index_span: Span,
}
impl EqWithEngines for TupleIndexExpression {}
impl PartialEqWithEngines for TupleIndexExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.prefix.eq(&other.prefix, ctx)
&& self.index == other.index
&& self.index_span == other.index_span
}
}
#[derive(Debug, Clone)]
pub enum ArrayExpression {
Explicit {
contents: Vec<Expression>,
length_span: Option<Span>,
},
Repeat {
value: Box<Expression>,
length: Box<Expression>,
},
}
impl EqWithEngines for ArrayExpression {}
impl PartialEqWithEngines for ArrayExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(
ArrayExpression::Explicit {
contents: self_contents,
length_span: self_length_span,
},
ArrayExpression::Explicit {
contents: other_contents,
length_span: other_length_span,
},
) => self_contents.eq(other_contents, ctx) && self_length_span == other_length_span,
(
ArrayExpression::Repeat {
value: self_value,
length: self_length,
},
ArrayExpression::Repeat {
value: other_value,
length: other_length,
},
) => self_value.eq(other_value, ctx) && self_length.eq(other_length, ctx),
_ => false,
}
}
}
#[derive(Debug, Clone)]
pub struct StructExpression {
pub resolved_call_path_binding:
Option<TypeBinding<ResolvedCallPath<ParsedDeclId<StructDeclaration>>>>,
pub call_path_binding: TypeBinding<CallPath>,
pub fields: Vec<StructExpressionField>,
}
impl EqWithEngines for StructExpression {}
impl PartialEqWithEngines for StructExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.call_path_binding.eq(&other.call_path_binding, ctx)
&& self.fields.eq(&other.fields, ctx)
}
}
#[derive(Debug, Clone)]
pub struct IfExpression {
pub condition: Box<Expression>,
pub then: Box<Expression>,
pub r#else: Option<Box<Expression>>,
}
impl EqWithEngines for IfExpression {}
impl PartialEqWithEngines for IfExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.condition.eq(&other.condition, ctx)
&& self.then.eq(&other.then, ctx)
&& self.r#else.eq(&other.r#else, ctx)
}
}
#[derive(Debug, Clone)]
pub struct MatchExpression {
pub value: Box<Expression>,
pub branches: Vec<MatchBranch>,
}
impl EqWithEngines for MatchExpression {}
impl PartialEqWithEngines for MatchExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.value.eq(&other.value, ctx) && self.branches.eq(&other.branches, ctx)
}
}
#[derive(Debug, Clone)]
pub struct MethodApplicationExpression {
pub method_name_binding: TypeBinding<MethodName>,
pub contract_call_params: Vec<StructExpressionField>,
pub arguments: Vec<Expression>,
}
impl EqWithEngines for MethodApplicationExpression {}
impl PartialEqWithEngines for MethodApplicationExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.method_name_binding.eq(&other.method_name_binding, ctx)
&& self
.contract_call_params
.eq(&other.contract_call_params, ctx)
&& self.arguments.eq(&other.arguments, ctx)
}
}
#[derive(Debug, Clone)]
pub struct SubfieldExpression {
pub prefix: Box<Expression>,
pub field_to_access: Ident,
}
impl EqWithEngines for SubfieldExpression {}
impl PartialEqWithEngines for SubfieldExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.prefix.eq(&other.prefix, ctx) && self.field_to_access == other.field_to_access
}
}
#[derive(Debug, Clone)]
pub struct AmbiguousSuffix {
/// If the suffix is a pair, the ambiguous part of the suffix.
///
/// For example, if we have `Foo::bar()`,
/// we don't know whether `Foo` is a module or a type,
/// so `before` would be `Foo` here with any type arguments.
pub before: Option<TypeBinding<Ident>>,
/// The final suffix, i.e., the function or variant name.
///
/// In the example above, this would be `bar`.
pub suffix: Ident,
}
impl EqWithEngines for AmbiguousSuffix {}
impl PartialEqWithEngines for AmbiguousSuffix {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.before.eq(&other.before, ctx) && self.suffix == other.suffix
}
}
impl Spanned for AmbiguousSuffix {
fn span(&self) -> Span {
if let Some(before) = &self.before {
Span::join(before.span(), &self.suffix.span())
} else {
self.suffix.span()
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualifiedPathType {
pub ty: GenericArgument,
pub as_trait: TypeId,
pub as_trait_span: Span,
}
impl HashWithEngines for QualifiedPathType {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let QualifiedPathType {
ty,
as_trait,
// ignored fields
as_trait_span: _,
} = self;
ty.hash(state, engines);
engines.te().get(*as_trait).hash(state, engines);
}
}
impl EqWithEngines for QualifiedPathType {}
impl PartialEqWithEngines for QualifiedPathType {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let QualifiedPathType {
ty,
as_trait,
// ignored fields
as_trait_span: _,
} = self;
ty.eq(&other.ty, ctx)
&& ctx
.engines()
.te()
.get(*as_trait)
.eq(&ctx.engines().te().get(other.as_trait), ctx)
}
}
impl OrdWithEngines for QualifiedPathType {
fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering {
let QualifiedPathType {
ty: l_ty,
as_trait: l_as_trait,
// ignored fields
as_trait_span: _,
} = self;
let QualifiedPathType {
ty: r_ty,
as_trait: r_as_trait,
// ignored fields
as_trait_span: _,
} = other;
l_ty.cmp(r_ty, ctx).then_with(|| {
ctx.engines()
.te()
.get(*l_as_trait)
.cmp(&ctx.engines().te().get(*r_as_trait), ctx)
})
}
}
impl DisplayWithEngines for QualifiedPathType {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(
f,
"<{} as {}>",
engines.help_out(self.ty.clone()),
engines.help_out(self.as_trait)
)
}
}
impl DebugWithEngines for QualifiedPathType {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(f, "{}", engines.help_out(self),)
}
}
#[derive(Debug, Clone)]
pub struct AmbiguousPathExpression {
pub qualified_path_root: Option<QualifiedPathType>,
pub call_path_binding: TypeBinding<CallPath<AmbiguousSuffix>>,
pub args: Vec<Expression>,
}
impl EqWithEngines for AmbiguousPathExpression {}
impl PartialEqWithEngines for AmbiguousPathExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.qualified_path_root.eq(&other.qualified_path_root, ctx)
&& PartialEqWithEngines::eq(&self.call_path_binding, &other.call_path_binding, ctx)
&& self.args.eq(&other.args, ctx)
}
}
#[derive(Debug, Clone)]
pub struct DelineatedPathExpression {
pub call_path_binding: TypeBinding<QualifiedCallPath>,
/// When args is equal to Option::None then it means that the
/// [DelineatedPathExpression] was initialized from an expression
/// that does not end with parenthesis.
pub args: Option<Vec<Expression>>,
}
impl EqWithEngines for DelineatedPathExpression {}
impl PartialEqWithEngines for DelineatedPathExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.call_path_binding.eq(&other.call_path_binding, ctx) && self.args.eq(&other.args, ctx)
}
}
#[derive(Debug, Clone)]
pub struct AbiCastExpression {
pub abi_name: CallPath,
pub address: Box<Expression>,
}
impl EqWithEngines for AbiCastExpression {}
impl PartialEqWithEngines for AbiCastExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
PartialEqWithEngines::eq(&self.abi_name, &other.abi_name, ctx)
&& self.address.eq(&other.address, ctx)
}
}
#[derive(Debug, Clone)]
pub struct ArrayIndexExpression {
pub prefix: Box<Expression>,
pub index: Box<Expression>,
}
impl EqWithEngines for ArrayIndexExpression {}
impl PartialEqWithEngines for ArrayIndexExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.prefix.eq(&other.prefix, ctx) && self.index.eq(&other.index, ctx)
}
}
#[derive(Debug, Clone)]
pub struct StorageAccessExpression {
pub namespace_names: Vec<Ident>,
pub field_names: Vec<Ident>,
pub storage_keyword_span: Span,
}
impl EqWithEngines for StorageAccessExpression {}
impl PartialEqWithEngines for StorageAccessExpression {
fn eq(&self, other: &Self, _ctx: &PartialEqWithEnginesContext) -> bool {
self.field_names.eq(&other.field_names)
&& self.storage_keyword_span.eq(&other.storage_keyword_span)
}
}
#[derive(Debug, Clone)]
pub struct IntrinsicFunctionExpression {
pub name: Ident,
pub kind_binding: TypeBinding<Intrinsic>,
pub arguments: Vec<Expression>,
}
impl EqWithEngines for IntrinsicFunctionExpression {}
impl PartialEqWithEngines for IntrinsicFunctionExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name.eq(&other.name)
&& self.kind_binding.eq(&other.kind_binding, ctx)
&& self.arguments.eq(&other.arguments, ctx)
}
}
#[derive(Debug, Clone)]
pub struct WhileLoopExpression {
pub condition: Box<Expression>,
pub body: CodeBlock,
pub is_desugared_for_loop: bool,
}
impl EqWithEngines for WhileLoopExpression {}
impl PartialEqWithEngines for WhileLoopExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.condition.eq(&other.condition, ctx) && self.body.eq(&other.body, ctx)
}
}
#[derive(Debug, Clone)]
pub struct ForLoopExpression {
pub desugared: Box<Expression>,
}
impl EqWithEngines for ForLoopExpression {}
impl PartialEqWithEngines for ForLoopExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.desugared.eq(&other.desugared, ctx)
}
}
#[derive(Debug, Clone)]
pub struct ReassignmentExpression {
pub lhs: ReassignmentTarget,
pub rhs: Box<Expression>,
}
impl EqWithEngines for ReassignmentExpression {}
impl PartialEqWithEngines for ReassignmentExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.lhs.eq(&other.lhs, ctx) && self.rhs.eq(&other.rhs, ctx)
}
}
#[derive(Debug, Clone)]
pub enum ExpressionKind {
/// A malformed expression.
///
/// Used for parser recovery when we cannot form a more specific node.
/// The list of `Span`s are for consumption by the LSP and are,
/// when joined, the same as that stored in `expr.span`.
Error(Box<[Span]>, ErrorEmitted),
Literal(Literal),
/// An ambiguous path where we don't know until type checking whether this
/// is a free function call, an enum variant or a UFCS (Rust term) style associated function call.
AmbiguousPathExpression(Box<AmbiguousPathExpression>),
FunctionApplication(Box<FunctionApplicationExpression>),
LazyOperator(LazyOperatorExpression),
/// And ambiguous single ident which could either be a variable or an enum variant
AmbiguousVariableExpression(Ident),
Variable(Ident),
Tuple(Vec<Expression>),
TupleIndex(TupleIndexExpression),
Array(ArrayExpression),
Struct(Box<StructExpression>),
CodeBlock(CodeBlock),
If(IfExpression),
Match(MatchExpression),
// separated into other struct for parsing reasons
Asm(Box<AsmExpression>),
MethodApplication(Box<MethodApplicationExpression>),
/// A _subfield expression_ is anything of the form:
/// ```ignore
/// <ident>.<ident>
/// ```
///
Subfield(SubfieldExpression),
/// A _delineated path_ is anything of the form:
/// ```ignore
/// <ident>::<ident>
/// ```
/// Where there are `n >= 2` idents.
/// These could be either enum variant constructions, or they could be
/// references to some sort of module in the module tree.
/// For example, a reference to a module:
/// ```ignore
/// std::ops::add
/// ```
///
/// And, an enum declaration:
/// ```ignore
/// enum MyEnum {
/// Variant1,
/// Variant2
/// }
///
/// MyEnum::Variant1
/// ```
DelineatedPath(Box<DelineatedPathExpression>),
/// A cast of a hash to an ABI for calling a contract.
AbiCast(Box<AbiCastExpression>),
ArrayIndex(ArrayIndexExpression),
StorageAccess(StorageAccessExpression),
IntrinsicFunction(IntrinsicFunctionExpression),
/// A control flow element which loops continually until some boolean expression evaluates as
/// `false`.
WhileLoop(WhileLoopExpression),
/// A control flow element which loops between values of an iterator.
ForLoop(ForLoopExpression),
Break,
Continue,
Reassignment(ReassignmentExpression),
/// An implicit return expression is different from a [Expression::Return] because
/// it is not a control flow item. Therefore it is a different variant.
///
/// An implicit return expression is an [Expression] at the end of a code block which has no
/// semicolon, denoting that it is the [Expression] to be returned from that block.
ImplicitReturn(Box<Expression>),
Return(Box<Expression>),
Panic(Box<Expression>),
Ref(RefExpression),
Deref(Box<Expression>),
}
impl EqWithEngines for Expression {}
impl PartialEqWithEngines for Expression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.kind.eq(&other.kind, ctx)
}
}
impl EqWithEngines for ExpressionKind {}
impl PartialEqWithEngines for ExpressionKind {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(ExpressionKind::Error(l_span, _), ExpressionKind::Error(r_span, _)) => {
l_span == r_span
}
(ExpressionKind::Literal(l_literal), ExpressionKind::Literal(r_literal)) => {
l_literal == r_literal
}
(
ExpressionKind::AmbiguousPathExpression(lhs),
ExpressionKind::AmbiguousPathExpression(rhs),
) => lhs.eq(rhs, ctx),
(
ExpressionKind::FunctionApplication(lhs),
ExpressionKind::FunctionApplication(rhs),
) => lhs.eq(rhs, ctx),
(ExpressionKind::LazyOperator(lhs), ExpressionKind::LazyOperator(rhs)) => {
lhs.eq(rhs, ctx)
}
(
ExpressionKind::AmbiguousVariableExpression(lhs),
ExpressionKind::AmbiguousVariableExpression(rhs),
) => lhs == rhs,
(ExpressionKind::Variable(lhs), ExpressionKind::Variable(rhs)) => lhs == rhs,
(ExpressionKind::Tuple(lhs), ExpressionKind::Tuple(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::TupleIndex(lhs), ExpressionKind::TupleIndex(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::Array(lhs), ExpressionKind::Array(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::Struct(lhs), ExpressionKind::Struct(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::CodeBlock(lhs), ExpressionKind::CodeBlock(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::If(lhs), ExpressionKind::If(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::Match(lhs), ExpressionKind::Match(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::Asm(lhs), ExpressionKind::Asm(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::MethodApplication(lhs), ExpressionKind::MethodApplication(rhs)) => {
lhs.eq(rhs, ctx)
}
(ExpressionKind::Subfield(lhs), ExpressionKind::Subfield(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::DelineatedPath(lhs), ExpressionKind::DelineatedPath(rhs)) => {
lhs.eq(rhs, ctx)
}
(ExpressionKind::AbiCast(lhs), ExpressionKind::AbiCast(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::ArrayIndex(lhs), ExpressionKind::ArrayIndex(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::StorageAccess(lhs), ExpressionKind::StorageAccess(rhs)) => {
lhs.eq(rhs, ctx)
}
(ExpressionKind::IntrinsicFunction(lhs), ExpressionKind::IntrinsicFunction(rhs)) => {
lhs.eq(rhs, ctx)
}
(ExpressionKind::WhileLoop(lhs), ExpressionKind::WhileLoop(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::ForLoop(lhs), ExpressionKind::ForLoop(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::Break, ExpressionKind::Break) => true,
(ExpressionKind::Continue, ExpressionKind::Continue) => true,
(ExpressionKind::Reassignment(lhs), ExpressionKind::Reassignment(rhs)) => {
lhs.eq(rhs, ctx)
}
(ExpressionKind::ImplicitReturn(lhs), ExpressionKind::ImplicitReturn(rhs)) => {
lhs.eq(rhs, ctx)
}
(ExpressionKind::Return(lhs), ExpressionKind::Return(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::Panic(lhs), ExpressionKind::Panic(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::Ref(lhs), ExpressionKind::Ref(rhs)) => lhs.eq(rhs, ctx),
(ExpressionKind::Deref(lhs), ExpressionKind::Deref(rhs)) => lhs.eq(rhs, ctx),
_ => false,
}
}
}
#[derive(Debug, Clone)]
pub struct RefExpression {
/// True if the reference is a reference to a mutable `value`.
pub to_mutable_value: bool,
pub value: Box<Expression>,
}
impl EqWithEngines for RefExpression {}
impl PartialEqWithEngines for RefExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.to_mutable_value.eq(&other.to_mutable_value) && self.value.eq(&other.value, ctx)
}
}
#[derive(Debug, Clone)]
pub enum ReassignmentTarget {
/// An [Expression] representing a single variable or a path
/// to a part of an aggregate.
/// E.g.:
/// - `my_variable`
/// - `array[0].field.x.1`
ElementAccess(Box<Expression>),
/// An dereferencing [Expression] representing dereferencing
/// of an arbitrary reference expression.
/// E.g.:
/// - *my_ref
/// - **if x > 0 { &mut &mut a } else { &mut &mut b }
Deref(Box<Expression>),
}
impl EqWithEngines for ReassignmentTarget {}
impl PartialEqWithEngines for ReassignmentTarget {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(ReassignmentTarget::ElementAccess(lhs), ReassignmentTarget::ElementAccess(rhs)) => {
lhs.eq(rhs, ctx)
}
(ReassignmentTarget::Deref(lhs), ReassignmentTarget::Deref(rhs)) => lhs.eq(rhs, ctx),
_ => false,
}
}
}
#[derive(Debug, Clone)]
pub struct StructExpressionField {
pub name: Ident,
pub value: Expression,
}
impl EqWithEngines for StructExpressionField {}
impl PartialEqWithEngines for StructExpressionField {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name && self.value.eq(&other.value, ctx)
}
}
impl Spanned for Expression {
fn span(&self) -> Span {
self.span.clone()
}
}
#[derive(Debug)]
pub(crate) struct Op {
pub span: Span,
pub op_variant: OpVariant,
}
impl Op {
pub fn to_method_name(&self) -> Ident {
Ident::new_with_override(self.op_variant.method_name().to_string(), self.span.clone())
}
}
#[derive(Debug)]
pub enum OpVariant {
Add,
Subtract,
Divide,
Multiply,
Modulo,
Or,
And,
Equals,
NotEquals,
Xor,
BinaryOr,
BinaryAnd,
GreaterThan,
LessThan,
GreaterThanOrEqualTo,
LessThanOrEqualTo,
}
impl OpVariant {
/// For all the operators except [OpVariant::Or] and [OpVariant::And],
/// returns the name of the method that can be found on the corresponding
/// operator trait. E.g., for `+` that will be the method `add` defined in
/// `std::ops::Add::add`.
///
/// [OpVariant::Or] and [OpVariant::And] are lazy and must be handled
/// internally by the compiler.
fn method_name(&self) -> &'static str {
use OpVariant::*;
match self {
Add => "add",
Subtract => "subtract",
Divide => "divide",
Multiply => "multiply",
Modulo => "modulo",
Or => "$or$",
And => "$and$",
Equals => "eq",
NotEquals => "neq",
Xor => "xor",
BinaryOr => "binary_or",
BinaryAnd => "binary_and",
GreaterThan => "gt",
LessThan => "lt",
LessThanOrEqualTo => "le",
GreaterThanOrEqualTo => "ge",
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/lexed/program.rs | sway-core/src/language/lexed/program.rs | use super::LexedModule;
use crate::language::parsed::TreeType;
/// A lexed, but not yet parsed or type-checked, Sway program.
///
/// Includes all modules in the form of a [LexedModule] tree accessed via the `root`.
#[derive(Debug, Clone)]
pub struct LexedProgram {
pub kind: TreeType,
pub root: LexedModule,
}
impl LexedProgram {
pub fn new(kind: TreeType, root: LexedModule) -> LexedProgram {
LexedProgram { kind, root }
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/lexed/mod.rs | sway-core/src/language/lexed/mod.rs | mod program;
use crate::language::ModName;
pub use program::LexedProgram;
use sway_ast::{attribute::Annotated, Module};
use super::{HasModule, HasSubmodules};
/// A module and its submodules in the form of a tree.
#[derive(Debug, Clone)]
pub struct LexedModule {
/// The content of this module in the form of a [Module].
pub tree: Annotated<Module>,
/// Submodules introduced within this module using the `mod` syntax in order of declaration.
pub submodules: Vec<(ModName, LexedSubmodule)>,
}
/// A library module that was declared as a `mod` of another module.
///
/// Only submodules are guaranteed to be a `library`.
#[derive(Debug, Clone)]
pub struct LexedSubmodule {
pub module: LexedModule,
}
impl HasModule<LexedModule> for LexedSubmodule {
fn module(&self) -> &LexedModule {
&self.module
}
}
impl HasSubmodules<LexedSubmodule> for LexedModule {
fn submodules(&self) -> &[(ModName, LexedSubmodule)] {
&self.submodules
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/program.rs | sway-core/src/language/ty/program.rs | use std::sync::Arc;
use crate::{
decl_engine::*,
fuel_prelude::fuel_tx::StorageSlot,
language::{parsed, ty::*, Purity, Visibility},
namespace::{check_impls_for_overlap, check_orphan_rules_for_impls, TraitMap},
semantic_analysis::namespace,
transform::AllowDeprecatedState,
type_system::*,
types::*,
Engines,
};
use sway_error::{
error::{CompileError, TypeNotAllowedReason},
handler::{ErrorEmitted, Handler},
};
use sway_features::ExperimentalFeatures;
use sway_types::*;
#[derive(Debug, Clone)]
pub struct TyProgram {
pub kind: TyProgramKind,
pub root_module: TyModule,
pub namespace: namespace::Namespace,
pub declarations: Vec<TyDecl>,
pub configurables: Vec<TyConfigurableDecl>,
pub storage_slots: Vec<StorageSlot>,
pub logged_types: Vec<(LogId, TypeId)>,
pub messages_types: Vec<(MessageId, TypeId)>,
}
fn get_type_not_allowed_error(
engines: &Engines,
type_id: TypeId,
spanned: &impl Spanned,
f: impl Fn(&TypeInfo) -> Option<TypeNotAllowedReason>,
) -> Option<CompileError> {
let types = type_id.extract_any_including_self(engines, &|t| f(t).is_some(), vec![], 0);
let (id, _) = types.into_iter().next()?;
let t = engines.te().get(id);
Some(CompileError::TypeNotAllowed {
reason: f(&t)?,
span: spanned.span(),
})
}
fn check_no_ref_main(engines: &Engines, handler: &Handler, main_function: &DeclId<TyFunctionDecl>) {
let main_function = engines.de().get_function(main_function);
for param in main_function.parameters.iter() {
if param.is_reference && param.is_mutable {
handler.emit_err(CompileError::RefMutableNotAllowedInMain {
param_name: param.name.clone(),
span: param.name.span(),
});
}
}
}
impl TyProgram {
pub fn validate_coherence(
handler: &Handler,
engines: &Engines,
root: &TyModule,
root_namespace: &mut namespace::Namespace,
) -> Result<(), ErrorEmitted> {
// check orphan rules for all traits
check_orphan_rules_for_impls(handler, engines, root_namespace.current_package_ref())?;
// check trait overlap
let mut unified_trait_map = root_namespace
.current_package_ref()
.root_module()
.root_lexical_scope()
.items
.implemented_traits
.clone();
Self::validate_coherence_overlap(
handler,
engines,
root,
root_namespace,
&mut unified_trait_map,
)?;
Ok(())
}
pub fn validate_coherence_overlap(
handler: &Handler,
engines: &Engines,
module: &TyModule,
root_namespace: &mut namespace::Namespace,
unified_trait_map: &mut TraitMap,
) -> Result<(), ErrorEmitted> {
let other_trait_map = unified_trait_map.clone();
check_impls_for_overlap(unified_trait_map, handler, other_trait_map, engines)?;
for (submod_name, submodule) in module.submodules.iter() {
root_namespace.push_submodule(
handler,
engines,
submod_name.clone(),
Visibility::Public,
submodule.mod_name_span.clone(),
false,
)?;
Self::validate_coherence_overlap(
handler,
engines,
&submodule.module,
root_namespace,
unified_trait_map,
)?;
root_namespace.pop_submodule();
}
Ok(())
}
/// Validate the root module given the expected program kind.
pub fn validate_root(
handler: &Handler,
engines: &Engines,
root: &TyModule,
kind: parsed::TreeType,
package_name: &str,
experimental: ExperimentalFeatures,
) -> Result<(TyProgramKind, Vec<TyDecl>, Vec<TyConfigurableDecl>), ErrorEmitted> {
// Extract program-kind-specific properties from the root nodes.
let ty_engine = engines.te();
let decl_engine = engines.de();
// Validate all submodules
let mut configurables = vec![];
for (_, submodule) in &root.submodules {
let _ = Self::validate_root(
handler,
engines,
&submodule.module,
parsed::TreeType::Library,
package_name,
experimental,
);
}
let mut entries = Vec::new();
let mut mains = Vec::new();
let mut declarations = Vec::<TyDecl>::new();
let mut abi_entries = Vec::new();
let mut fn_declarations = std::collections::HashSet::new();
for node in &root.all_nodes {
match &node.content {
TyAstNodeContent::Declaration(TyDecl::FunctionDecl(FunctionDecl { decl_id })) => {
let func = decl_engine.get_function(decl_id);
match func.kind {
TyFunctionDeclKind::Main => mains.push(*decl_id),
TyFunctionDeclKind::Entry => entries.push(*decl_id),
_ => {}
}
if !fn_declarations.insert(func.name.clone()) {
handler.emit_err(CompileError::MultipleDefinitionsOfFunction {
name: func.name.clone(),
span: func.name.span(),
});
}
declarations.push(TyDecl::FunctionDecl(FunctionDecl { decl_id: *decl_id }));
}
TyAstNodeContent::Declaration(TyDecl::ConfigurableDecl(ConfigurableDecl {
decl_id,
..
})) => {
let decl = (*decl_engine.get_configurable(decl_id)).clone();
configurables.push(decl);
}
// ABI entries are all functions declared in impl_traits on the contract type
// itself, except for ABI supertraits, which do not expose their methods to
// the user
TyAstNodeContent::Declaration(TyDecl::ImplSelfOrTrait(ImplSelfOrTrait {
decl_id,
..
})) => {
let impl_trait_decl = decl_engine.get_impl_self_or_trait(decl_id);
let TyImplSelfOrTrait {
items,
implementing_for,
trait_decl_ref,
..
} = &*impl_trait_decl;
if matches!(
&*ty_engine.get(implementing_for.type_id),
TypeInfo::Contract
) {
// add methods to the ABI only if they come from an ABI implementation
// and not a (super)trait implementation for Contract
if let Some(trait_decl_ref) = trait_decl_ref {
if matches!(*trait_decl_ref.id(), InterfaceDeclId::Abi(_)) {
for item in items {
match item {
TyImplItem::Fn(method_ref) => {
abi_entries.push(*method_ref.id());
}
TyImplItem::Constant(const_ref) => {
declarations.push(TyDecl::ConstantDecl(ConstantDecl {
decl_id: *const_ref.id(),
}));
}
TyImplItem::Type(type_ref) => {
declarations.push(TyDecl::TraitTypeDecl(
TraitTypeDecl {
decl_id: *type_ref.id(),
},
));
}
}
}
}
}
}
}
// XXX we're excluding the above ABI methods, is that OK?
TyAstNodeContent::Declaration(decl) => {
declarations.push(decl.clone());
}
_ => {}
};
}
// Some checks that are specific to non-contracts
if kind != parsed::TreeType::Contract {
// impure functions are disallowed in non-contracts
if !matches!(kind, parsed::TreeType::Library) {
for err in disallow_impure_functions(decl_engine, &declarations, &entries) {
handler.emit_err(err);
}
}
// `storage` declarations are not allowed in non-contracts
let storage_decl = declarations
.iter()
.find(|decl| matches!(decl, TyDecl::StorageDecl { .. }));
if let Some(TyDecl::StorageDecl(StorageDecl { decl_id })) = storage_decl {
handler.emit_err(CompileError::StorageDeclarationInNonContract {
program_kind: format!("{kind}"),
span: engines.de().get(decl_id).span.clone(),
});
}
}
// Perform other validation based on the tree type.
let typed_program_kind = match kind {
parsed::TreeType::Contract => {
// Types containing raw_ptr are not allowed in storage (e.g Vec)
for decl in declarations.iter() {
if let TyDecl::StorageDecl(StorageDecl { decl_id }) = decl {
let storage_decl = decl_engine.get_storage(decl_id);
for field in storage_decl.fields.iter() {
if let Some(error) = get_type_not_allowed_error(
engines,
field.type_argument.type_id,
&field.type_argument,
|t| match t {
TypeInfo::StringSlice => {
Some(TypeNotAllowedReason::StringSliceInConfigurables)
}
TypeInfo::RawUntypedPtr => Some(
TypeNotAllowedReason::TypeNotAllowedInContractStorage {
ty: engines.help_out(t).to_string(),
},
),
_ => None,
},
) {
handler.emit_err(error);
}
}
}
}
TyProgramKind::Contract {
entry_function: if experimental.new_encoding {
if entries.len() != 1 {
return Err(handler.emit_err(CompileError::CouldNotGenerateEntry {
span: Span::dummy(),
}));
}
Some(entries[0])
} else {
None
},
abi_entries,
}
}
parsed::TreeType::Library => {
if !configurables.is_empty() {
handler.emit_err(CompileError::ConfigurableInLibrary {
span: configurables[0].call_path.suffix.span(),
});
}
TyProgramKind::Library {
name: package_name.to_string(),
}
}
parsed::TreeType::Predicate => {
if mains.is_empty() {
return Err(
handler.emit_err(CompileError::NoPredicateMainFunction(root.span.clone()))
);
}
if mains.len() > 1 {
let mut last_error = None;
for m in mains.iter().skip(1) {
let mains_last = decl_engine.get_function(m);
last_error = Some(handler.emit_err(
CompileError::MultipleDefinitionsOfFunction {
name: mains_last.name.clone(),
span: mains_last.name.span(),
},
));
}
return Err(last_error.unwrap());
}
// check if no ref mut arguments passed to a `main()` in a `script` or `predicate`.
check_no_ref_main(engines, handler, &mains[0]);
let (entry_fn_id, main_fn_id) = if experimental.new_encoding {
if entries.len() != 1 {
return Err(handler.emit_err(CompileError::CouldNotGenerateEntry {
span: Span::dummy(),
}));
}
(entries[0], mains[0])
} else {
assert!(entries.is_empty());
(mains[0], mains[0])
};
let main_fn = decl_engine.get(&main_fn_id);
if !ty_engine.get(main_fn.return_type.type_id).is_bool() {
handler.emit_err(CompileError::PredicateMainDoesNotReturnBool(
main_fn.span.clone(),
));
}
TyProgramKind::Predicate {
entry_function: entry_fn_id,
main_function: main_fn_id,
}
}
parsed::TreeType::Script => {
// A script must have exactly one main function
if mains.is_empty() {
return Err(
handler.emit_err(CompileError::NoScriptMainFunction(root.span.clone()))
);
}
if mains.len() > 1 {
let mut last_error = None;
for m in mains.iter().skip(1) {
let mains_last = decl_engine.get_function(m);
last_error = Some(handler.emit_err(
CompileError::MultipleDefinitionsOfFunction {
name: mains_last.name.clone(),
span: mains_last.name.span(),
},
));
}
return Err(last_error.unwrap());
}
// check if no ref mut arguments passed to a `main()` in a `script` or `predicate`.
check_no_ref_main(engines, handler, &mains[0]);
let (entry_fn_id, main_fn_id) = if experimental.new_encoding {
if entries.len() != 1 {
return Err(handler.emit_err(CompileError::CouldNotGenerateEntry {
span: Span::dummy(),
}));
}
(entries[0], mains[0])
} else {
assert!(entries.is_empty());
(mains[0], mains[0])
};
// On encoding v0, we cannot accept/return ptrs, slices etc...
if !experimental.new_encoding {
let main_fn = decl_engine.get(&main_fn_id);
for p in main_fn.parameters() {
if let Some(error) = get_type_not_allowed_error(
engines,
p.type_argument.type_id,
&p.type_argument,
|t| match t {
TypeInfo::StringSlice => {
Some(TypeNotAllowedReason::StringSliceInMainParameters)
}
TypeInfo::RawUntypedSlice => {
Some(TypeNotAllowedReason::NestedSliceReturnNotAllowedInMain)
}
_ => None,
},
) {
handler.emit_err(error);
}
}
// Check main return type is valid
if let Some(error) = get_type_not_allowed_error(
engines,
main_fn.return_type.type_id,
&main_fn.return_type,
|t| match t {
TypeInfo::StringSlice => {
Some(TypeNotAllowedReason::StringSliceInMainReturn)
}
TypeInfo::RawUntypedSlice => {
Some(TypeNotAllowedReason::NestedSliceReturnNotAllowedInMain)
}
_ => None,
},
) {
// Let main return `raw_slice` directly
if !matches!(
&*engines.te().get(main_fn.return_type.type_id),
TypeInfo::RawUntypedSlice
) {
handler.emit_err(error);
}
}
}
TyProgramKind::Script {
entry_function: entry_fn_id,
main_function: main_fn_id,
}
}
};
//configurables and constant cannot be str slice
for c in configurables.iter() {
if let Some(error) = get_type_not_allowed_error(
engines,
c.return_type,
&c.type_ascription,
|t| match t {
TypeInfo::StringSlice => Some(TypeNotAllowedReason::StringSliceInConfigurables),
TypeInfo::Slice(_) => Some(TypeNotAllowedReason::SliceInConst),
_ => None,
},
) {
handler.emit_err(error);
}
}
// verify all constants
for decl in root.iter_constants(decl_engine).iter() {
let decl = decl_engine.get_constant(&decl.decl_id);
let e =
get_type_not_allowed_error(engines, decl.return_type, &decl.type_ascription, |t| {
match t {
TypeInfo::StringSlice => Some(TypeNotAllowedReason::StringSliceInConst),
TypeInfo::Slice(_) => Some(TypeNotAllowedReason::SliceInConst),
_ => None,
}
});
if let Some(error) = e {
handler.emit_err(error);
}
}
Ok((typed_program_kind, declarations, configurables))
}
/// All test function declarations within the program.
pub fn test_fns<'a: 'b, 'b>(
&'b self,
decl_engine: &'a DeclEngine,
) -> impl 'b + Iterator<Item = (Arc<TyFunctionDecl>, DeclRefFunction)> {
self.root_module.test_fns_recursive(decl_engine)
}
pub fn check_deprecated(&self, engines: &Engines, handler: &Handler) {
let mut allow_deprecated = AllowDeprecatedState::default();
self.root_module
.check_deprecated(engines, handler, &mut allow_deprecated);
}
pub fn check_recursive(
&self,
engines: &Engines,
handler: &Handler,
) -> Result<(), ErrorEmitted> {
self.root_module.check_recursive(engines, handler)
}
}
impl CollectTypesMetadata for TyProgram {
/// Collect various type information such as unresolved types and types of logged data
fn collect_types_metadata(
&self,
handler: &Handler,
ctx: &mut CollectTypesMetadataContext,
) -> Result<Vec<TypeMetadata>, ErrorEmitted> {
let decl_engine = ctx.engines.de();
let mut metadata = vec![];
// First, look into all entry points that are not unit tests.
match &self.kind {
// For scripts and predicates, collect metadata for all the types starting with
// `main()` as the only entry point
TyProgramKind::Script {
entry_function: main_function,
..
}
| TyProgramKind::Predicate {
entry_function: main_function,
..
} => {
let main_function = decl_engine.get_function(main_function);
metadata.append(&mut main_function.collect_types_metadata(handler, ctx)?);
}
// For contracts, collect metadata for all the types starting with each ABI method as
// an entry point.
TyProgramKind::Contract {
abi_entries,
entry_function: main_function,
} => {
if let Some(main_function) = main_function {
let entry = decl_engine.get_function(main_function);
metadata.append(&mut entry.collect_types_metadata(handler, ctx)?);
}
for entry in abi_entries.iter() {
let entry = decl_engine.get_function(entry);
metadata.append(&mut entry.collect_types_metadata(handler, ctx)?);
}
}
// For libraries, collect metadata for all the types starting with each `pub` node as
// an entry point. Also dig into all the submodules of a library because nodes in those
// submodules can also be entry points.
TyProgramKind::Library { .. } => {
for module in std::iter::once(&self.root_module).chain(
self.root_module
.submodules_recursive()
.map(|(_, submod)| &*submod.module),
) {
for node in module.all_nodes.iter() {
let is_generic_function = node.is_generic_function(decl_engine);
if node.is_public(decl_engine) {
let node_metadata = node.collect_types_metadata(handler, ctx)?;
metadata.append(
&mut node_metadata
.iter()
.filter(|m| {
// Generic functions are allowed to have unresolved types
// so filter those
!(is_generic_function
&& matches!(m, TypeMetadata::UnresolvedType(..)))
})
.cloned()
.collect::<Vec<TypeMetadata>>(),
);
}
}
}
}
}
// Now consider unit tests: all unit test are considered entry points regardless of the
// program type
for module in std::iter::once(&self.root_module).chain(
self.root_module
.submodules_recursive()
.map(|(_, submod)| &*submod.module),
) {
for node in module.all_nodes.iter() {
if node.is_test_function(decl_engine) {
metadata.append(&mut node.collect_types_metadata(handler, ctx)?);
}
}
}
Ok(metadata)
}
}
#[derive(Clone, Debug)]
pub enum TyProgramKind {
Contract {
entry_function: Option<DeclId<TyFunctionDecl>>,
abi_entries: Vec<DeclId<TyFunctionDecl>>,
},
Library {
name: String,
},
Predicate {
entry_function: DeclId<TyFunctionDecl>,
main_function: DeclId<TyFunctionDecl>,
},
Script {
entry_function: DeclId<TyFunctionDecl>,
main_function: DeclId<TyFunctionDecl>,
},
}
impl TyProgramKind {
/// The parse tree type associated with this program kind.
pub fn tree_type(&self) -> parsed::TreeType {
match self {
TyProgramKind::Contract { .. } => parsed::TreeType::Contract,
TyProgramKind::Library { .. } => parsed::TreeType::Library,
TyProgramKind::Predicate { .. } => parsed::TreeType::Predicate,
TyProgramKind::Script { .. } => parsed::TreeType::Script,
}
}
/// Used for project titles in `forc doc`.
pub fn as_title_str(&self) -> &str {
match self {
TyProgramKind::Contract { .. } => "Contract",
TyProgramKind::Library { .. } => "Library",
TyProgramKind::Predicate { .. } => "Predicate",
TyProgramKind::Script { .. } => "Script",
}
}
}
fn disallow_impure_functions(
decl_engine: &DeclEngine,
declarations: &[TyDecl],
mains: &[DeclId<TyFunctionDecl>],
) -> Vec<CompileError> {
let mut errs: Vec<CompileError> = vec![];
let fn_decls = declarations
.iter()
.filter_map(|decl| match decl {
TyDecl::FunctionDecl(FunctionDecl { decl_id, .. }) => Some(*decl_id),
_ => None,
})
.chain(mains.to_owned());
let mut err_purity = fn_decls
.filter_map(|decl_id| {
let fn_decl = decl_engine.get_function(&decl_id);
let TyFunctionDecl { purity, name, .. } = &*fn_decl;
if *purity != Purity::Pure {
Some(CompileError::ImpureInNonContract { span: name.span() })
} else {
None
}
})
.collect::<Vec<_>>();
errs.append(&mut err_purity);
errs
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/module.rs | sway-core/src/language/ty/module.rs | use std::sync::Arc;
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::Span;
use crate::{
decl_engine::{DeclEngine, DeclEngineGet, DeclId, DeclRef, DeclRefFunction},
language::{ty::*, HasModule, HasSubmodules, ModName},
transform::{self, AllowDeprecatedState},
Engines,
};
#[derive(Clone, Debug)]
pub struct TyModule {
pub span: Span,
pub submodules: Vec<(ModName, TySubmodule)>,
pub all_nodes: Vec<TyAstNode>,
pub attributes: transform::Attributes,
}
impl TyModule {
/// Iter on all constants in this module, which means, globals constants and
/// local constants, but it does not enter into submodules.
pub fn iter_constants(&self, de: &DeclEngine) -> Vec<ConstantDecl> {
fn inside_code_block(de: &DeclEngine, block: &TyCodeBlock) -> Vec<ConstantDecl> {
block
.contents
.iter()
.flat_map(|node| inside_ast_node(de, node))
.collect::<Vec<_>>()
}
fn inside_ast_node(de: &DeclEngine, node: &TyAstNode) -> Vec<ConstantDecl> {
match &node.content {
TyAstNodeContent::Declaration(decl) => match decl {
TyDecl::ConstantDecl(decl) => {
vec![decl.clone()]
}
TyDecl::FunctionDecl(decl) => {
let decl = de.get(&decl.decl_id);
inside_code_block(de, &decl.body)
}
TyDecl::ImplSelfOrTrait(decl) => {
let decl = de.get(&decl.decl_id);
decl.items
.iter()
.flat_map(|item| match item {
TyTraitItem::Fn(decl) => {
let decl = de.get(decl.id());
inside_code_block(de, &decl.body)
}
TyTraitItem::Constant(decl) => {
vec![ConstantDecl {
decl_id: *decl.id(),
}]
}
_ => vec![],
})
.collect()
}
_ => vec![],
},
_ => vec![],
}
}
self.all_nodes
.iter()
.flat_map(|node| inside_ast_node(de, node))
.collect::<Vec<_>>()
}
/// Recursively find all test function declarations.
pub fn test_fns_recursive<'a: 'b, 'b>(
&'b self,
decl_engine: &'a DeclEngine,
) -> impl 'b + Iterator<Item = (Arc<TyFunctionDecl>, DeclRefFunction)> {
self.submodules_recursive()
.flat_map(|(_, submod)| submod.module.test_fns(decl_engine))
.chain(self.test_fns(decl_engine))
}
}
#[derive(Clone, Debug)]
pub struct TySubmodule {
pub module: Arc<TyModule>,
pub mod_name_span: Span,
}
/// Iterator type for iterating over submodules.
///
/// Used rather than `impl Iterator` to enable recursive submodule iteration.
pub struct SubmodulesRecursive<'module> {
submods: std::slice::Iter<'module, (ModName, TySubmodule)>,
current: Option<(
&'module (ModName, TySubmodule),
Box<SubmodulesRecursive<'module>>,
)>,
}
impl TyModule {
/// An iterator yielding all submodules recursively, depth-first.
pub fn submodules_recursive(&self) -> SubmodulesRecursive {
SubmodulesRecursive {
submods: self.submodules.iter(),
current: None,
}
}
/// All test functions within this module.
pub fn test_fns<'a: 'b, 'b>(
&'b self,
decl_engine: &'a DeclEngine,
) -> impl 'b + Iterator<Item = (Arc<TyFunctionDecl>, DeclRefFunction)> {
self.all_nodes.iter().filter_map(|node| {
if let TyAstNodeContent::Declaration(TyDecl::FunctionDecl(FunctionDecl { decl_id })) =
&node.content
{
let fn_decl = decl_engine.get_function(decl_id);
let name = fn_decl.name.clone();
let span = fn_decl.span.clone();
if fn_decl.is_test() {
return Some((fn_decl, DeclRef::new(name, *decl_id, span)));
}
}
None
})
}
/// All contract functions within this module.
pub fn contract_fns<'a: 'b, 'b>(
&'b self,
engines: &'a Engines,
) -> impl 'b + Iterator<Item = DeclId<TyFunctionDecl>> {
self.all_nodes
.iter()
.flat_map(move |node| node.contract_fns(engines))
}
/// All contract supertrait functions within this module.
pub fn contract_supertrait_fns<'a: 'b, 'b>(
&'b self,
engines: &'a Engines,
) -> impl 'b + Iterator<Item = DeclId<TyFunctionDecl>> {
self.all_nodes
.iter()
.flat_map(move |node| node.contract_supertrait_fns(engines))
}
pub(crate) fn check_deprecated(
&self,
engines: &Engines,
handler: &Handler,
allow_deprecated: &mut AllowDeprecatedState,
) {
for (_, submodule) in self.submodules.iter() {
submodule
.module
.check_deprecated(engines, handler, allow_deprecated);
}
for node in self.all_nodes.iter() {
node.check_deprecated(engines, handler, allow_deprecated);
}
}
pub(crate) fn check_recursive(
&self,
engines: &Engines,
handler: &Handler,
) -> Result<(), ErrorEmitted> {
handler.scope(|handler| {
for (_, submodule) in self.submodules.iter() {
let _ = submodule.module.check_recursive(engines, handler);
}
for node in self.all_nodes.iter() {
let _ = node.check_recursive(engines, handler);
}
Ok(())
})
}
}
impl<'module> Iterator for SubmodulesRecursive<'module> {
type Item = &'module (ModName, TySubmodule);
fn next(&mut self) -> Option<Self::Item> {
loop {
self.current = match self.current.take() {
None => match self.submods.next() {
None => return None,
Some(submod) => {
Some((submod, Box::new(submod.1.module.submodules_recursive())))
}
},
Some((submod, mut submods)) => match submods.next() {
Some(next) => {
self.current = Some((submod, submods));
return Some(next);
}
None => return Some(submod),
},
}
}
}
}
impl HasModule<TyModule> for TySubmodule {
fn module(&self) -> &TyModule {
&self.module
}
}
impl HasSubmodules<TySubmodule> for TyModule {
fn submodules(&self) -> &[(ModName, TySubmodule)] {
&self.submodules
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/variable_mutability.rs | sway-core/src/language/ty/variable_mutability.rs | use crate::language::Visibility;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub enum VariableMutability {
// mutable
Mutable,
// referenceable + mutable
RefMutable,
// immutable
#[default]
Immutable,
}
impl VariableMutability {
pub fn new_from_ref_mut(is_reference: bool, is_mutable: bool) -> VariableMutability {
if is_reference {
VariableMutability::RefMutable
} else if is_mutable {
VariableMutability::Mutable
} else {
VariableMutability::Immutable
}
}
pub fn is_mutable(&self) -> bool {
matches!(
self,
VariableMutability::Mutable | VariableMutability::RefMutable
)
}
pub fn visibility(&self) -> Visibility {
Visibility::Private
}
pub fn is_immutable(&self) -> bool {
!self.is_mutable()
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/mod.rs | sway-core/src/language/ty/mod.rs | mod ast_node;
mod code_block;
mod declaration;
mod expression;
mod module;
mod program;
mod side_effect;
mod variable_mutability;
pub use ast_node::*;
pub use code_block::*;
pub use declaration::*;
pub use expression::*;
pub use module::*;
pub use program::*;
pub use side_effect::*;
pub use variable_mutability::*;
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/code_block.rs | sway-core/src/language/ty/code_block.rs | use crate::{
decl_engine::*, engine_threading::*, language::ty::*, semantic_analysis::TypeCheckContext,
transform::AllowDeprecatedState, type_system::*,
};
use serde::{Deserialize, Serialize};
use std::hash::Hasher;
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::Span;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyCodeBlock {
pub contents: Vec<TyAstNode>,
pub(crate) whole_block_span: Span,
}
impl TyCodeBlock {
pub(crate) fn check_deprecated(
&self,
engines: &Engines,
handler: &Handler,
allow_deprecated: &mut AllowDeprecatedState,
) {
for n in self.contents.iter() {
n.check_deprecated(engines, handler, allow_deprecated);
}
}
}
impl Default for TyCodeBlock {
fn default() -> Self {
Self {
contents: Default::default(),
whole_block_span: Span::dummy(),
}
}
}
impl EqWithEngines for TyCodeBlock {}
impl PartialEqWithEngines for TyCodeBlock {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.contents.eq(&other.contents, ctx)
}
}
impl HashWithEngines for TyCodeBlock {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyCodeBlock { contents, .. } = self;
contents.hash(state, engines);
}
}
impl SubstTypes for TyCodeBlock {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
self.contents.subst(ctx)
}
}
impl ReplaceDecls for TyCodeBlock {
fn replace_decls_inner(
&mut self,
decl_mapping: &DeclMapping,
handler: &Handler,
ctx: &mut TypeCheckContext,
) -> Result<bool, ErrorEmitted> {
handler.scope(|handler| {
let mut has_changes = false;
for node in self.contents.iter_mut() {
if let Ok(r) = node.replace_decls(decl_mapping, handler, ctx) {
has_changes |= r;
}
}
Ok(has_changes)
})
}
}
impl UpdateConstantExpression for TyCodeBlock {
fn update_constant_expression(&mut self, engines: &Engines, implementing_type: &TyDecl) {
self.contents
.iter_mut()
.for_each(|x| x.update_constant_expression(engines, implementing_type));
}
}
impl MaterializeConstGenerics for TyCodeBlock {
fn materialize_const_generics(
&mut self,
engines: &Engines,
handler: &Handler,
name: &str,
value: &TyExpression,
) -> Result<(), ErrorEmitted> {
self.contents
.iter_mut()
.try_for_each(|x| x.materialize_const_generics(engines, handler, name, value))
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/ast_node.rs | sway-core/src/language/ty/ast_node.rs | use crate::{
decl_engine::*,
engine_threading::*,
language::ty::*,
semantic_analysis::{
TypeCheckAnalysis, TypeCheckAnalysisContext, TypeCheckContext, TypeCheckFinalization,
TypeCheckFinalizationContext,
},
transform::{AllowDeprecatedState, AttributeKind},
type_system::*,
types::*,
};
use serde::{Deserialize, Serialize};
use std::{
fmt::{self, Debug},
hash::{Hash, Hasher},
};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::{Ident, Span};
pub trait GetDeclIdent {
fn get_decl_ident(&self, engines: &Engines) -> Option<Ident>;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyAstNode {
pub content: TyAstNodeContent,
pub span: Span,
}
impl EqWithEngines for TyAstNode {}
impl PartialEqWithEngines for TyAstNode {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.content.eq(&other.content, ctx)
}
}
impl HashWithEngines for TyAstNode {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyAstNode {
content,
// the span is not hashed because it isn't relevant/a reliable
// source of obj v. obj distinction
span: _,
} = self;
content.hash(state, engines);
}
}
impl DebugWithEngines for TyAstNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
use TyAstNodeContent::*;
match &self.content {
Declaration(typed_decl) => DebugWithEngines::fmt(typed_decl, f, engines),
Expression(exp) => DebugWithEngines::fmt(exp, f, engines),
SideEffect(_) => f.write_str(""),
Error(_, _) => f.write_str("error"),
}
}
}
impl SubstTypes for TyAstNode {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
match self.content {
TyAstNodeContent::Declaration(ref mut decl) => decl.subst(ctx),
TyAstNodeContent::Expression(ref mut expr) => expr.subst(ctx),
TyAstNodeContent::SideEffect(_) | TyAstNodeContent::Error(_, _) => HasChanges::No,
}
}
}
impl ReplaceDecls for TyAstNode {
fn replace_decls_inner(
&mut self,
decl_mapping: &DeclMapping,
handler: &Handler,
ctx: &mut TypeCheckContext,
) -> Result<bool, ErrorEmitted> {
match self.content {
TyAstNodeContent::Declaration(TyDecl::VariableDecl(ref mut decl)) => {
decl.body.replace_decls(decl_mapping, handler, ctx)
}
TyAstNodeContent::Declaration(_) => Ok(false),
TyAstNodeContent::Expression(ref mut expr) => {
expr.replace_decls(decl_mapping, handler, ctx)
}
TyAstNodeContent::SideEffect(_) => Ok(false),
TyAstNodeContent::Error(_, _) => Ok(false),
}
}
}
impl UpdateConstantExpression for TyAstNode {
fn update_constant_expression(&mut self, engines: &Engines, implementing_type: &TyDecl) {
match self.content {
TyAstNodeContent::Declaration(_) => {}
TyAstNodeContent::Expression(ref mut expr) => {
expr.update_constant_expression(engines, implementing_type)
}
TyAstNodeContent::SideEffect(_) => (),
TyAstNodeContent::Error(_, _) => (),
}
}
}
impl TypeCheckAnalysis for TyAstNode {
fn type_check_analyze(
&self,
handler: &Handler,
ctx: &mut TypeCheckAnalysisContext,
) -> Result<(), ErrorEmitted> {
self.content.type_check_analyze(handler, ctx)
}
}
impl TypeCheckFinalization for TyAstNode {
fn type_check_finalize(
&mut self,
handler: &Handler,
ctx: &mut TypeCheckFinalizationContext,
) -> Result<(), ErrorEmitted> {
self.content.type_check_finalize(handler, ctx)
}
}
impl CollectTypesMetadata for TyAstNode {
fn collect_types_metadata(
&self,
handler: &Handler,
ctx: &mut CollectTypesMetadataContext,
) -> Result<Vec<TypeMetadata>, ErrorEmitted> {
self.content.collect_types_metadata(handler, ctx)
}
}
impl GetDeclIdent for TyAstNode {
fn get_decl_ident(&self, engines: &Engines) -> Option<Ident> {
self.content.get_decl_ident(engines)
}
}
impl MaterializeConstGenerics for TyAstNode {
fn materialize_const_generics(
&mut self,
engines: &Engines,
handler: &Handler,
name: &str,
value: &TyExpression,
) -> Result<(), ErrorEmitted> {
match &mut self.content {
TyAstNodeContent::Declaration(TyDecl::ConstantDecl(constant_decl)) => {
let decl = engines.de().get(&constant_decl.decl_id);
let mut decl = TyConstantDecl::clone(&*decl);
decl.materialize_const_generics(engines, handler, name, value)?;
let r = engines.de().insert(decl, None);
*constant_decl = ConstantDecl { decl_id: *r.id() };
Ok(())
}
TyAstNodeContent::Declaration(TyDecl::VariableDecl(decl)) => {
decl.body
.materialize_const_generics(engines, handler, name, value)?;
decl.return_type
.materialize_const_generics(engines, handler, name, value)?;
decl.type_ascription
.type_id
.materialize_const_generics(engines, handler, name, value)?;
Ok(())
}
TyAstNodeContent::Expression(expr) => {
expr.materialize_const_generics(engines, handler, name, value)
}
_ => Ok(()),
}
}
}
impl TyAstNode {
/// Returns `true` if this AST node will be exported in a library, i.e. it is a public declaration.
pub(crate) fn is_public(&self, decl_engine: &DeclEngine) -> bool {
match &self.content {
TyAstNodeContent::Declaration(decl) => decl.visibility(decl_engine).is_public(),
TyAstNodeContent::Expression(_)
| TyAstNodeContent::SideEffect(_)
| TyAstNodeContent::Error(_, _) => false,
}
}
/// Check to see if this node is a function declaration with generic type parameters.
pub(crate) fn is_generic_function(&self, decl_engine: &DeclEngine) -> bool {
match &self {
TyAstNode {
span: _,
content:
TyAstNodeContent::Declaration(TyDecl::FunctionDecl(FunctionDecl {
decl_id, ..
})),
..
} => {
let fn_decl = decl_engine.get_function(decl_id);
let TyFunctionDecl {
type_parameters, ..
} = &*fn_decl;
!type_parameters.is_empty()
}
_ => false,
}
}
/// Check to see if this node is a function declaration of a function annotated as test.
pub(crate) fn is_test_function(&self, decl_engine: &DeclEngine) -> bool {
match &self {
TyAstNode {
span: _,
content:
TyAstNodeContent::Declaration(TyDecl::FunctionDecl(FunctionDecl {
decl_id, ..
})),
..
} => {
let fn_decl = decl_engine.get_function(decl_id);
let TyFunctionDecl { attributes, .. } = &*fn_decl;
attributes.has_any_of_kind(AttributeKind::Test)
}
_ => false,
}
}
pub(crate) fn type_info(&self, type_engine: &TypeEngine) -> TypeInfo {
// return statement should be ()
match &self.content {
TyAstNodeContent::Declaration(_) => TypeInfo::Tuple(Vec::new()),
TyAstNodeContent::Expression(TyExpression { return_type, .. }) => {
(*type_engine.get(*return_type)).clone()
}
TyAstNodeContent::SideEffect(_) => TypeInfo::Tuple(Vec::new()),
TyAstNodeContent::Error(_, error) => TypeInfo::ErrorRecovery(*error),
}
}
pub(crate) fn check_deprecated(
&self,
engines: &Engines,
handler: &Handler,
allow_deprecated: &mut AllowDeprecatedState,
) {
match &self.content {
TyAstNodeContent::Declaration(node) => match node {
TyDecl::VariableDecl(decl) => {
decl.body
.check_deprecated(engines, handler, allow_deprecated);
}
TyDecl::ConstantDecl(decl) => {
let decl = engines.de().get(&decl.decl_id);
if let Some(value) = &decl.value {
value.check_deprecated(engines, handler, allow_deprecated);
}
}
TyDecl::ConfigurableDecl(decl) => {
let decl = engines.de().get(&decl.decl_id);
if let Some(value) = &decl.value {
value.check_deprecated(engines, handler, allow_deprecated);
}
}
TyDecl::ConstGenericDecl(_) => {
unreachable!("ConstGenericDecl is not reachable from AstNode")
}
TyDecl::TraitTypeDecl(_) => {}
TyDecl::FunctionDecl(decl) => {
let decl = engines.de().get(&decl.decl_id);
let token = allow_deprecated.enter(decl.attributes.clone());
for node in decl.body.contents.iter() {
node.check_deprecated(engines, handler, allow_deprecated);
}
allow_deprecated.exit(token);
}
TyDecl::ImplSelfOrTrait(decl) => {
let decl = engines.de().get(&decl.decl_id);
for item in decl.items.iter() {
match item {
TyTraitItem::Fn(item) => {
let decl = engines.de().get(item.id());
let token = allow_deprecated.enter(decl.attributes.clone());
for node in decl.body.contents.iter() {
node.check_deprecated(engines, handler, allow_deprecated);
}
allow_deprecated.exit(token);
}
TyTraitItem::Constant(item) => {
let decl = engines.de().get(item.id());
if let Some(expr) = decl.value.as_ref() {
expr.check_deprecated(engines, handler, allow_deprecated);
}
}
TyTraitItem::Type(_) => {}
}
}
}
TyDecl::AbiDecl(_)
| TyDecl::GenericTypeForFunctionScope(_)
| TyDecl::ErrorRecovery(_, _)
| TyDecl::StorageDecl(_)
| TyDecl::TraitDecl(_)
| TyDecl::StructDecl(_)
| TyDecl::EnumDecl(_)
| TyDecl::EnumVariantDecl(_)
| TyDecl::TypeAliasDecl(_) => {}
},
TyAstNodeContent::Expression(node) => {
node.check_deprecated(engines, handler, allow_deprecated);
}
TyAstNodeContent::SideEffect(_) | TyAstNodeContent::Error(_, _) => {}
}
}
pub(crate) fn check_recursive(
&self,
engines: &Engines,
handler: &Handler,
) -> Result<(), ErrorEmitted> {
handler.scope(|handler| {
match &self.content {
TyAstNodeContent::Declaration(node) => match node {
TyDecl::VariableDecl(_decl) => {}
TyDecl::ConstantDecl(_decl) => {}
TyDecl::ConfigurableDecl(_decl) => {}
TyDecl::ConstGenericDecl(_decl) => {
unreachable!("ConstGenericDecl is not reachable from AstNode")
}
TyDecl::TraitTypeDecl(_) => {}
TyDecl::FunctionDecl(decl) => {
let fn_decl_id = decl.decl_id;
let mut ctx = TypeCheckAnalysisContext::new(engines);
let _ = fn_decl_id.type_check_analyze(handler, &mut ctx);
let _ = ctx.check_recursive_calls(handler);
}
TyDecl::ImplSelfOrTrait(decl) => {
let decl = engines.de().get(&decl.decl_id);
for item in decl.items.iter() {
let mut ctx = TypeCheckAnalysisContext::new(engines);
let _ = item.type_check_analyze(handler, &mut ctx);
let _ = ctx.check_recursive_calls(handler);
}
}
TyDecl::AbiDecl(_)
| TyDecl::GenericTypeForFunctionScope(_)
| TyDecl::ErrorRecovery(_, _)
| TyDecl::StorageDecl(_)
| TyDecl::TraitDecl(_)
| TyDecl::StructDecl(_)
| TyDecl::EnumDecl(_)
| TyDecl::EnumVariantDecl(_)
| TyDecl::TypeAliasDecl(_) => {}
},
TyAstNodeContent::Expression(_node) => {}
TyAstNodeContent::SideEffect(_) | TyAstNodeContent::Error(_, _) => {}
};
Ok(())
})
}
pub fn contract_supertrait_fns(&self, engines: &Engines) -> Vec<DeclId<TyFunctionDecl>> {
let mut fns = vec![];
if let TyAstNodeContent::Declaration(TyDecl::ImplSelfOrTrait(decl)) = &self.content {
let decl = engines.de().get(&decl.decl_id);
if decl.is_impl_contract(engines.te()) {
for item in &decl.supertrait_items {
if let TyTraitItem::Fn(f) = item {
fns.push(*f.id());
}
}
}
}
fns
}
pub fn contract_fns(&self, engines: &Engines) -> Vec<DeclId<TyFunctionDecl>> {
let mut fns = vec![];
if let TyAstNodeContent::Declaration(TyDecl::ImplSelfOrTrait(decl)) = &self.content {
let decl = engines.de().get(&decl.decl_id);
if decl.is_impl_contract(engines.te()) {
for item in &decl.items {
if let TyTraitItem::Fn(f) = item {
fns.push(*f.id());
}
}
}
}
fns
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[allow(clippy::large_enum_variant)]
pub enum TyAstNodeContent {
Declaration(TyDecl),
Expression(TyExpression),
// a no-op node used for something that just issues a side effect, like an import statement.
SideEffect(TySideEffect),
Error(Box<[Span]>, #[serde(skip)] ErrorEmitted),
}
impl EqWithEngines for TyAstNodeContent {}
impl PartialEqWithEngines for TyAstNodeContent {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(Self::Declaration(x), Self::Declaration(y)) => x.eq(y, ctx),
(Self::Expression(x), Self::Expression(y)) => x.eq(y, ctx),
(Self::SideEffect(_), Self::SideEffect(_)) => true,
_ => false,
}
}
}
impl HashWithEngines for TyAstNodeContent {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
use TyAstNodeContent::*;
std::mem::discriminant(self).hash(state);
match self {
Declaration(decl) => {
decl.hash(state, engines);
}
Expression(exp) => {
exp.hash(state, engines);
}
SideEffect(effect) => {
effect.hash(state);
}
Error(_, _) => {}
}
}
}
impl TypeCheckAnalysis for TyAstNodeContent {
fn type_check_analyze(
&self,
handler: &Handler,
ctx: &mut TypeCheckAnalysisContext,
) -> Result<(), ErrorEmitted> {
match self {
TyAstNodeContent::Declaration(node) => node.type_check_analyze(handler, ctx)?,
TyAstNodeContent::Expression(node) => node.type_check_analyze(handler, ctx)?,
TyAstNodeContent::SideEffect(_) => {}
TyAstNodeContent::Error(_, _) => {}
}
Ok(())
}
}
impl TypeCheckFinalization for TyAstNodeContent {
fn type_check_finalize(
&mut self,
handler: &Handler,
ctx: &mut TypeCheckFinalizationContext,
) -> Result<(), ErrorEmitted> {
match self {
TyAstNodeContent::Declaration(node) => node.type_check_finalize(handler, ctx)?,
TyAstNodeContent::Expression(node) => node.type_check_finalize(handler, ctx)?,
TyAstNodeContent::SideEffect(_) => {}
TyAstNodeContent::Error(_, _) => {}
}
Ok(())
}
}
impl CollectTypesMetadata for TyAstNodeContent {
fn collect_types_metadata(
&self,
handler: &Handler,
ctx: &mut CollectTypesMetadataContext,
) -> Result<Vec<TypeMetadata>, ErrorEmitted> {
use TyAstNodeContent::*;
match self {
Declaration(decl) => decl.collect_types_metadata(handler, ctx),
Expression(expr) => expr.collect_types_metadata(handler, ctx),
SideEffect(_) => Ok(vec![]),
Error(_, _) => Ok(vec![]),
}
}
}
impl GetDeclIdent for TyAstNodeContent {
fn get_decl_ident(&self, engines: &Engines) -> Option<Ident> {
match self {
TyAstNodeContent::Declaration(decl) => decl.get_decl_ident(engines),
TyAstNodeContent::Expression(_expr) => None, //expr.get_decl_ident(),
TyAstNodeContent::SideEffect(_) => None,
TyAstNodeContent::Error(_, _) => None,
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/side_effect/mod.rs | sway-core/src/language/ty/side_effect/mod.rs | mod include_statement;
#[allow(clippy::module_inception)]
mod side_effect;
mod use_statement;
pub use include_statement::*;
pub use side_effect::*;
pub use use_statement::*;
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/side_effect/include_statement.rs | sway-core/src/language/ty/side_effect/include_statement.rs | use crate::language::Visibility;
use serde::{Deserialize, Serialize};
use sway_types::{ident::Ident, Span, Spanned};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TyIncludeStatement {
pub span: Span,
pub visibility: Visibility,
pub mod_name: Ident,
}
impl Spanned for TyIncludeStatement {
fn span(&self) -> Span {
self.span.clone()
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/side_effect/use_statement.rs | sway-core/src/language/ty/side_effect/use_statement.rs | use crate::language::parsed;
use serde::{Deserialize, Serialize};
use sway_types::{ident::Ident, Span, Spanned};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TyUseStatement {
pub call_path: Vec<Ident>,
pub span: Span,
pub import_type: parsed::ImportType,
// If `is_relative_to_package_root` is true, then this use statement is a path relative to the
// project root. For example, if the path is `::X::Y` and occurs in package `P`, then the path
// refers to the full path `P::X::Y`.
// If `is_relative_to_package_root` is false, then there are two options:
// - The path refers to a path relative to the current namespace. For example, if the path is
// `X::Y` and it occurs in a module whose path is `P::M`, then the path refers to the full
// path `P::M::X::Y`.
// - The path refers to a path in an external package. For example, the path `X::Y` refers to an
// entity `Y` in the external package `X`.
pub is_relative_to_package_root: bool,
pub alias: Option<Ident>,
}
impl Spanned for TyUseStatement {
fn span(&self) -> Span {
self.span.clone()
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/side_effect/side_effect.rs | sway-core/src/language/ty/side_effect/side_effect.rs | use super::{TyIncludeStatement, TyUseStatement};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TySideEffect {
pub side_effect: TySideEffectVariant,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TySideEffectVariant {
IncludeStatement(TyIncludeStatement),
UseStatement(TyUseStatement),
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/struct.rs | sway-core/src/language/ty/declaration/struct.rs | use crate::{
ast_elements::type_argument::GenericTypeArgument,
decl_engine::MaterializeConstGenerics,
engine_threading::*,
error::module_can_be_changed,
has_changes,
language::{
parsed::StructDeclaration, ty::TyDeclParsedType, CallPath, CallPathType, Visibility,
},
transform,
type_system::*,
Namespace,
};
use ast_elements::type_parameter::ConstGenericExpr;
use monomorphization::MonomorphizeHelper;
use serde::{Deserialize, Serialize};
use std::{
cmp::Ordering,
hash::{Hash, Hasher},
};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyStructDecl {
pub call_path: CallPath,
pub fields: Vec<TyStructField>,
pub generic_parameters: Vec<TypeParameter>,
pub visibility: Visibility,
pub span: Span,
pub attributes: transform::Attributes,
}
impl TyDeclParsedType for TyStructDecl {
type ParsedType = StructDeclaration;
}
impl Named for TyStructDecl {
fn name(&self) -> &Ident {
&self.call_path.suffix
}
}
impl EqWithEngines for TyStructDecl {}
impl PartialEqWithEngines for TyStructDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.call_path == other.call_path
&& self.fields.eq(&other.fields, ctx)
&& self.generic_parameters.eq(&other.generic_parameters, ctx)
&& self.visibility == other.visibility
}
}
impl HashWithEngines for TyStructDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyStructDecl {
call_path,
fields,
generic_parameters: type_parameters,
visibility,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
attributes: _,
} = self;
call_path.hash(state);
fields.hash(state, engines);
type_parameters.hash(state, engines);
visibility.hash(state);
}
}
impl SubstTypes for TyStructDecl {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
self.fields.subst(ctx);
self.generic_parameters.subst(ctx);
}
}
}
impl Spanned for TyStructDecl {
fn span(&self) -> Span {
self.span.clone()
}
}
impl MonomorphizeHelper for TyStructDecl {
fn type_parameters(&self) -> &[TypeParameter] {
&self.generic_parameters
}
fn name(&self) -> &Ident {
&self.call_path.suffix
}
fn has_self_type_param(&self) -> bool {
false
}
}
impl MaterializeConstGenerics for TyStructDecl {
fn materialize_const_generics(
&mut self,
engines: &Engines,
handler: &Handler,
name: &str,
value: &crate::language::ty::TyExpression,
) -> Result<(), ErrorEmitted> {
for p in self.generic_parameters.iter_mut() {
match p {
TypeParameter::Const(p) if p.name.as_str() == name => {
p.expr = Some(ConstGenericExpr::from_ty_expression(handler, value)?);
}
_ => {}
}
}
for field in self.fields.iter_mut() {
field
.type_argument
.type_id
.materialize_const_generics(engines, handler, name, value)?;
}
Ok(())
}
}
impl TyStructDecl {
/// Returns names of the [TyStructField]s of the struct `self` accessible in the given context.
/// If `is_public_struct_access` is true, only the names of the public fields are returned, otherwise
/// the names of all fields.
/// Suitable for error reporting.
pub(crate) fn accessible_fields_names(&self, is_public_struct_access: bool) -> Vec<Ident> {
TyStructField::accessible_fields_names(&self.fields, is_public_struct_access)
}
/// Returns [TyStructField] with the given `field_name`, or `None` if the field with the
/// name `field_name` does not exist.
pub(crate) fn find_field(&self, field_name: &Ident) -> Option<&TyStructField> {
self.fields.iter().find(|field| field.name == *field_name)
}
/// For the given `field_name` returns the zero-based index and the type of the field
/// within the struct memory layout, or `None` if the field with the
/// name `field_name` does not exist.
pub(crate) fn get_field_index_and_type(&self, field_name: &Ident) -> Option<(u64, TypeId)> {
// TODO-MEMLAY: Warning! This implementation assumes that fields are laid out in
// memory in the order of their declaration.
// This assumption can be changed in the future.
self.fields
.iter()
.enumerate()
.find(|(_, field)| field.name == *field_name)
.map(|(idx, field)| (idx as u64, field.type_argument.type_id))
}
/// Returns true if the struct `self` has at least one private field.
pub(crate) fn has_private_fields(&self) -> bool {
self.fields.iter().any(|field| field.is_private())
}
/// Returns true if the struct `self` has fields (it is not empty)
/// and all fields are private.
pub(crate) fn has_only_private_fields(&self) -> bool {
!self.is_empty() && self.fields.iter().all(|field| field.is_private())
}
/// Returns true if the struct `self` does not have any fields.
pub(crate) fn is_empty(&self) -> bool {
self.fields.is_empty()
}
}
/// Provides information about the struct access within a particular [Namespace].
pub struct StructAccessInfo {
/// True if the programmer who can change the code in the [Namespace]
/// can also change the struct declaration.
struct_can_be_changed: bool,
/// True if the struct access is public, i.e., outside of the module in
/// which the struct is defined.
is_public_struct_access: bool,
}
impl StructAccessInfo {
pub fn get_info(engines: &Engines, struct_decl: &TyStructDecl, namespace: &Namespace) -> Self {
assert!(
matches!(struct_decl.call_path.callpath_type, CallPathType::Full),
"The call path of the struct declaration must always be fully resolved."
);
let struct_can_be_changed =
module_can_be_changed(engines, namespace, &struct_decl.call_path.prefixes);
let is_public_struct_access =
!namespace.module_is_submodule_of(&struct_decl.call_path.prefixes, true);
Self {
struct_can_be_changed,
is_public_struct_access,
}
}
}
impl From<StructAccessInfo> for (bool, bool) {
/// Deconstructs `struct_access_info` into (`struct_can_be_changed`, `is_public_struct_access`)
fn from(struct_access_info: StructAccessInfo) -> (bool, bool) {
let StructAccessInfo {
struct_can_be_changed,
is_public_struct_access,
} = struct_access_info;
(struct_can_be_changed, is_public_struct_access)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TyStructField {
pub visibility: Visibility,
pub name: Ident,
pub span: Span,
pub type_argument: GenericTypeArgument,
pub attributes: transform::Attributes,
}
impl TyStructField {
pub fn is_private(&self) -> bool {
matches!(self.visibility, Visibility::Private)
}
pub fn is_public(&self) -> bool {
matches!(self.visibility, Visibility::Public)
}
/// Returns [TyStructField]s from the `fields` that are accessible in the given context.
/// If `is_public_struct_access` is true, only public fields are returned, otherwise
/// all fields.
pub(crate) fn accessible_fields(
fields: &[TyStructField],
is_public_struct_access: bool,
) -> impl Iterator<Item = &TyStructField> {
fields
.iter()
.filter(move |field| !is_public_struct_access || field.is_public())
}
/// Returns names of the [TyStructField]s from the `fields` that are accessible in the given context.
/// If `is_public_struct_access` is true, only the names of the public fields are returned, otherwise
/// the names of all fields.
/// Suitable for error reporting.
pub(crate) fn accessible_fields_names(
fields: &[TyStructField],
is_public_struct_access: bool,
) -> Vec<Ident> {
Self::accessible_fields(fields, is_public_struct_access)
.map(|field| field.name.clone())
.collect()
}
}
impl Spanned for TyStructField {
fn span(&self) -> Span {
self.span.clone()
}
}
impl HashWithEngines for TyStructField {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyStructField {
visibility,
name,
type_argument,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
attributes: _,
} = self;
visibility.hash(state);
name.hash(state);
type_argument.hash(state, engines);
}
}
impl EqWithEngines for TyStructField {}
impl PartialEqWithEngines for TyStructField {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name && self.type_argument.eq(&other.type_argument, ctx)
}
}
impl OrdWithEngines for TyStructField {
fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering {
let TyStructField {
name: ln,
type_argument: lta,
// these fields are not compared because they aren't relevant for ordering
span: _,
attributes: _,
visibility: _,
} = self;
let TyStructField {
name: rn,
type_argument: rta,
// these fields are not compared because they aren't relevant for ordering
span: _,
attributes: _,
visibility: _,
} = other;
ln.cmp(rn).then_with(|| lta.cmp(rta, ctx))
}
}
impl SubstTypes for TyStructField {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
self.type_argument.subst_inner(ctx)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/variable.rs | sway-core/src/language/ty/declaration/variable.rs | use crate::{
ast_elements::type_argument::GenericTypeArgument,
engine_threading::*,
language::{parsed::VariableDeclaration, ty::*},
type_system::*,
};
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use sway_types::{Ident, Named, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyVariableDecl {
pub name: Ident,
pub body: TyExpression,
pub mutability: VariableMutability,
pub return_type: TypeId,
pub type_ascription: GenericTypeArgument,
}
impl TyDeclParsedType for TyVariableDecl {
type ParsedType = VariableDeclaration;
}
impl Named for TyVariableDecl {
fn name(&self) -> &sway_types::BaseIdent {
&self.name
}
}
impl Spanned for TyVariableDecl {
fn span(&self) -> sway_types::Span {
self.name.span()
}
}
impl EqWithEngines for TyVariableDecl {}
impl PartialEqWithEngines for TyVariableDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let type_engine = ctx.engines().te();
self.name == other.name
&& self.body.eq(&other.body, ctx)
&& self.mutability == other.mutability
&& type_engine
.get(self.return_type)
.eq(&type_engine.get(other.return_type), ctx)
&& self.type_ascription.eq(&other.type_ascription, ctx)
}
}
impl HashWithEngines for TyVariableDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyVariableDecl {
name,
body,
mutability,
return_type,
type_ascription,
} = self;
let type_engine = engines.te();
name.hash(state);
body.hash(state, engines);
type_engine.get(*return_type).hash(state, engines);
type_ascription.hash(state, engines);
mutability.hash(state);
}
}
impl SubstTypes for TyVariableDecl {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
self.return_type.subst(ctx);
self.type_ascription.subst(ctx);
self.body.subst(ctx)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/declaration.rs | sway-core/src/language/ty/declaration/declaration.rs | use crate::{
decl_engine::*,
engine_threading::*,
language::{parsed::Declaration, ty::*, Visibility},
type_system::*,
types::*,
};
use serde::{Deserialize, Serialize};
use std::{
fmt,
hash::{Hash, Hasher},
};
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::{BaseIdent, Ident, Named, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TyDecl {
VariableDecl(Box<TyVariableDecl>),
ConstantDecl(ConstantDecl),
ConfigurableDecl(ConfigurableDecl),
ConstGenericDecl(ConstGenericDecl),
TraitTypeDecl(TraitTypeDecl),
FunctionDecl(FunctionDecl),
TraitDecl(TraitDecl),
StructDecl(StructDecl),
EnumDecl(EnumDecl),
EnumVariantDecl(EnumVariantDecl),
ImplSelfOrTrait(ImplSelfOrTrait),
AbiDecl(AbiDecl),
// If type parameters are defined for a function, they are put in the namespace just for
// the body of that function.
GenericTypeForFunctionScope(GenericTypeForFunctionScope),
ErrorRecovery(Span, #[serde(skip)] ErrorEmitted),
StorageDecl(StorageDecl),
TypeAliasDecl(TypeAliasDecl),
}
/// This trait is used to associate a typed declaration node with its
/// corresponding parsed declaration node by way of an associated type.
/// This is used by the generic code in [`DeclEngine`] related to handling
/// typed to parsed node maps.
pub trait TyDeclParsedType {
type ParsedType;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ConstGenericDecl {
pub decl_id: DeclId<TyConstGenericDecl>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ConstantDecl {
pub decl_id: DeclId<TyConstantDecl>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ConfigurableDecl {
pub decl_id: DeclId<TyConfigurableDecl>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TraitTypeDecl {
pub decl_id: DeclId<TyTraitType>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FunctionDecl {
pub decl_id: DeclId<TyFunctionDecl>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TraitDecl {
pub decl_id: DeclId<TyTraitDecl>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StructDecl {
pub decl_id: DeclId<TyStructDecl>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EnumDecl {
pub decl_id: DeclId<TyEnumDecl>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EnumVariantDecl {
pub enum_ref: DeclRefEnum,
pub variant_name: Ident,
pub variant_decl_span: Span,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ImplSelfOrTrait {
pub decl_id: DeclId<TyImplSelfOrTrait>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AbiDecl {
pub decl_id: DeclId<TyAbiDecl>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GenericTypeForFunctionScope {
pub name: Ident,
pub type_id: TypeId,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StorageDecl {
pub decl_id: DeclId<TyStorageDecl>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TypeAliasDecl {
pub decl_id: DeclId<TyTypeAliasDecl>,
}
impl EqWithEngines for TyDecl {}
impl PartialEqWithEngines for TyDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let decl_engine = ctx.engines().de();
let type_engine = ctx.engines().te();
match (self, other) {
(TyDecl::VariableDecl(x), TyDecl::VariableDecl(y)) => x.eq(y, ctx),
(
TyDecl::ConstantDecl(ConstantDecl { decl_id: lid, .. }),
TyDecl::ConstantDecl(ConstantDecl { decl_id: rid, .. }),
) => decl_engine.get(lid).eq(&decl_engine.get(rid), ctx),
(
TyDecl::FunctionDecl(FunctionDecl { decl_id: lid, .. }),
TyDecl::FunctionDecl(FunctionDecl { decl_id: rid, .. }),
) => decl_engine.get(lid).eq(&decl_engine.get(rid), ctx),
(
TyDecl::TraitDecl(TraitDecl { decl_id: lid, .. }),
TyDecl::TraitDecl(TraitDecl { decl_id: rid, .. }),
) => decl_engine.get(lid).eq(&decl_engine.get(rid), ctx),
(
TyDecl::StructDecl(StructDecl { decl_id: lid, .. }),
TyDecl::StructDecl(StructDecl { decl_id: rid, .. }),
) => decl_engine.get(lid).eq(&decl_engine.get(rid), ctx),
(
TyDecl::EnumDecl(EnumDecl { decl_id: lid, .. }),
TyDecl::EnumDecl(EnumDecl { decl_id: rid, .. }),
) => decl_engine.get(lid).eq(&decl_engine.get(rid), ctx),
(
TyDecl::EnumVariantDecl(EnumVariantDecl {
enum_ref: l_enum,
variant_name: ln,
..
}),
TyDecl::EnumVariantDecl(EnumVariantDecl {
enum_ref: r_enum,
variant_name: rn,
..
}),
) => {
ln == rn
&& decl_engine
.get_enum(l_enum)
.eq(&decl_engine.get_enum(r_enum), ctx)
}
(
TyDecl::ImplSelfOrTrait(ImplSelfOrTrait { decl_id: lid, .. }),
TyDecl::ImplSelfOrTrait(ImplSelfOrTrait { decl_id: rid, .. }),
) => decl_engine.get(lid).eq(&decl_engine.get(rid), ctx),
(
TyDecl::AbiDecl(AbiDecl { decl_id: lid, .. }),
TyDecl::AbiDecl(AbiDecl { decl_id: rid, .. }),
) => decl_engine.get(lid).eq(&decl_engine.get(rid), ctx),
(
TyDecl::StorageDecl(StorageDecl { decl_id: lid, .. }),
TyDecl::StorageDecl(StorageDecl { decl_id: rid, .. }),
) => decl_engine.get(lid).eq(&decl_engine.get(rid), ctx),
(
TyDecl::TypeAliasDecl(TypeAliasDecl { decl_id: lid, .. }),
TyDecl::TypeAliasDecl(TypeAliasDecl { decl_id: rid, .. }),
) => decl_engine.get(lid).eq(&decl_engine.get(rid), ctx),
(
TyDecl::GenericTypeForFunctionScope(GenericTypeForFunctionScope {
name: xn,
type_id: xti,
}),
TyDecl::GenericTypeForFunctionScope(GenericTypeForFunctionScope {
name: yn,
type_id: yti,
}),
) => xn == yn && type_engine.get(*xti).eq(&type_engine.get(*yti), ctx),
(TyDecl::ErrorRecovery(x, _), TyDecl::ErrorRecovery(y, _)) => x == y,
_ => false,
}
}
}
impl HashWithEngines for TyDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let decl_engine = engines.de();
let type_engine = engines.te();
std::mem::discriminant(self).hash(state);
match self {
TyDecl::VariableDecl(decl) => {
decl.hash(state, engines);
}
TyDecl::ConstantDecl(ConstantDecl { decl_id, .. }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::ConfigurableDecl(ConfigurableDecl { decl_id, .. }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::ConstGenericDecl(ConstGenericDecl { decl_id }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::TraitTypeDecl(TraitTypeDecl { decl_id, .. }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::FunctionDecl(FunctionDecl { decl_id, .. }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::TraitDecl(TraitDecl { decl_id, .. }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::StructDecl(StructDecl { decl_id, .. }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::EnumDecl(EnumDecl { decl_id, .. }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::EnumVariantDecl(EnumVariantDecl {
enum_ref,
variant_name,
..
}) => {
enum_ref.hash(state, engines);
variant_name.hash(state);
}
TyDecl::ImplSelfOrTrait(ImplSelfOrTrait { decl_id, .. }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::AbiDecl(AbiDecl { decl_id, .. }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::TypeAliasDecl(TypeAliasDecl { decl_id, .. }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::StorageDecl(StorageDecl { decl_id, .. }) => {
decl_engine.get(decl_id).hash(state, engines);
}
TyDecl::GenericTypeForFunctionScope(GenericTypeForFunctionScope { name, type_id }) => {
name.hash(state);
type_engine.get(*type_id).hash(state, engines);
}
TyDecl::ErrorRecovery(..) => {}
}
}
}
impl SubstTypes for TyDecl {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
match self {
TyDecl::VariableDecl(ref mut var_decl) => var_decl.subst(ctx),
TyDecl::FunctionDecl(FunctionDecl {
ref mut decl_id, ..
}) => decl_id.subst(ctx),
TyDecl::TraitDecl(TraitDecl {
ref mut decl_id, ..
}) => decl_id.subst(ctx),
TyDecl::StructDecl(StructDecl {
ref mut decl_id, ..
}) => decl_id.subst(ctx),
TyDecl::EnumDecl(EnumDecl {
ref mut decl_id, ..
}) => decl_id.subst(ctx),
TyDecl::EnumVariantDecl(EnumVariantDecl {
ref mut enum_ref, ..
}) => enum_ref.subst(ctx),
TyDecl::ImplSelfOrTrait(ImplSelfOrTrait {
ref mut decl_id, ..
}) => decl_id.subst(ctx),
TyDecl::TypeAliasDecl(TypeAliasDecl {
ref mut decl_id, ..
}) => decl_id.subst(ctx),
TyDecl::TraitTypeDecl(TraitTypeDecl {
ref mut decl_id, ..
}) => decl_id.subst(ctx),
TyDecl::ConstantDecl(ConstantDecl { decl_id }) => decl_id.subst(ctx),
// generics in an ABI is unsupported by design
TyDecl::AbiDecl(_)
| TyDecl::ConfigurableDecl(_)
| TyDecl::StorageDecl(_)
| TyDecl::GenericTypeForFunctionScope(_)
| TyDecl::ErrorRecovery(..) => HasChanges::No,
TyDecl::ConstGenericDecl(_) => HasChanges::No,
}
}
}
impl SpannedWithEngines for TyDecl {
fn span(&self, engines: &Engines) -> Span {
match self {
TyDecl::ConstantDecl(ConstantDecl { decl_id, .. }) => {
let decl = engines.de().get(decl_id);
decl.span.clone()
}
TyDecl::ConfigurableDecl(ConfigurableDecl { decl_id, .. }) => {
let decl = engines.de().get(decl_id);
decl.span.clone()
}
TyDecl::ConstGenericDecl(ConstGenericDecl { decl_id }) => {
let decl = engines.de().get(decl_id);
decl.span.clone()
}
TyDecl::TraitTypeDecl(TraitTypeDecl { decl_id }) => {
engines.de().get_type(decl_id).span.clone()
}
TyDecl::FunctionDecl(FunctionDecl { decl_id }) => {
engines.de().get_function(decl_id).span.clone()
}
TyDecl::TraitDecl(TraitDecl { decl_id }) => {
engines.de().get_trait(decl_id).span.clone()
}
TyDecl::StructDecl(StructDecl { decl_id }) => {
engines.de().get_struct(decl_id).span.clone()
}
TyDecl::EnumDecl(EnumDecl { decl_id }) => engines.de().get_enum(decl_id).span.clone(),
TyDecl::ImplSelfOrTrait(ImplSelfOrTrait { decl_id }) => {
engines.de().get_impl_self_or_trait(decl_id).span.clone()
}
TyDecl::AbiDecl(AbiDecl { decl_id }) => engines.de().get_abi(decl_id).span.clone(),
TyDecl::VariableDecl(decl) => decl.name.span(),
TyDecl::StorageDecl(StorageDecl { decl_id }) => engines.de().get(decl_id).span.clone(),
TyDecl::TypeAliasDecl(TypeAliasDecl { decl_id }) => {
engines.de().get(decl_id).span.clone()
}
TyDecl::EnumVariantDecl(EnumVariantDecl {
variant_decl_span, ..
}) => variant_decl_span.clone(),
TyDecl::GenericTypeForFunctionScope(GenericTypeForFunctionScope { name, .. }) => {
name.span()
}
TyDecl::ErrorRecovery(span, _) => span.clone(),
}
}
}
impl DisplayWithEngines for TyDecl {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> std::fmt::Result {
let type_engine = engines.te();
write!(
f,
"{} declaration ({})",
self.friendly_type_name(),
match self {
TyDecl::VariableDecl(decl) => {
let TyVariableDecl {
mutability,
name,
type_ascription,
body,
..
} = &**decl;
let mut builder = String::new();
match mutability {
VariableMutability::Mutable => builder.push_str("mut"),
VariableMutability::RefMutable => builder.push_str("ref mut"),
VariableMutability::Immutable => {}
}
builder.push_str(name.as_str());
builder.push_str(": ");
builder.push_str(
&engines
.help_out(&*type_engine.get(type_ascription.type_id))
.to_string(),
);
builder.push_str(" = ");
builder.push_str(&engines.help_out(body).to_string());
builder
}
TyDecl::FunctionDecl(FunctionDecl { decl_id }) => {
engines.de().get(decl_id).name.as_str().into()
}
TyDecl::TraitDecl(TraitDecl { decl_id }) => {
engines.de().get(decl_id).name.as_str().into()
}
TyDecl::StructDecl(StructDecl { decl_id }) => {
engines.de().get(decl_id).name().as_str().into()
}
TyDecl::EnumDecl(EnumDecl { decl_id }) => {
engines.de().get(decl_id).name().as_str().into()
}
TyDecl::ImplSelfOrTrait(ImplSelfOrTrait { decl_id }) => {
engines.de().get(decl_id).name().as_str().into()
}
TyDecl::TypeAliasDecl(TypeAliasDecl { decl_id }) =>
engines.de().get(decl_id).name().as_str().into(),
_ => String::new(),
}
)
}
}
impl DebugWithEngines for TyDecl {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> std::fmt::Result {
let type_engine = engines.te();
write!(
f,
"{} declaration ({})",
self.friendly_type_name(),
match self {
TyDecl::VariableDecl(decl) => {
let TyVariableDecl {
mutability,
name,
type_ascription,
body,
..
} = &**decl;
let mut builder = String::new();
match mutability {
VariableMutability::Mutable => builder.push_str("mut"),
VariableMutability::RefMutable => builder.push_str("ref mut"),
VariableMutability::Immutable => {}
}
builder.push_str(name.as_str());
builder.push_str(": ");
builder.push_str(
&engines
.help_out(&*type_engine.get(type_ascription.type_id))
.to_string(),
);
builder.push_str(" = ");
builder.push_str(&engines.help_out(body).to_string());
builder
}
TyDecl::FunctionDecl(FunctionDecl { decl_id }) => {
engines.de().get(decl_id).name.as_str().into()
}
TyDecl::TraitDecl(TraitDecl { decl_id }) => {
engines.de().get(decl_id).name.as_str().into()
}
TyDecl::StructDecl(StructDecl { decl_id }) => {
engines.de().get(decl_id).name().as_str().into()
}
TyDecl::EnumDecl(EnumDecl { decl_id }) => {
engines.de().get(decl_id).name().as_str().into()
}
TyDecl::ImplSelfOrTrait(ImplSelfOrTrait { decl_id }) => {
let decl = engines.de().get(decl_id);
return DebugWithEngines::fmt(&*decl, f, engines);
}
TyDecl::TypeAliasDecl(TypeAliasDecl { decl_id }) =>
engines.de().get(decl_id).name().as_str().into(),
_ => String::new(),
}
)
}
}
impl CollectTypesMetadata for TyDecl {
// this is only run on entry nodes, which must have all well-formed types
fn collect_types_metadata(
&self,
handler: &Handler,
ctx: &mut CollectTypesMetadataContext,
) -> Result<Vec<TypeMetadata>, ErrorEmitted> {
let decl_engine = ctx.engines.de();
let metadata = match self {
TyDecl::VariableDecl(decl) => {
let mut body = decl.body.collect_types_metadata(handler, ctx)?;
body.append(
&mut decl
.type_ascription
.type_id
.collect_types_metadata(handler, ctx)?,
);
body
}
TyDecl::FunctionDecl(FunctionDecl { decl_id, .. }) => {
let decl = decl_engine.get_function(decl_id);
decl.collect_types_metadata(handler, ctx)?
}
TyDecl::ConstantDecl(ConstantDecl { decl_id, .. }) => {
let decl = decl_engine.get_constant(decl_id);
let TyConstantDecl { value, .. } = &*decl;
if let Some(value) = value {
value.collect_types_metadata(handler, ctx)?
} else {
vec![]
}
}
TyDecl::ConfigurableDecl(ConfigurableDecl { decl_id, .. }) => {
let decl = decl_engine.get_configurable(decl_id);
let TyConfigurableDecl { value, .. } = &*decl;
if let Some(value) = value {
value.collect_types_metadata(handler, ctx)?
} else {
return Ok(vec![]);
}
}
TyDecl::ErrorRecovery(..)
| TyDecl::StorageDecl(_)
| TyDecl::TraitDecl(_)
| TyDecl::StructDecl(_)
| TyDecl::EnumDecl(_)
| TyDecl::EnumVariantDecl(_)
| TyDecl::ImplSelfOrTrait(_)
| TyDecl::AbiDecl(_)
| TyDecl::TypeAliasDecl(_)
| TyDecl::TraitTypeDecl(_)
| TyDecl::GenericTypeForFunctionScope(_)
| TyDecl::ConstGenericDecl(_) => vec![],
};
Ok(metadata)
}
}
impl GetDeclIdent for TyDecl {
fn get_decl_ident(&self, engines: &Engines) -> Option<Ident> {
match self {
TyDecl::ConstantDecl(ConstantDecl { decl_id }) => {
Some(engines.de().get_constant(decl_id).name().clone())
}
TyDecl::ConfigurableDecl(ConfigurableDecl { decl_id }) => {
Some(engines.de().get_configurable(decl_id).name().clone())
}
TyDecl::ConstGenericDecl(ConstGenericDecl { decl_id }) => {
Some(engines.de().get_const_generic(decl_id).name().clone())
}
TyDecl::TraitTypeDecl(TraitTypeDecl { decl_id }) => {
Some(engines.de().get_type(decl_id).name().clone())
}
TyDecl::FunctionDecl(FunctionDecl { decl_id }) => {
Some(engines.de().get(decl_id).name.clone())
}
TyDecl::TraitDecl(TraitDecl { decl_id }) => {
Some(engines.de().get(decl_id).name.clone())
}
TyDecl::StructDecl(StructDecl { decl_id }) => {
Some(engines.de().get(decl_id).name().clone())
}
TyDecl::EnumDecl(EnumDecl { decl_id }) => {
Some(engines.de().get(decl_id).name().clone())
}
TyDecl::ImplSelfOrTrait(ImplSelfOrTrait { decl_id }) => {
Some(engines.de().get(decl_id).name().clone())
}
TyDecl::AbiDecl(AbiDecl { decl_id }) => Some(engines.de().get(decl_id).name().clone()),
TyDecl::VariableDecl(decl) => Some(decl.name.clone()),
TyDecl::TypeAliasDecl(TypeAliasDecl { decl_id }) => {
Some(engines.de().get(decl_id).name().clone())
}
TyDecl::GenericTypeForFunctionScope(GenericTypeForFunctionScope { name, .. }) => {
Some(name.clone())
}
TyDecl::EnumVariantDecl(EnumVariantDecl { variant_name, .. }) => {
Some(variant_name.clone())
}
TyDecl::ErrorRecovery(..) => None,
TyDecl::StorageDecl(_) => None,
}
}
}
impl TyDecl {
pub(crate) fn get_parsed_decl(&self, decl_engine: &DeclEngine) -> Option<Declaration> {
match self {
TyDecl::VariableDecl(_decl) => None,
TyDecl::ConstantDecl(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::ConfigurableDecl(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::ConstGenericDecl(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::TraitTypeDecl(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::FunctionDecl(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::TraitDecl(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::StructDecl(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::EnumDecl(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::EnumVariantDecl(decl) => decl_engine.get_parsed_decl(decl.enum_ref.id()),
TyDecl::ImplSelfOrTrait(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::AbiDecl(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::GenericTypeForFunctionScope(_data) => None,
TyDecl::StorageDecl(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::TypeAliasDecl(decl) => decl_engine.get_parsed_decl(&decl.decl_id),
TyDecl::ErrorRecovery(_, _) => None,
}
}
/// Retrieves the declaration as a `DeclId<TyEnumDecl>`.
///
/// Returns an error if `self` is not the [TyDecl][EnumDecl] variant.
pub(crate) fn to_enum_id(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<DeclId<TyEnumDecl>, ErrorEmitted> {
match self {
TyDecl::EnumDecl(EnumDecl { decl_id }) => Ok(*decl_id),
TyDecl::TypeAliasDecl(TypeAliasDecl { decl_id, .. }) => {
let alias_decl = engines.de().get_type_alias(decl_id);
let TyTypeAliasDecl { ty, span, .. } = &*alias_decl;
engines
.te()
.get(ty.type_id)
.expect_enum(handler, engines, "", span)
}
// `Self` type parameter might resolve to an Enum
TyDecl::GenericTypeForFunctionScope(GenericTypeForFunctionScope {
type_id, ..
}) => match &*engines.te().get(*type_id) {
TypeInfo::Enum(r) => Ok(*r),
_ => Err(handler.emit_err(CompileError::DeclIsNotAnEnum {
actually: self.friendly_type_name().to_string(),
span: self.span(engines),
})),
},
TyDecl::ErrorRecovery(_, err) => Err(*err),
decl => Err(handler.emit_err(CompileError::DeclIsNotAnEnum {
actually: decl.friendly_type_name().to_string(),
span: decl.span(engines),
})),
}
}
/// Retrieves the declaration as a `DeclRef<DeclId<TyStructDecl>>`.
///
/// Returns an error if `self` is not the [TyDecl][StructDecl] variant.
pub(crate) fn to_struct_decl(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<DeclId<TyStructDecl>, ErrorEmitted> {
match self {
TyDecl::StructDecl(StructDecl { decl_id }) => Ok(*decl_id),
TyDecl::TypeAliasDecl(TypeAliasDecl { decl_id, .. }) => {
let alias_decl = engines.de().get_type_alias(decl_id);
let TyTypeAliasDecl { ty, span, .. } = &*alias_decl;
engines
.te()
.get(ty.type_id)
.expect_struct(handler, engines, span)
}
TyDecl::ErrorRecovery(_, err) => Err(*err),
decl => Err(handler.emit_err(CompileError::DeclIsNotAStruct {
actually: decl.friendly_type_name().to_string(),
span: decl.span(engines),
})),
}
}
/// Retrieves the declaration as a `DeclRef<DeclId<TyFunctionDecl>>`.
///
/// Returns an error if `self` is not the [TyDecl][FunctionDecl] variant.
pub(crate) fn to_fn_ref(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<DeclRefFunction, ErrorEmitted> {
match self {
TyDecl::FunctionDecl(FunctionDecl { decl_id }) => {
let decl = engines.de().get(decl_id);
Ok(DeclRef::new(decl.name.clone(), *decl_id, decl.span.clone()))
}
TyDecl::ErrorRecovery(_, err) => Err(*err),
decl => Err(handler.emit_err(CompileError::DeclIsNotAFunction {
actually: decl.friendly_type_name().to_string(),
span: decl.span(engines),
})),
}
}
/// Retrieves the declaration as a variable declaration.
///
/// Returns an error if `self` is not a [TyVariableDecl].
pub(crate) fn expect_variable(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<&TyVariableDecl, ErrorEmitted> {
match self {
TyDecl::VariableDecl(decl) => Ok(decl),
TyDecl::ErrorRecovery(_, err) => Err(*err),
decl => Err(handler.emit_err(CompileError::DeclIsNotAVariable {
actually: decl.friendly_type_name().to_string(),
span: decl.span(engines),
})),
}
}
/// Retrieves the declaration as a `DeclRef<DeclId<TyAbiDecl>>`.
///
/// Returns an error if `self` is not the [TyDecl][AbiDecl] variant.
pub(crate) fn to_abi_ref(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<DeclRef<DeclId<TyAbiDecl>>, ErrorEmitted> {
match self {
TyDecl::AbiDecl(AbiDecl { decl_id }) => {
let abi_decl = engines.de().get_abi(decl_id);
Ok(DeclRef::new(
abi_decl.name().clone(),
*decl_id,
abi_decl.span.clone(),
))
}
TyDecl::ErrorRecovery(_, err) => Err(*err),
decl => Err(handler.emit_err(CompileError::DeclIsNotAnAbi {
actually: decl.friendly_type_name().to_string(),
span: decl.span(engines),
})),
}
}
/// Retrieves the declaration as a `DeclRef<DeclId<TyConstantDecl>>`.
///
/// Returns an error if `self` is not the [TyDecl][ConstantDecl] variant.
pub(crate) fn to_const_ref(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<DeclRef<DeclId<TyConstantDecl>>, ErrorEmitted> {
match self {
TyDecl::ConstantDecl(ConstantDecl { decl_id }) => {
let const_decl = engines.de().get_constant(decl_id);
Ok(DeclRef::new(
const_decl.name().clone(),
*decl_id,
const_decl.span.clone(),
))
}
TyDecl::ErrorRecovery(_, err) => Err(*err),
decl => Err(handler.emit_err(CompileError::DeclIsNotAConstant {
actually: decl.friendly_type_name().to_string(),
span: decl.span(engines),
})),
}
}
pub fn get_name(&self, engines: &Engines) -> BaseIdent {
match self {
TyDecl::VariableDecl(ty_variable_decl) => ty_variable_decl.name.clone(),
TyDecl::ConstantDecl(constant_decl) => engines
.de()
.get_constant(&constant_decl.decl_id)
.call_path
.suffix
.clone(),
TyDecl::ConfigurableDecl(configurable_decl) => engines
.de()
.get_configurable(&configurable_decl.decl_id)
.call_path
.suffix
.clone(),
TyDecl::ConstGenericDecl(const_generic_decl) => engines
.de()
.get_const_generic(&const_generic_decl.decl_id)
.call_path
.suffix
.clone(),
TyDecl::TraitTypeDecl(trait_type_decl) => {
engines.de().get_type(&trait_type_decl.decl_id).name.clone()
}
TyDecl::FunctionDecl(function_decl) => engines
.de()
.get_function(&function_decl.decl_id)
.name
.clone(),
TyDecl::TraitDecl(trait_decl) => {
engines.de().get_trait(&trait_decl.decl_id).name.clone()
}
TyDecl::StructDecl(struct_decl) => engines
.de()
.get_struct(&struct_decl.decl_id)
.call_path
.suffix
.clone(),
TyDecl::EnumDecl(enum_decl) => engines
.de()
.get_enum(&enum_decl.decl_id)
.call_path
.suffix
.clone(),
TyDecl::EnumVariantDecl(_enum_variant_decl) => {
unreachable!()
}
TyDecl::ImplSelfOrTrait(impl_self_or_trait) => engines
.de()
.get_impl_self_or_trait(&impl_self_or_trait.decl_id)
.trait_name
.suffix
.clone(),
TyDecl::AbiDecl(abi_decl) => engines.de().get_abi(&abi_decl.decl_id).name.clone(),
TyDecl::GenericTypeForFunctionScope(_generic_type_for_function_scope) => unreachable!(),
TyDecl::ErrorRecovery(_span, _error_emitted) => unreachable!(),
TyDecl::StorageDecl(_storage_decl) => unreachable!(),
TyDecl::TypeAliasDecl(type_alias_decl) => engines
.de()
.get_type_alias(&type_alias_decl.decl_id)
.call_path
.suffix
.clone(),
}
}
/// Friendly name string used for error reporting,
/// which consists of the identifier for the declaration.
pub fn friendly_name(&self, engines: &Engines) -> String {
let decl_engine = engines.de();
let type_engine = engines.te();
match self {
TyDecl::ImplSelfOrTrait(ImplSelfOrTrait { decl_id, .. }) => {
let decl = decl_engine.get_impl_self_or_trait(decl_id);
let implementing_for_type_id_arc = type_engine.get(decl.implementing_for.type_id);
let implementing_for_type_id = &*implementing_for_type_id_arc;
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/trait.rs | sway-core/src/language/ty/declaration/trait.rs | use crate::{
decl_engine::{
DeclEngineReplace, DeclRefConstant, DeclRefFunction, DeclRefTraitFn, DeclRefTraitType,
MaterializeConstGenerics, ReplaceFunctionImplementingType,
},
engine_threading::*,
has_changes,
language::{
parsed::{self, TraitDeclaration},
ty::{TyDecl, TyDeclParsedType},
CallPath, Visibility,
},
semantic_analysis::{
TypeCheckAnalysis, TypeCheckAnalysisContext, TypeCheckFinalization,
TypeCheckFinalizationContext,
},
transform,
type_system::*,
};
use monomorphization::MonomorphizeHelper;
use serde::{Deserialize, Serialize};
use std::{
fmt,
hash::{Hash, Hasher},
};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyTraitDecl {
pub name: Ident,
pub type_parameters: Vec<TypeParameter>,
pub self_type: TypeParameter,
pub interface_surface: Vec<TyTraitInterfaceItem>,
pub items: Vec<TyTraitItem>,
pub supertraits: Vec<parsed::Supertrait>,
pub visibility: Visibility,
pub attributes: transform::Attributes,
pub call_path: CallPath,
pub span: Span,
}
impl TyDeclParsedType for TyTraitDecl {
type ParsedType = TraitDeclaration;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TyTraitInterfaceItem {
TraitFn(DeclRefTraitFn),
Constant(DeclRefConstant),
Type(DeclRefTraitType),
}
impl DisplayWithEngines for TyTraitInterfaceItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(f, "{:?}", engines.help_out(self))
}
}
impl DebugWithEngines for TyTraitInterfaceItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(
f,
"TyTraitItem {}",
match self {
TyTraitInterfaceItem::TraitFn(fn_ref) => format!(
"fn {:?}",
engines.help_out(&*engines.de().get_trait_fn(fn_ref))
),
TyTraitInterfaceItem::Constant(const_ref) => format!(
"const {:?}",
engines.help_out(&*engines.de().get_constant(const_ref))
),
TyTraitInterfaceItem::Type(type_ref) => format!(
"type {:?}",
engines.help_out(&*engines.de().get_type(type_ref))
),
}
)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TyTraitItem {
Fn(DeclRefFunction),
Constant(DeclRefConstant),
Type(DeclRefTraitType),
}
impl DisplayWithEngines for TyTraitItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(f, "{:?}", engines.help_out(self))
}
}
impl DebugWithEngines for TyTraitItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(
f,
"TyTraitItem {}",
match self {
TyTraitItem::Fn(fn_ref) => format!(
"fn {:?}",
engines.help_out(&*engines.de().get_function(fn_ref))
),
TyTraitItem::Constant(const_ref) => format!(
"const {:?}",
engines.help_out(&*engines.de().get_constant(const_ref))
),
TyTraitItem::Type(type_ref) => format!(
"type {:?}",
engines.help_out(&*engines.de().get_type(type_ref))
),
}
)
}
}
impl Named for TyTraitDecl {
fn name(&self) -> &Ident {
&self.name
}
}
impl Spanned for TyTraitDecl {
fn span(&self) -> Span {
self.span.clone()
}
}
impl EqWithEngines for TyTraitDecl {}
impl PartialEqWithEngines for TyTraitDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.type_parameters.eq(&other.type_parameters, ctx)
&& self.interface_surface.eq(&other.interface_surface, ctx)
&& self.items.eq(&other.items, ctx)
&& self.supertraits.eq(&other.supertraits, ctx)
&& self.visibility == other.visibility
}
}
impl HashWithEngines for TyTraitDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyTraitDecl {
name,
type_parameters,
self_type,
interface_surface,
items,
supertraits,
visibility,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
attributes: _,
span: _,
call_path: _,
} = self;
name.hash(state);
type_parameters.hash(state, engines);
self_type.hash(state, engines);
interface_surface.hash(state, engines);
items.hash(state, engines);
supertraits.hash(state, engines);
visibility.hash(state);
}
}
impl MaterializeConstGenerics for TyTraitDecl {
fn materialize_const_generics(
&mut self,
_engines: &Engines,
_handler: &Handler,
_name: &str,
_value: &crate::language::ty::TyExpression,
) -> Result<(), ErrorEmitted> {
Ok(())
}
}
impl EqWithEngines for TyTraitInterfaceItem {}
impl PartialEqWithEngines for TyTraitInterfaceItem {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(TyTraitInterfaceItem::TraitFn(id), TyTraitInterfaceItem::TraitFn(other_id)) => {
id.eq(other_id, ctx)
}
(TyTraitInterfaceItem::Constant(id), TyTraitInterfaceItem::Constant(other_id)) => {
id.eq(other_id, ctx)
}
_ => false,
}
}
}
impl EqWithEngines for TyTraitItem {}
impl PartialEqWithEngines for TyTraitItem {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(TyTraitItem::Fn(id), TyTraitItem::Fn(other_id)) => id.eq(other_id, ctx),
(TyTraitItem::Constant(id), TyTraitItem::Constant(other_id)) => id.eq(other_id, ctx),
_ => false,
}
}
}
impl HashWithEngines for TyTraitInterfaceItem {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
match self {
TyTraitInterfaceItem::TraitFn(fn_decl) => fn_decl.hash(state, engines),
TyTraitInterfaceItem::Constant(const_decl) => const_decl.hash(state, engines),
TyTraitInterfaceItem::Type(type_decl) => type_decl.hash(state, engines),
}
}
}
impl HashWithEngines for TyTraitItem {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
match self {
TyTraitItem::Fn(fn_decl) => fn_decl.hash(state, engines),
TyTraitItem::Constant(const_decl) => const_decl.hash(state, engines),
TyTraitItem::Type(type_decl) => type_decl.hash(state, engines),
}
}
}
impl TypeCheckAnalysis for TyTraitItem {
fn type_check_analyze(
&self,
handler: &Handler,
ctx: &mut TypeCheckAnalysisContext,
) -> Result<(), ErrorEmitted> {
let decl_engine = ctx.engines.de();
match self {
TyTraitItem::Fn(node) => {
node.type_check_analyze(handler, ctx)?;
}
TyTraitItem::Constant(node) => {
let item_const = decl_engine.get_constant(node);
item_const.type_check_analyze(handler, ctx)?;
}
TyTraitItem::Type(node) => {
let item_type = decl_engine.get_type(node);
item_type.type_check_analyze(handler, ctx)?;
}
}
Ok(())
}
}
impl TypeCheckFinalization for TyTraitItem {
fn type_check_finalize(
&mut self,
handler: &Handler,
ctx: &mut TypeCheckFinalizationContext,
) -> Result<(), ErrorEmitted> {
let decl_engine = ctx.engines.de();
match self {
TyTraitItem::Fn(node) => {
let mut item_fn = (*decl_engine.get_function(node)).clone();
item_fn.type_check_finalize(handler, ctx)?;
decl_engine.replace(*node.id(), item_fn);
}
TyTraitItem::Constant(node) => {
let mut item_const = (*decl_engine.get_constant(node)).clone();
item_const.type_check_finalize(handler, ctx)?;
decl_engine.replace(*node.id(), item_const);
}
TyTraitItem::Type(_node) => {
// Nothing to finalize
}
}
Ok(())
}
}
impl Spanned for TyTraitItem {
fn span(&self) -> Span {
match self {
TyTraitItem::Fn(fn_decl) => fn_decl.span(),
TyTraitItem::Constant(const_decl) => const_decl.span(),
TyTraitItem::Type(type_decl) => type_decl.span(),
}
}
}
impl SubstTypes for TyTraitDecl {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
self.type_parameters.subst(ctx);
self.interface_surface
.iter_mut()
.fold(HasChanges::No, |has_changes, item| match item {
TyTraitInterfaceItem::TraitFn(item_ref) => {
if let Some(new_item_ref) = item_ref
.clone()
.subst_types_and_insert_new_with_parent(ctx) {
item_ref.replace_id(*new_item_ref.id());
HasChanges::Yes
} else {
HasChanges::No
}
}
TyTraitInterfaceItem::Constant(decl_ref) => {
if let Some(new_decl_ref) = decl_ref
.clone()
.subst_types_and_insert_new(ctx) {
decl_ref.replace_id(*new_decl_ref.id());
HasChanges::Yes
} else{
HasChanges::No
}
}
TyTraitInterfaceItem::Type(decl_ref) => {
if let Some(new_decl_ref) = decl_ref
.clone()
.subst_types_and_insert_new(ctx) {
decl_ref.replace_id(*new_decl_ref.id());
HasChanges::Yes
} else{
HasChanges::No
}
}
} | has_changes);
self.items.iter_mut().fold(HasChanges::No, |has_changes, item| match item {
TyTraitItem::Fn(item_ref) => {
if let Some(new_item_ref) = item_ref
.clone()
.subst_types_and_insert_new_with_parent(ctx)
{
item_ref.replace_id(*new_item_ref.id());
HasChanges::Yes
} else {
HasChanges::No
}
}
TyTraitItem::Constant(item_ref) => {
if let Some(new_decl_ref) = item_ref
.clone()
.subst_types_and_insert_new_with_parent(ctx)
{
item_ref.replace_id(*new_decl_ref.id());
HasChanges::Yes
} else {
HasChanges::No
}
}
TyTraitItem::Type(item_ref) => {
if let Some(new_decl_ref) = item_ref
.clone()
.subst_types_and_insert_new_with_parent(ctx)
{
item_ref.replace_id(*new_decl_ref.id());
HasChanges::Yes
} else {
HasChanges::No
}
}
} | has_changes);
}
}
}
impl SubstTypes for TyTraitItem {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
match self {
TyTraitItem::Fn(fn_decl) => fn_decl.subst(ctx),
TyTraitItem::Constant(const_decl) => const_decl.subst(ctx),
TyTraitItem::Type(type_decl) => type_decl.subst(ctx),
}
}
}
impl ReplaceFunctionImplementingType for TyTraitItem {
fn replace_implementing_type(&mut self, engines: &Engines, implementing_type: TyDecl) {
match self {
TyTraitItem::Fn(decl_ref) => {
decl_ref.replace_implementing_type(engines, implementing_type)
}
TyTraitItem::Constant(_decl_ref) => {
// ignore, only needed for functions
}
TyTraitItem::Type(_decl_ref) => {
// ignore, only needed for functions
}
}
}
}
impl MonomorphizeHelper for TyTraitDecl {
fn name(&self) -> &Ident {
&self.name
}
fn type_parameters(&self) -> &[TypeParameter] {
&self.type_parameters
}
fn has_self_type_param(&self) -> bool {
true
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/abi.rs | sway-core/src/language/ty/declaration/abi.rs | use super::{TyDeclParsedType, TyTraitInterfaceItem, TyTraitItem};
use crate::{
decl_engine::DeclEngineGet as _,
engine_threading::*,
language::parsed::{self, AbiDeclaration},
transform,
type_system::*,
};
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::{Ident, Named, Span, Spanned};
/// A [TyAbiDecl] contains the type-checked version of the parse tree's
/// [AbiDeclaration].
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyAbiDecl {
/// The name of the abi trait (also known as a "contract trait")
pub name: Ident,
/// The methods a contract is required to implement in order opt in to this interface
pub interface_surface: Vec<TyTraitInterfaceItem>,
pub supertraits: Vec<parsed::Supertrait>,
pub items: Vec<TyTraitItem>,
pub span: Span,
pub attributes: transform::Attributes,
}
impl TyAbiDecl {
pub(crate) fn forbid_const_generics(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<(), ErrorEmitted> {
for item in self.interface_surface.iter() {
match item {
TyTraitInterfaceItem::TraitFn(decl_ref) => {
let decl = engines.de().get(decl_ref.id());
if decl.return_type.type_id.has_const_generics(engines) {
let err = handler.emit_err(CompileError::ConstGenericNotSupportedHere {
span: decl.return_type.span(),
});
return Err(err);
}
for arg in decl.parameters.iter() {
if arg.type_argument.type_id.has_const_generics(engines) {
let err =
handler.emit_err(CompileError::ConstGenericNotSupportedHere {
span: arg.type_argument.span.clone(),
});
return Err(err);
}
}
}
TyTraitInterfaceItem::Constant(_) => {}
TyTraitInterfaceItem::Type(_) => {}
}
}
for item in self.items.iter() {
match item {
TyTraitItem::Fn(decl_ref) => {
let decl = engines.de().get(decl_ref.id());
if decl.return_type.type_id.has_const_generics(engines) {
let err = handler.emit_err(CompileError::ConstGenericNotSupportedHere {
span: decl.return_type.span(),
});
return Err(err);
}
for arg in decl.parameters.iter() {
if arg.type_argument.type_id.has_const_generics(engines) {
let err =
handler.emit_err(CompileError::ConstGenericNotSupportedHere {
span: arg.type_argument.span.clone(),
});
return Err(err);
}
}
}
TyTraitItem::Constant(_) => {}
TyTraitItem::Type(_) => {}
}
}
Ok(())
}
}
impl TyDeclParsedType for TyAbiDecl {
type ParsedType = AbiDeclaration;
}
impl EqWithEngines for TyAbiDecl {}
impl PartialEqWithEngines for TyAbiDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let TyAbiDecl {
name: ln,
interface_surface: lis,
supertraits: ls,
items: li,
// these fields are not compared because they aren't relevant/a
// reliable source of obj v. obj distinction
attributes: _,
span: _,
} = self;
let TyAbiDecl {
name: rn,
interface_surface: ris,
supertraits: rs,
items: ri,
// these fields are not compared because they aren't relevant/a
// reliable source of obj v. obj distinction
attributes: _,
span: _,
} = other;
ln == rn && lis.eq(ris, ctx) && li.eq(ri, ctx) && ls.eq(rs, ctx)
}
}
impl HashWithEngines for TyAbiDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyAbiDecl {
name,
interface_surface,
items,
supertraits,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
attributes: _,
span: _,
} = self;
name.hash(state);
interface_surface.hash(state, engines);
items.hash(state, engines);
supertraits.hash(state, engines);
}
}
impl CreateTypeId for TyAbiDecl {
fn create_type_id(&self, engines: &Engines) -> TypeId {
engines
.te()
.new_contract_caller(engines, AbiName::Known(self.name.clone().into()), None)
}
}
impl Spanned for TyAbiDecl {
fn span(&self) -> Span {
self.span.clone()
}
}
impl Named for TyAbiDecl {
fn name(&self) -> &Ident {
&self.name
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/function.rs | sway-core/src/language/ty/declaration/function.rs | use crate::{
ast_elements::type_argument::GenericTypeArgument,
decl_engine::*,
engine_threading::*,
has_changes,
language::{
parsed::{self, FunctionDeclaration, FunctionDeclarationKind},
ty::*,
CallPath, Inline, Purity, Trace, Visibility,
},
semantic_analysis::TypeCheckContext,
transform::{self, AttributeKind},
type_system::*,
types::*,
};
use ast_elements::type_parameter::ConstGenericExpr;
use either::Either;
use monomorphization::MonomorphizeHelper;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
collections::BTreeMap,
fmt,
hash::{Hash, Hasher},
};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TyFunctionDeclKind {
Default,
Entry,
Main,
Test,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyFunctionDecl {
pub name: Ident,
pub body: TyCodeBlock,
pub parameters: Vec<TyFunctionParameter>,
/// The [TyDecl] in which this function is implemented.
///
/// For [TyFunctionDecl]s representing _declarations_ of
/// trait or ABI provided functions and methods, this will be
/// the [TyDecl::TraitDecl] and [TyDecl::AbiDecl], respectively.
///
/// For [TyFunctionDecl]s representing _implementations_ of
/// functions and methods in trait or self impls, this will be
/// the [TyDecl::ImplSelfOrTrait].
///
/// **For [TyFunctionDecl]s representing _function applications_,
/// this will always be the [TyDecl::ImplSelfOrTrait], even if
/// the called function is a trait or ABI provided function.**
///
/// `None` for module functions.
pub implementing_type: Option<TyDecl>,
/// The [TypeId] of the type that this function is implemented for.
///
/// For [TyFunctionDecl]s representing _declarations_ of
/// trait or ABI provided functions and methods, this will be
/// the [TypeInfo::UnknownGeneric] representing the `Self` generic parameter.
///
/// For [TyFunctionDecl]s representing _implementations_ of
/// functions and methods in trait or self impls, this will be
/// the [TypeInfo] of the corresponding `Self` type, e.g., [TypeInfo::Struct].
///
/// **For [TyFunctionDecl]s representing _function applications_,
/// this will always be the [TypeInfo] of the corresponding `Self` type,
/// even if the called function is a trait or ABI provided function.**
///
/// `None` for module functions.
pub implementing_for: Option<TypeId>,
pub span: Span,
/// For module functions, this is the full call path of the function.
///
/// Otherwise, the [CallPath::prefixes] are the prefixes of the module
/// in which the defining [TyFunctionDecl] is located, and the
/// [CallPath::suffix] is the function name.
pub call_path: CallPath,
pub attributes: transform::Attributes,
pub type_parameters: Vec<TypeParameter>,
pub return_type: GenericTypeArgument,
pub visibility: Visibility,
/// Whether this function exists in another contract and requires a call to it or not.
pub is_contract_call: bool,
pub purity: Purity,
pub where_clause: Vec<(Ident, Vec<TraitConstraint>)>,
pub is_trait_method_dummy: bool,
pub is_type_check_finalized: bool,
/// !!! WARNING !!!
/// This field is currently not reliable.
/// Do not use it to check the function kind.
/// Instead, use the [Self::is_default], [Self::is_entry], [Self::is_main], and [Self::is_test] methods.
/// TODO: See: https://github.com/FuelLabs/sway/issues/7371
/// !!! WARNING !!!
pub kind: TyFunctionDeclKind,
}
impl TyDeclParsedType for TyFunctionDecl {
type ParsedType = FunctionDeclaration;
}
impl DebugWithEngines for TyFunctionDecl {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(
f,
"{}{:?}{}({}): {:?} -> {:?}",
if self.is_trait_method_dummy {
"dummy ".to_string()
} else {
"".to_string()
},
self.name,
if !self.type_parameters.is_empty() {
format!(
"<{}>",
self.type_parameters
.iter()
.map(|p| format!("{:?}", engines.help_out(p)))
.collect::<Vec<_>>()
.join(", ")
)
} else {
"".to_string()
},
self.parameters
.iter()
.map(|p| format!(
"{}: {:?} -> {:?}",
p.name.as_str(),
engines.help_out(p.type_argument.initial_type_id),
engines.help_out(p.type_argument.type_id)
))
.collect::<Vec<_>>()
.join(", "),
engines.help_out(self.return_type.initial_type_id),
engines.help_out(self.return_type.type_id),
)
}
}
impl DisplayWithEngines for TyFunctionDecl {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(
f,
"{}{}({}) -> {}",
self.name,
if !self.type_parameters.is_empty() {
format!(
"<{}>",
self.type_parameters
.iter()
.map(|p| {
let p = p
.as_type_parameter()
.expect("only works for type parameters");
format!("{}", engines.help_out(p.initial_type_id))
})
.collect::<Vec<_>>()
.join(", ")
)
} else {
"".to_string()
},
self.parameters
.iter()
.map(|p| format!(
"{}: {}",
p.name.as_str(),
engines.help_out(p.type_argument.initial_type_id)
))
.collect::<Vec<_>>()
.join(", "),
engines.help_out(self.return_type.initial_type_id),
)
}
}
impl MaterializeConstGenerics for TyFunctionDecl {
fn materialize_const_generics(
&mut self,
engines: &Engines,
handler: &Handler,
name: &str,
value: &TyExpression,
) -> Result<(), ErrorEmitted> {
for tp in self.type_parameters.iter_mut() {
match tp {
TypeParameter::Type(p) => p
.type_id
.materialize_const_generics(engines, handler, name, value)?,
TypeParameter::Const(p) if p.name.as_str() == name => match p.expr.as_ref() {
Some(v) => {
assert!(
v.as_literal_val().unwrap() as u64
== value
.extract_literal_value()
.unwrap()
.cast_value_to_u64()
.unwrap()
);
}
None => {
p.expr = Some(ConstGenericExpr::from_ty_expression(handler, value)?);
}
},
_ => {}
}
}
for param in self.parameters.iter_mut() {
param
.type_argument
.type_id
.materialize_const_generics(engines, handler, name, value)?;
}
self.return_type
.type_id
.materialize_const_generics(engines, handler, name, value)?;
self.body
.materialize_const_generics(engines, handler, name, value)
}
}
/// Rename const generics when the name inside the struct/enum declaration does not match
/// the name in the impl.
fn rename_const_generics_on_function(
handler: &Handler,
engines: &Engines,
impl_self_or_trait: &TyImplSelfOrTrait,
function: &mut TyFunctionDecl,
) {
let from = impl_self_or_trait.implementing_for.initial_type_id;
let to = impl_self_or_trait.implementing_for.type_id;
let from = engines.te().get(from);
let to = engines.te().get(to);
match (&*from, &*to) {
(
TypeInfo::Custom {
type_arguments: Some(type_arguments),
..
},
TypeInfo::Struct(s),
) => {
let decl = engines.de().get(s);
rename_const_generics_on_function_inner(
handler,
engines,
function,
type_arguments,
decl.type_parameters(),
);
}
(
TypeInfo::Custom {
type_arguments: Some(type_arguments),
..
},
TypeInfo::Enum(s),
) => {
let decl = engines.de().get(s);
rename_const_generics_on_function_inner(
handler,
engines,
function,
type_arguments,
decl.type_parameters(),
);
}
_ => (),
}
}
fn rename_const_generics_on_function_inner(
handler: &Handler,
engines: &Engines,
function: &mut TyFunctionDecl,
type_arguments: &[GenericArgument],
generic_parameters: &[TypeParameter],
) {
for a in type_arguments.iter().zip(generic_parameters.iter()) {
match (a.0, a.1) {
(GenericArgument::Type(a), TypeParameter::Const(b)) => {
// replace all references from "a.name.as_str()" to "b.name.as_str()"
let mut type_subst_map = TypeSubstMap::default();
type_subst_map.const_generics_renaming.insert(
a.call_path_tree
.as_ref()
.unwrap()
.qualified_call_path
.call_path
.suffix
.clone(),
b.name.clone(),
);
function.subst_inner(&SubstTypesContext {
handler,
engines,
type_subst_map: Some(&type_subst_map),
subst_function_body: true,
});
}
(GenericArgument::Const(a), TypeParameter::Const(b)) => {
engines
.obs()
.trace(|| format!("{:?} -> {:?}", a.expr, b.expr));
}
_ => {}
}
}
}
impl DeclRefFunction {
/// Makes method with a copy of type_id.
/// This avoids altering the type_id already in the type map.
/// Without this it is possible to retrieve a method from the type map unify its types and
/// the second time it won't be possible to retrieve the same method.
pub fn get_method_safe_to_unify(
&self,
handler: &Handler,
engines: &Engines,
type_id: TypeId,
) -> Self {
engines.obs().trace(|| {
format!(
" before get_method_safe_to_unify: {:?} {:?}",
engines.help_out(type_id),
engines.help_out(self.id())
)
});
let decl_engine = engines.de();
let original = &*decl_engine.get_function(self);
let mut method = original.clone();
if let Some(method_implementing_for) = method.implementing_for {
let mut type_id_type_subst_map = TypeSubstMap::new();
if let Some(TyDecl::ImplSelfOrTrait(t)) = method.implementing_type.clone() {
let impl_self_or_trait = &*engines.de().get(&t.decl_id);
rename_const_generics_on_function(
handler,
engines,
impl_self_or_trait,
&mut method,
);
let mut type_id_type_parameters = vec![];
let mut const_generic_parameters = BTreeMap::default();
type_id.extract_type_parameters(
handler,
engines,
0,
&mut type_id_type_parameters,
&mut const_generic_parameters,
impl_self_or_trait.implementing_for.type_id,
);
type_id_type_subst_map
.const_generics_materialization
.append(&mut const_generic_parameters);
for p in impl_self_or_trait
.impl_type_parameters
.iter()
.filter_map(|x| x.as_type_parameter())
{
let matches = type_id_type_parameters
.iter()
.filter(|(_, orig_tp)| {
engines.te().get(*orig_tp).eq(
&*engines.te().get(p.type_id),
&PartialEqWithEnginesContext::new(engines),
)
})
.collect::<Vec<_>>();
if !matches.is_empty() {
// Adds type substitution for first match only as we can apply only one.
type_id_type_subst_map.insert(p.type_id, matches[0].0);
} else if engines
.te()
.get(impl_self_or_trait.implementing_for.initial_type_id)
.eq(
&*engines.te().get(p.initial_type_id),
&PartialEqWithEnginesContext::new(engines),
)
{
type_id_type_subst_map.insert(p.type_id, type_id);
}
}
}
// Duplicate arguments to avoid changing TypeId inside TraitMap
for parameter in method.parameters.iter_mut() {
parameter.type_argument.type_id = engines
.te()
.duplicate(engines, parameter.type_argument.type_id)
}
let mut method_type_subst_map = TypeSubstMap::new();
method_type_subst_map.extend(&type_id_type_subst_map);
method_type_subst_map.insert(method_implementing_for, type_id);
method.subst(&SubstTypesContext::new(
handler,
engines,
&method_type_subst_map,
true,
));
let r = engines
.de()
.insert(
method.clone(),
engines.de().get_parsed_decl_id(self.id()).as_ref(),
)
.with_parent(decl_engine, self.id().into());
engines.obs().trace(|| {
format!(
" after get_method_safe_to_unify: {:?}; {:?}",
engines.help_out(type_id),
engines.help_out(r.id())
)
});
return r;
}
engines.obs().trace(|| {
format!(
" after get_method_safe_to_unify: {:?}; {:?}",
engines.help_out(type_id),
engines.help_out(self.id())
)
});
self.clone()
}
}
impl Named for TyFunctionDecl {
fn name(&self) -> &Ident {
&self.name
}
}
impl IsConcrete for TyFunctionDecl {
fn is_concrete(&self, handler: &Handler, engines: &Engines) -> bool {
self.type_parameters
.iter()
.all(|tp| tp.is_concrete(handler, engines))
&& self
.return_type
.type_id
.is_concrete(engines, TreatNumericAs::Concrete)
&& self.parameters().iter().all(|t| {
t.type_argument
.type_id
.is_concrete(engines, TreatNumericAs::Concrete)
})
}
}
impl declaration::FunctionSignature for TyFunctionDecl {
fn parameters(&self) -> &Vec<TyFunctionParameter> {
&self.parameters
}
fn return_type(&self) -> &GenericTypeArgument {
&self.return_type
}
}
impl EqWithEngines for TyFunctionDecl {}
impl PartialEqWithEngines for TyFunctionDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.body.eq(&other.body, ctx)
&& self.parameters.eq(&other.parameters, ctx)
&& self.return_type.eq(&other.return_type, ctx)
&& self.type_parameters.eq(&other.type_parameters, ctx)
&& self.visibility == other.visibility
&& self.is_contract_call == other.is_contract_call
&& self.purity == other.purity
&& self.call_path == other.call_path
&& self.span == other.span
}
}
impl HashWithEngines for TyFunctionDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyFunctionDecl {
name,
body,
parameters,
return_type,
type_parameters,
visibility,
is_contract_call,
purity,
call_path,
span,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
attributes: _,
implementing_type: _,
implementing_for: _,
where_clause: _,
is_trait_method_dummy: _,
is_type_check_finalized: _,
kind: _,
} = self;
name.hash(state);
body.hash(state, engines);
parameters.hash(state, engines);
return_type.hash(state, engines);
type_parameters.hash(state, engines);
visibility.hash(state);
is_contract_call.hash(state);
purity.hash(state);
call_path.hash(state);
span.hash(state);
}
}
impl SubstTypes for TyFunctionDecl {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
let changes = if ctx.subst_function_body {
has_changes! {
self.type_parameters.subst(ctx);
self.parameters.subst(ctx);
self.return_type.subst(ctx);
self.body.subst(ctx);
self.implementing_for.subst(ctx);
}
} else {
has_changes! {
self.type_parameters.subst(ctx);
self.parameters.subst(ctx);
self.return_type.subst(ctx);
self.implementing_for.subst(ctx);
}
};
if let Some(map) = ctx.type_subst_map.as_ref() {
let handler = Handler::default();
for (name, value) in &map.const_generics_materialization {
let _ = self.materialize_const_generics(ctx.engines, &handler, name, value);
}
HasChanges::Yes
} else {
changes
}
}
}
impl ReplaceDecls for TyFunctionDecl {
fn replace_decls_inner(
&mut self,
decl_mapping: &DeclMapping,
handler: &Handler,
ctx: &mut TypeCheckContext,
) -> Result<bool, ErrorEmitted> {
let mut func_ctx = ctx.by_ref().with_self_type(self.implementing_for);
self.body
.replace_decls(decl_mapping, handler, &mut func_ctx)
}
}
impl Spanned for TyFunctionDecl {
fn span(&self) -> Span {
self.span.clone()
}
}
impl MonomorphizeHelper for TyFunctionDecl {
fn type_parameters(&self) -> &[TypeParameter] {
&self.type_parameters
}
fn name(&self) -> &Ident {
&self.name
}
fn has_self_type_param(&self) -> bool {
false
}
}
impl CollectTypesMetadata for TyFunctionDecl {
fn collect_types_metadata(
&self,
handler: &Handler,
ctx: &mut CollectTypesMetadataContext,
) -> Result<Vec<TypeMetadata>, ErrorEmitted> {
let mut body = vec![];
for content in self.body.contents.iter() {
body.append(&mut content.collect_types_metadata(handler, ctx)?);
}
body.append(
&mut self
.return_type
.type_id
.collect_types_metadata(handler, ctx)?,
);
for p in self.type_parameters.iter() {
let p = p
.as_type_parameter()
.expect("only works for type parameters");
body.append(&mut p.type_id.collect_types_metadata(handler, ctx)?);
}
for param in self.parameters.iter() {
body.append(
&mut param
.type_argument
.type_id
.collect_types_metadata(handler, ctx)?,
);
}
Ok(body)
}
}
impl TyFunctionDecl {
pub(crate) fn set_implementing_type(&mut self, decl: TyDecl) {
self.implementing_type = Some(decl);
}
/// Used to create a stubbed out function when the function fails to
/// compile, preventing cascading namespace errors.
pub(crate) fn error(decl: &parsed::FunctionDeclaration) -> TyFunctionDecl {
let parsed::FunctionDeclaration {
name,
return_type,
span,
visibility,
purity,
where_clause,
kind,
..
} = decl;
TyFunctionDecl {
purity: *purity,
name: name.clone(),
body: <_>::default(),
implementing_type: None,
implementing_for: None,
span: span.clone(),
call_path: CallPath::from(Ident::dummy()),
attributes: Default::default(),
is_contract_call: false,
parameters: Default::default(),
visibility: *visibility,
return_type: return_type.clone(),
type_parameters: Default::default(),
where_clause: where_clause.clone(),
is_trait_method_dummy: false,
is_type_check_finalized: true,
kind: match kind {
FunctionDeclarationKind::Default => TyFunctionDeclKind::Default,
FunctionDeclarationKind::Entry => TyFunctionDeclKind::Entry,
FunctionDeclarationKind::Test => TyFunctionDeclKind::Test,
FunctionDeclarationKind::Main => TyFunctionDeclKind::Main,
},
}
}
/// If there are parameters, join their spans. Otherwise, use the fn name span.
pub(crate) fn parameters_span(&self) -> Span {
if !self.parameters.is_empty() {
self.parameters.iter().fold(
// TODO: Use Span::join_all().
self.parameters[0].name.span(),
|acc, TyFunctionParameter { type_argument, .. }| {
Span::join(acc, &type_argument.span)
},
)
} else {
self.name.span()
}
}
pub fn to_fn_selector_value_untruncated(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<Vec<u8>, ErrorEmitted> {
let mut hasher = Sha256::new();
let data = self.to_selector_name(handler, engines)?;
hasher.update(data);
let hash = hasher.finalize();
Ok(hash.to_vec())
}
/// Converts a [TyFunctionDecl] into a value that is to be used in contract function
/// selectors.
/// Hashes the name and parameters using SHA256, and then truncates to four bytes.
pub fn to_fn_selector_value(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<[u8; 4], ErrorEmitted> {
let hash = self.to_fn_selector_value_untruncated(handler, engines)?;
// 4 bytes truncation via copying into a 4 byte buffer
let mut buf = [0u8; 4];
buf.copy_from_slice(&hash[..4]);
Ok(buf)
}
pub fn to_selector_name(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<String, ErrorEmitted> {
let named_params = self
.parameters
.iter()
.map(|TyFunctionParameter { type_argument, .. }| {
engines
.te()
.to_typeinfo(type_argument.type_id, &type_argument.span)
.expect("unreachable I think?")
.to_selector_name(handler, engines, &type_argument.span)
})
.filter_map(|name| name.ok())
.collect::<Vec<String>>();
Ok(format!(
"{}({})",
self.name.as_str(),
named_params.join(","),
))
}
pub fn is_default(&self) -> bool {
// TODO: Properly implement `TyFunctionDecl::kind` and match kind to `Default`.
// See: https://github.com/FuelLabs/sway/issues/7371
!(self.is_entry() || self.is_main() || self.is_test())
}
/// Whether or not this function is the default entry point.
pub fn is_entry(&self) -> bool {
matches!(self.kind, TyFunctionDeclKind::Entry)
}
pub fn is_main(&self) -> bool {
matches!(self.kind, TyFunctionDeclKind::Main)
}
/// Whether or not this function is a unit test, i.e. decorated with `#[test]`.
pub fn is_test(&self) -> bool {
// TODO: Properly implement `TyFunctionDecl::kind` and match kind to `Test`.
// See: https://github.com/FuelLabs/sway/issues/7371
self.attributes.has_any_of_kind(AttributeKind::Test)
}
pub fn inline(&self) -> Option<Inline> {
self.attributes.inline()
}
pub fn trace(&self) -> Option<Trace> {
self.attributes.trace()
}
pub fn is_fallback(&self) -> bool {
self.attributes.has_any_of_kind(AttributeKind::Fallback)
}
/// Whether or not this function is a constructor for the type given by `type_id`.
///
/// Returns `Some(true)` if the function is surely the constructor and `Some(false)` if
/// it is surely not a constructor, and `None` if it cannot decide.
pub fn is_constructor(&self, engines: &Engines, type_id: TypeId) -> Option<bool> {
if self
.parameters
.first()
.map(|param| param.is_self())
.unwrap_or_default()
{
return Some(false);
};
match &self.implementing_type {
Some(TyDecl::ImplSelfOrTrait(t)) => {
let unify_check = UnifyCheck::non_dynamic_equality(engines);
let implementing_for = engines.de().get(&t.decl_id).implementing_for.type_id;
// TODO: Implement the check in detail for all possible cases (e.g. trait impls for generics etc.)
// and return just the definite `bool` and not `Option<bool>`.
// That would be too much effort at the moment for the immediate practical need of
// error reporting where we suggest obvious most common constructors
// that will be found using this simple check.
if unify_check.check(type_id, implementing_for)
&& unify_check.check(type_id, self.return_type.type_id)
{
Some(true)
} else {
None
}
}
_ => Some(false),
}
}
pub fn is_from_blanket_impl(&self, engines: &Engines) -> bool {
if let Some(TyDecl::ImplSelfOrTrait(existing_impl_trait)) = &self.implementing_type {
let existing_trait_decl = engines
.de()
.get_impl_self_or_trait(&existing_impl_trait.decl_id);
if !existing_trait_decl.impl_type_parameters.is_empty()
&& matches!(
*engines
.te()
.get(existing_trait_decl.implementing_for.type_id),
TypeInfo::UnknownGeneric { .. }
)
{
return true;
}
}
false
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TyFunctionParameter {
pub name: Ident,
pub is_reference: bool,
pub is_mutable: bool,
pub mutability_span: Span,
pub type_argument: GenericTypeArgument,
}
impl EqWithEngines for TyFunctionParameter {}
impl PartialEqWithEngines for TyFunctionParameter {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.type_argument.eq(&other.type_argument, ctx)
&& self.is_reference == other.is_reference
&& self.is_mutable == other.is_mutable
}
}
impl HashWithEngines for TyFunctionParameter {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyFunctionParameter {
name,
is_reference,
is_mutable,
type_argument,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
mutability_span: _,
} = self;
name.hash(state);
type_argument.hash(state, engines);
is_reference.hash(state);
is_mutable.hash(state);
}
}
impl SubstTypes for TyFunctionParameter {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
self.type_argument.type_id.subst(ctx)
}
}
impl TyFunctionParameter {
pub fn is_self(&self) -> bool {
self.name.as_str() == "self"
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum TyFunctionSigTypeParameter {
Type(TypeId),
Const(ConstGenericExpr),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TyFunctionSig {
pub return_type: TypeId,
pub parameters: Vec<TypeId>,
pub type_parameters: Vec<TyFunctionSigTypeParameter>,
}
impl DisplayWithEngines for TyFunctionSig {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(f, "{:?}", engines.help_out(self))
}
}
impl DebugWithEngines for TyFunctionSig {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
let tp_str = if self.type_parameters.is_empty() {
"".to_string()
} else {
format!(
"<{}>",
self.type_parameters
.iter()
.map(|p| match p {
TyFunctionSigTypeParameter::Type(t) => format!("{:?}", engines.help_out(t)),
TyFunctionSigTypeParameter::Const(expr) =>
format!("{:?}", engines.help_out(expr)),
})
.collect::<Vec<_>>()
.join(", "),
)
};
write!(
f,
"fn{}({}) -> {}",
tp_str,
self.parameters
.iter()
.map(|p| format!("{}", engines.help_out(p)))
.collect::<Vec<_>>()
.join(", "),
engines.help_out(self.return_type),
)
}
}
impl TyFunctionSig {
pub fn from_fn_decl(fn_decl: &TyFunctionDecl) -> Self {
Self {
return_type: fn_decl.return_type.type_id,
parameters: fn_decl
.parameters
.iter()
.map(|p| p.type_argument.type_id)
.collect::<Vec<_>>(),
type_parameters: fn_decl
.type_parameters
.iter()
.map(|x| match x {
TypeParameter::Type(p) => TyFunctionSigTypeParameter::Type(p.type_id),
TypeParameter::Const(p) => {
let expr = ConstGenericExpr::AmbiguousVariableExpression {
ident: p.name.clone(),
decl: None,
};
TyFunctionSigTypeParameter::Const(p.expr.clone().unwrap_or(expr))
}
})
.collect(),
}
}
pub fn is_concrete(&self, engines: &Engines) -> bool {
self.return_type
.is_concrete(engines, TreatNumericAs::Concrete)
&& self
.parameters
.iter()
.all(|p| p.is_concrete(engines, TreatNumericAs::Concrete))
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/storage.rs | sway-core/src/language/ty/declaration/storage.rs | use crate::{
engine_threading::*,
ir_generation::storage::get_storage_key_string,
language::parsed::StorageDeclaration,
transform::{self},
ty::*,
type_system::*,
Namespace,
};
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use sway_error::{
error::{CompileError, StructFieldUsageContext},
handler::{ErrorEmitted, Handler},
};
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyStorageDecl {
pub fields: Vec<TyStorageField>,
pub span: Span,
pub attributes: transform::Attributes,
pub storage_keyword: Ident,
}
impl TyDeclParsedType for TyStorageDecl {
type ParsedType = StorageDeclaration;
}
impl Named for TyStorageDecl {
fn name(&self) -> &Ident {
&self.storage_keyword
}
}
impl EqWithEngines for TyStorageDecl {}
impl PartialEqWithEngines for TyStorageDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.fields.eq(&other.fields, ctx) && self.attributes == other.attributes
}
}
impl HashWithEngines for TyStorageDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyStorageDecl {
fields,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
attributes: _,
storage_keyword: _,
} = self;
fields.hash(state, engines);
}
}
impl Spanned for TyStorageDecl {
fn span(&self) -> Span {
self.span.clone()
}
}
impl TyStorageDecl {
/// Given a path that consists of `fields`, where the first field is one of the storage fields,
/// find the type information of all the elements in the path and return it as a [TyStorageAccess].
///
/// The first element in the `fields` must be one of the storage fields.
/// The last element in the `fields` can, but must not be, a struct.
/// All the elements in between must be structs.
///
/// An error is returned if the above constraints are violated or if the access to the struct fields
/// fails. E.g, if the struct field does not exists or is an inaccessible private field.
#[allow(clippy::too_many_arguments)]
pub fn apply_storage_load(
&self,
handler: &Handler,
engines: &Engines,
namespace: &Namespace,
namespace_names: &[Ident],
fields: &[Ident],
storage_fields: &[TyStorageField],
storage_keyword_span: Span,
) -> Result<(TyStorageAccess, TypeId), ErrorEmitted> {
let type_engine = engines.te();
let decl_engine = engines.de();
// The resulting storage access descriptors, built on the go as we move through the `fields`.
let mut access_descriptors = vec![];
// The field we've analyzed before the current field we are on, and its type id.
let mut previous_field: &Ident;
let mut previous_field_type_id: TypeId;
let (first_field, remaining_fields) = fields.split_first().expect(
"Having at least one element in the storage load is guaranteed by the grammar.",
);
let (initial_field_type, initial_field_key, initial_field_name) =
match storage_fields.iter().find(|sf| {
&sf.name == first_field
&& sf.namespace_names.len() == namespace_names.len()
&& sf
.namespace_names
.iter()
.zip(namespace_names.iter())
.all(|(n1, n2)| n1 == n2)
}) {
Some(TyStorageField {
type_argument,
key_expression,
name,
..
}) => (type_argument.type_id, key_expression, name),
None => {
return Err(handler.emit_err(CompileError::StorageFieldDoesNotExist {
field_name: first_field.into(),
available_fields: storage_fields
.iter()
.map(|sf| (sf.namespace_names.clone(), sf.name.clone()))
.collect(),
storage_decl_span: self.span(),
}));
}
};
access_descriptors.push(TyStorageAccessDescriptor {
name: first_field.clone(),
type_id: initial_field_type,
span: first_field.span(),
});
previous_field = first_field;
previous_field_type_id = initial_field_type;
// Storage cannot contain references, so there is no need for checking
// if the declaration is a reference to a struct. References can still
// be erroneously declared in the storage, and the type behind a concrete
// field access might be a reference to struct, but we do not treat that
// as a special case but just another one "not a struct".
// The FieldAccessOnNonStruct error message will explain that in the case
// of storage access, fields can be accessed only on structs.
let get_struct_decl = |type_id: TypeId| match &*type_engine.get(type_id) {
TypeInfo::Struct(decl_ref) => Some(decl_engine.get_struct(decl_ref)),
_ => None,
};
let mut struct_field_names = vec![];
for field in remaining_fields {
match get_struct_decl(previous_field_type_id) {
Some(struct_decl) => {
let (struct_can_be_changed, is_public_struct_access) =
StructAccessInfo::get_info(engines, &struct_decl, namespace).into();
match struct_decl.find_field(field) {
Some(struct_field) => {
if is_public_struct_access && struct_field.is_private() {
return Err(handler.emit_err(CompileError::StructFieldIsPrivate {
field_name: field.into(),
struct_name: struct_decl.call_path.suffix.clone(),
field_decl_span: struct_field.name.span(),
struct_can_be_changed,
usage_context: StructFieldUsageContext::StorageAccess,
}));
}
// Everything is fine. Push the storage access descriptor and move to the next field.
let current_field_type_id = struct_field.type_argument.type_id;
access_descriptors.push(TyStorageAccessDescriptor {
name: field.clone(),
type_id: current_field_type_id,
span: field.span(),
});
struct_field_names.push(field.as_str().to_string());
previous_field = field;
previous_field_type_id = current_field_type_id;
}
None => {
// Since storage cannot be passed to other modules, the access
// is always in the module of the storage declaration.
// If the struct cannot be instantiated in this module at all,
// we will just show the error, without any additional help lines
// showing available fields or anything.
// Note that if the struct is empty it can always be instantiated.
let struct_can_be_instantiated =
!is_public_struct_access || !struct_decl.has_private_fields();
let available_fields = if struct_can_be_instantiated {
struct_decl.accessible_fields_names(is_public_struct_access)
} else {
vec![]
};
return Err(handler.emit_err(CompileError::StructFieldDoesNotExist {
field_name: field.into(),
available_fields,
is_public_struct_access,
struct_name: struct_decl.call_path.suffix.clone(),
struct_decl_span: struct_decl.span(),
struct_is_empty: struct_decl.is_empty(),
usage_context: StructFieldUsageContext::StorageAccess,
}));
}
}
}
None => {
return Err(handler.emit_err(CompileError::FieldAccessOnNonStruct {
actually: engines.help_out(previous_field_type_id).to_string(),
storage_variable: Some(previous_field.to_string()),
field_name: field.into(),
span: previous_field.span(),
}))
}
};
}
let return_type = access_descriptors[access_descriptors.len() - 1].type_id;
Ok((
TyStorageAccess {
fields: access_descriptors,
key_expression: initial_field_key.clone().map(Box::new),
storage_field_names: namespace_names
.iter()
.map(|n| n.as_str().to_string())
.chain(vec![initial_field_name.as_str().to_string()])
.collect(),
struct_field_names,
storage_keyword_span,
},
return_type,
))
}
}
impl Spanned for TyStorageField {
fn span(&self) -> Span {
self.span.clone()
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyStorageField {
pub name: Ident,
pub namespace_names: Vec<Ident>,
pub key_expression: Option<TyExpression>,
pub type_argument: GenericTypeArgument,
pub initializer: TyExpression,
pub(crate) span: Span,
pub attributes: transform::Attributes,
}
impl TyStorageField {
/// Returns the full name of the [TyStorageField], consisting
/// of its name preceded by its full namespace path.
/// E.g., "storage::ns1::ns1.name".
pub fn full_name(&self) -> String {
get_storage_key_string(
&self
.namespace_names
.iter()
.map(|i| i.as_str().to_string())
.chain(vec![self.name.as_str().to_string()])
.collect::<Vec<_>>(),
)
}
}
impl EqWithEngines for TyStorageField {}
impl PartialEqWithEngines for TyStorageField {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.namespace_names.eq(&other.namespace_names)
&& self.type_argument.eq(&other.type_argument, ctx)
&& self.initializer.eq(&other.initializer, ctx)
}
}
impl HashWithEngines for TyStorageField {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyStorageField {
name,
namespace_names,
key_expression,
type_argument,
initializer,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
attributes: _,
} = self;
name.hash(state);
namespace_names.hash(state);
key_expression.hash(state, engines);
type_argument.hash(state, engines);
initializer.hash(state, engines);
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/configurable.rs | sway-core/src/language/ty/declaration/configurable.rs | use crate::{
decl_engine::{DeclId, DeclMapping, DeclRef, ReplaceDecls},
engine_threading::*,
has_changes,
language::{parsed::ConfigurableDeclaration, ty::*, CallPath, Visibility},
semantic_analysis::TypeCheckContext,
transform,
type_system::*,
};
use serde::{Deserialize, Serialize};
use std::{
fmt,
hash::{Hash, Hasher},
};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyConfigurableDecl {
pub call_path: CallPath,
pub value: Option<TyExpression>,
pub visibility: Visibility,
pub attributes: transform::Attributes,
pub return_type: TypeId,
pub type_ascription: GenericTypeArgument,
pub span: Span,
// Only encoding v1 has a decode_fn
pub decode_fn: Option<DeclRef<DeclId<TyFunctionDecl>>>,
}
impl TyDeclParsedType for TyConfigurableDecl {
type ParsedType = ConfigurableDeclaration;
}
impl DebugWithEngines for TyConfigurableDecl {
fn fmt(&self, f: &mut fmt::Formatter<'_>, _engines: &Engines) -> fmt::Result {
write!(f, "{}", self.call_path)
}
}
impl EqWithEngines for TyConfigurableDecl {}
impl PartialEqWithEngines for TyConfigurableDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let type_engine = ctx.engines().te();
self.call_path == other.call_path
&& self.value.eq(&other.value, ctx)
&& self.visibility == other.visibility
&& self.type_ascription.eq(&other.type_ascription, ctx)
&& type_engine
.get(self.return_type)
.eq(&type_engine.get(other.return_type), ctx)
}
}
impl HashWithEngines for TyConfigurableDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let type_engine = engines.te();
let TyConfigurableDecl {
call_path,
value,
visibility,
return_type,
type_ascription,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
attributes: _,
span: _,
decode_fn: _, // this is defined entirely by the type ascription
} = self;
call_path.hash(state);
value.hash(state, engines);
visibility.hash(state);
type_engine.get(*return_type).hash(state, engines);
type_ascription.hash(state, engines);
}
}
impl Named for TyConfigurableDecl {
fn name(&self) -> &Ident {
&self.call_path.suffix
}
}
impl Spanned for TyConfigurableDecl {
fn span(&self) -> Span {
self.span.clone()
}
}
impl SubstTypes for TyConfigurableDecl {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
self.return_type.subst(ctx);
self.type_ascription.subst(ctx);
self.value.subst(ctx);
}
}
}
impl ReplaceDecls for TyConfigurableDecl {
fn replace_decls_inner(
&mut self,
decl_mapping: &DeclMapping,
handler: &Handler,
ctx: &mut TypeCheckContext,
) -> Result<bool, ErrorEmitted> {
if let Some(expr) = &mut self.value {
expr.replace_decls(decl_mapping, handler, ctx)
} else {
Ok(false)
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/impl_trait.rs | sway-core/src/language/ty/declaration/impl_trait.rs | use super::{TyAbiDecl, TyDeclParsedType, TyTraitDecl, TyTraitItem};
use crate::{
decl_engine::{DeclId, DeclRefMixedInterface, InterfaceDeclId},
engine_threading::*,
has_changes,
language::{parsed::ImplSelfOrTrait, CallPath},
type_system::*,
};
use serde::{Deserialize, Serialize};
use std::{
fmt::Formatter,
hash::{Hash, Hasher},
};
use sway_types::{Ident, Named, Span, Spanned};
pub type TyImplItem = TyTraitItem;
/// Self impl, e.g.: `impl<A> Type<A>`,
/// or trait impl, e.g.: `impl<A, B, C> Trait<A, B> for Type<C>`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyImplSelfOrTrait {
pub impl_type_parameters: Vec<TypeParameter>,
pub trait_name: CallPath,
pub trait_type_arguments: Vec<GenericArgument>,
pub items: Vec<TyImplItem>,
pub supertrait_items: Vec<TyImplItem>,
pub trait_decl_ref: Option<DeclRefMixedInterface>,
pub implementing_for: GenericTypeArgument,
pub span: Span,
}
impl TyImplSelfOrTrait {
pub fn is_impl_contract(&self, te: &TypeEngine) -> bool {
matches!(&*te.get(self.implementing_for.type_id), TypeInfo::Contract)
}
pub fn is_impl_self(&self) -> bool {
self.trait_decl_ref.is_none()
}
pub fn is_impl_trait(&self) -> bool {
match &self.trait_decl_ref {
Some(decl_ref) => matches!(decl_ref.id(), InterfaceDeclId::Trait(_)),
_ => false,
}
}
pub fn is_impl_abi(&self) -> bool {
match &self.trait_decl_ref {
Some(decl_ref) => matches!(decl_ref.id(), InterfaceDeclId::Abi(_)),
_ => false,
}
}
/// Returns [DeclId] of the trait implemented by `self`, if `self` implements a trait.
pub fn implemented_trait_decl_id(&self) -> Option<DeclId<TyTraitDecl>> {
match &self.trait_decl_ref {
Some(decl_ref) => match &decl_ref.id() {
InterfaceDeclId::Trait(decl_id) => Some(*decl_id),
InterfaceDeclId::Abi(_) => None,
},
_ => None,
}
}
/// Returns [DeclId] of the ABI implemented by `self`, if `self` implements an ABI for a contract.
pub fn implemented_abi_decl_id(&self) -> Option<DeclId<TyAbiDecl>> {
match &self.trait_decl_ref {
Some(decl_ref) => match &decl_ref.id() {
InterfaceDeclId::Abi(decl_id) => Some(*decl_id),
InterfaceDeclId::Trait(_) => None,
},
_ => None,
}
}
}
impl TyDeclParsedType for TyImplSelfOrTrait {
type ParsedType = ImplSelfOrTrait;
}
impl Named for TyImplSelfOrTrait {
fn name(&self) -> &Ident {
&self.trait_name.suffix
}
}
impl Spanned for TyImplSelfOrTrait {
fn span(&self) -> Span {
self.span.clone()
}
}
impl EqWithEngines for TyImplSelfOrTrait {}
impl PartialEqWithEngines for TyImplSelfOrTrait {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.impl_type_parameters
.eq(&other.impl_type_parameters, ctx)
&& self.trait_name == other.trait_name
&& self
.trait_type_arguments
.eq(&other.trait_type_arguments, ctx)
&& self.items.eq(&other.items, ctx)
&& self.implementing_for.eq(&other.implementing_for, ctx)
&& self.trait_decl_ref.eq(&other.trait_decl_ref, ctx)
}
}
impl HashWithEngines for TyImplSelfOrTrait {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyImplSelfOrTrait {
impl_type_parameters,
trait_name,
trait_type_arguments,
items,
implementing_for,
trait_decl_ref,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
supertrait_items: _,
} = self;
trait_name.hash(state);
impl_type_parameters.hash(state, engines);
trait_type_arguments.hash(state, engines);
items.hash(state, engines);
implementing_for.hash(state, engines);
trait_decl_ref.hash(state, engines);
}
}
impl SubstTypes for TyImplSelfOrTrait {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
self.impl_type_parameters.subst(ctx);
self.implementing_for.subst_inner(ctx);
self.items.subst(ctx);
}
}
}
impl DebugWithEngines for TyImplSelfOrTrait {
fn fmt(&self, f: &mut Formatter<'_>, engines: &Engines) -> std::fmt::Result {
if let Some(t) = self.trait_decl_ref.as_ref() {
write!(
f,
"impl<> {:?} for {:?} -> {:?}",
t.name().as_str(),
engines.help_out(self.implementing_for.initial_type_id),
engines.help_out(self.implementing_for.type_id),
)
} else {
write!(
f,
"impl<> {:?} -> {:?}",
engines.help_out(self.implementing_for.initial_type_id),
engines.help_out(self.implementing_for.type_id),
)
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/const_generic.rs | sway-core/src/language/ty/declaration/const_generic.rs | use crate::{
decl_engine::MaterializeConstGenerics,
engine_threading::HashWithEngines,
has_changes,
language::{parsed::ConstGenericDeclaration, ty::TyExpression, CallPath},
semantic_analysis::{TypeCheckAnalysis, TypeCheckAnalysisContext},
Engines, HasChanges, SubstTypes, TypeId,
};
use serde::{Deserialize, Serialize};
use std::hash::{Hash as _, Hasher};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::{Ident, Named, Span, Spanned};
use super::TyDeclParsedType;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyConstGenericDecl {
pub call_path: CallPath,
pub return_type: TypeId,
pub span: Span,
pub value: Option<TyExpression>,
}
impl HashWithEngines for TyConstGenericDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let type_engine = engines.te();
let TyConstGenericDecl {
call_path,
return_type,
span: _,
value: _,
} = self;
call_path.hash(state);
type_engine.get(*return_type).hash(state, engines);
}
}
impl SubstTypes for TyConstGenericDecl {
fn subst_inner(&mut self, ctx: &crate::SubstTypesContext) -> crate::HasChanges {
has_changes! {
self.return_type.subst(ctx);
if let Some(v) = ctx.get_renamed_const_generic(&self.call_path.suffix) {
self.call_path.suffix = v.clone();
HasChanges::Yes
} else {
HasChanges::No
};
}
}
}
impl MaterializeConstGenerics for TyConstGenericDecl {
fn materialize_const_generics(
&mut self,
_engines: &crate::Engines,
_handler: &Handler,
name: &str,
value: &TyExpression,
) -> Result<(), ErrorEmitted> {
if self.call_path.suffix.as_str() == name {
match self.value.as_ref() {
Some(v) => {
assert!(
v.extract_literal_value()
.unwrap()
.cast_value_to_u64()
.unwrap()
== value
.extract_literal_value()
.unwrap()
.cast_value_to_u64()
.unwrap(),
"{v:?} {value:?}",
);
}
None => {
self.value = Some(value.clone());
}
}
}
Ok(())
}
}
impl TypeCheckAnalysis for TyConstGenericDecl {
fn type_check_analyze(
&self,
_handler: &Handler,
_ctx: &mut TypeCheckAnalysisContext,
) -> Result<(), ErrorEmitted> {
Ok(())
}
}
impl Named for TyConstGenericDecl {
fn name(&self) -> &Ident {
&self.call_path.suffix
}
}
impl Spanned for TyConstGenericDecl {
fn span(&self) -> Span {
self.span.clone()
}
}
impl TyDeclParsedType for TyConstGenericDecl {
type ParsedType = ConstGenericDeclaration;
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/mod.rs | sway-core/src/language/ty/declaration/mod.rs | mod abi;
mod configurable;
mod const_generic;
mod constant;
#[allow(clippy::module_inception)]
mod declaration;
mod r#enum;
mod function;
mod impl_trait;
mod storage;
mod r#struct;
mod r#trait;
mod trait_fn;
mod trait_type;
mod type_alias;
mod variable;
pub use abi::*;
pub use configurable::*;
pub use const_generic::*;
pub use constant::*;
pub use declaration::*;
pub use function::*;
pub use impl_trait::*;
pub use r#enum::*;
pub use r#struct::*;
pub use r#trait::*;
pub use storage::*;
pub use trait_fn::*;
pub use trait_type::*;
pub use type_alias::*;
pub use variable::*;
use crate::ast_elements::type_argument::GenericTypeArgument;
pub trait FunctionSignature {
fn parameters(&self) -> &Vec<TyFunctionParameter>;
fn return_type(&self) -> &GenericTypeArgument;
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/constant.rs | sway-core/src/language/ty/declaration/constant.rs | use crate::{
decl_engine::{DeclMapping, MaterializeConstGenerics, ReplaceDecls},
engine_threading::*,
has_changes,
language::{parsed::ConstantDeclaration, ty::*, CallPath, Visibility},
semantic_analysis::TypeCheckContext,
transform,
type_system::*,
};
use serde::{Deserialize, Serialize};
use std::{
fmt,
hash::{Hash, Hasher},
};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyConstantDecl {
pub call_path: CallPath,
pub value: Option<TyExpression>,
pub visibility: Visibility,
pub attributes: transform::Attributes,
pub return_type: TypeId,
pub type_ascription: GenericTypeArgument,
pub span: Span,
}
impl TyDeclParsedType for TyConstantDecl {
type ParsedType = ConstantDeclaration;
}
impl DebugWithEngines for TyConstantDecl {
fn fmt(&self, f: &mut fmt::Formatter<'_>, _engines: &Engines) -> fmt::Result {
write!(f, "{}", self.call_path)
}
}
impl EqWithEngines for TyConstantDecl {}
impl PartialEqWithEngines for TyConstantDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let type_engine = ctx.engines().te();
self.call_path == other.call_path
&& self.value.eq(&other.value, ctx)
&& self.visibility == other.visibility
&& self.type_ascription.eq(&other.type_ascription, ctx)
&& type_engine
.get(self.return_type)
.eq(&type_engine.get(other.return_type), ctx)
}
}
impl HashWithEngines for TyConstantDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let type_engine = engines.te();
let TyConstantDecl {
call_path,
value,
visibility,
return_type,
type_ascription,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
attributes: _,
span: _,
} = self;
call_path.hash(state);
value.hash(state, engines);
visibility.hash(state);
type_engine.get(*return_type).hash(state, engines);
type_ascription.hash(state, engines);
}
}
impl Named for TyConstantDecl {
fn name(&self) -> &Ident {
&self.call_path.suffix
}
}
impl Spanned for TyConstantDecl {
fn span(&self) -> Span {
self.span.clone()
}
}
impl IsConcrete for TyConstantDecl {
fn is_concrete(&self, _: &Handler, engines: &Engines) -> bool {
self.return_type
.is_concrete(engines, TreatNumericAs::Concrete)
}
}
impl SubstTypes for TyConstantDecl {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
self.return_type.subst(ctx);
self.type_ascription.subst(ctx);
self.value.subst(ctx);
}
}
}
impl ReplaceDecls for TyConstantDecl {
fn replace_decls_inner(
&mut self,
decl_mapping: &DeclMapping,
handler: &Handler,
ctx: &mut TypeCheckContext,
) -> Result<bool, ErrorEmitted> {
if let Some(expr) = &mut self.value {
expr.replace_decls(decl_mapping, handler, ctx)
} else {
Ok(false)
}
}
}
impl MaterializeConstGenerics for TyConstantDecl {
fn materialize_const_generics(
&mut self,
engines: &Engines,
handler: &Handler,
name: &str,
value: &TyExpression,
) -> Result<(), ErrorEmitted> {
if let Some(v) = self.value.as_mut() {
v.materialize_const_generics(engines, handler, name, value)?;
}
self.return_type
.materialize_const_generics(engines, handler, name, value)?;
self.type_ascription
.type_id
.materialize_const_generics(engines, handler, name, value)?;
Ok(())
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/trait_fn.rs | sway-core/src/language/ty/declaration/trait_fn.rs | use std::{
fmt,
hash::{Hash, Hasher},
};
use monomorphization::MonomorphizeHelper;
use sway_error::handler::Handler;
use sway_types::{Ident, Named, Span, Spanned};
use crate::{
ast_elements::type_argument::GenericTypeArgument,
engine_threading::*,
has_changes,
language::{parsed::TraitFn, ty::*, Purity},
transform,
type_system::*,
};
#[derive(Clone, Debug)]
pub struct TyTraitFn {
pub name: Ident,
pub(crate) span: Span,
pub(crate) purity: Purity,
pub parameters: Vec<TyFunctionParameter>,
pub return_type: GenericTypeArgument,
pub attributes: transform::Attributes,
}
impl TyDeclParsedType for TyTraitFn {
type ParsedType = TraitFn;
}
impl DebugWithEngines for TyTraitFn {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(
f,
"{:?}({}):{}",
self.name,
self.parameters
.iter()
.map(|p| format!(
"{}:{}",
p.name.as_str(),
engines.help_out(p.type_argument.initial_type_id)
))
.collect::<Vec<_>>()
.join(", "),
engines.help_out(self.return_type.initial_type_id),
)
}
}
impl Named for TyTraitFn {
fn name(&self) -> &Ident {
&self.name
}
}
impl Spanned for TyTraitFn {
fn span(&self) -> Span {
self.span.clone()
}
}
impl IsConcrete for TyTraitFn {
fn is_concrete(&self, handler: &Handler, engines: &Engines) -> bool {
self.type_parameters()
.iter()
.all(|tp| tp.is_concrete(handler, engines))
&& self
.return_type
.type_id
.is_concrete(engines, TreatNumericAs::Concrete)
&& self.parameters().iter().all(|t| {
t.type_argument
.type_id
.is_concrete(engines, TreatNumericAs::Concrete)
})
}
}
impl declaration::FunctionSignature for TyTraitFn {
fn parameters(&self) -> &Vec<TyFunctionParameter> {
&self.parameters
}
fn return_type(&self) -> &GenericTypeArgument {
&self.return_type
}
}
impl EqWithEngines for TyTraitFn {}
impl PartialEqWithEngines for TyTraitFn {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let type_engine = ctx.engines().te();
self.name == other.name
&& self.purity == other.purity
&& self.parameters.eq(&other.parameters, ctx)
&& type_engine
.get(self.return_type.type_id)
.eq(&type_engine.get(other.return_type.type_id), ctx)
&& self.attributes == other.attributes
}
}
impl HashWithEngines for TyTraitFn {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyTraitFn {
name,
purity,
parameters,
return_type,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
attributes: _,
} = self;
let type_engine = engines.te();
name.hash(state);
parameters.hash(state, engines);
type_engine.get(return_type.type_id).hash(state, engines);
purity.hash(state);
}
}
impl SubstTypes for TyTraitFn {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
self.parameters.subst(ctx);
self.return_type.subst(ctx);
}
}
}
impl MonomorphizeHelper for TyTraitFn {
fn name(&self) -> &Ident {
&self.name
}
fn type_parameters(&self) -> &[TypeParameter] {
&[]
}
fn has_self_type_param(&self) -> bool {
false
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/type_alias.rs | sway-core/src/language/ty/declaration/type_alias.rs | use crate::{
ast_elements::type_argument::GenericTypeArgument,
engine_threading::*,
language::{parsed::TypeAliasDeclaration, ty::TyDeclParsedType, CallPath, Visibility},
transform,
type_system::*,
};
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyTypeAliasDecl {
pub name: Ident,
pub call_path: CallPath,
pub attributes: transform::Attributes,
pub ty: GenericTypeArgument,
pub visibility: Visibility,
pub span: Span,
}
impl TyDeclParsedType for TyTypeAliasDecl {
type ParsedType = TypeAliasDeclaration;
}
impl Named for TyTypeAliasDecl {
fn name(&self) -> &Ident {
&self.name
}
}
impl EqWithEngines for TyTypeAliasDecl {}
impl PartialEqWithEngines for TyTypeAliasDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name && self.ty.eq(&other.ty, ctx) && self.visibility == other.visibility
}
}
impl HashWithEngines for TyTypeAliasDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyTypeAliasDecl {
name,
ty,
visibility,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
call_path: _,
span: _,
attributes: _,
} = self;
name.hash(state);
ty.hash(state, engines);
visibility.hash(state);
}
}
impl SubstTypes for TyTypeAliasDecl {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
self.ty.subst(ctx)
}
}
impl CreateTypeId for TyTypeAliasDecl {
fn create_type_id(&self, engines: &Engines) -> TypeId {
engines
.te()
.new_alias(engines, self.name.clone(), self.ty.clone())
}
}
impl Spanned for TyTypeAliasDecl {
fn span(&self) -> Span {
self.span.clone()
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/enum.rs | sway-core/src/language/ty/declaration/enum.rs | use crate::{
ast_elements::type_argument::GenericTypeArgument,
decl_engine::MaterializeConstGenerics,
engine_threading::*,
has_changes,
language::{parsed::EnumDeclaration, ty::TyDeclParsedType, CallPath, Visibility},
transform,
type_system::*,
};
use ast_elements::type_parameter::ConstGenericExpr;
use monomorphization::MonomorphizeHelper;
use serde::{Deserialize, Serialize};
use std::{
cmp::Ordering,
hash::{Hash, Hasher},
};
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyEnumDecl {
pub call_path: CallPath,
pub generic_parameters: Vec<TypeParameter>,
pub attributes: transform::Attributes,
pub variants: Vec<TyEnumVariant>,
pub span: Span,
pub visibility: Visibility,
}
impl TyDeclParsedType for TyEnumDecl {
type ParsedType = EnumDeclaration;
}
impl Named for TyEnumDecl {
fn name(&self) -> &Ident {
&self.call_path.suffix
}
}
impl EqWithEngines for TyEnumDecl {}
impl PartialEqWithEngines for TyEnumDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.call_path == other.call_path
&& self.generic_parameters.eq(&other.generic_parameters, ctx)
&& self.variants.eq(&other.variants, ctx)
&& self.visibility == other.visibility
}
}
impl HashWithEngines for TyEnumDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyEnumDecl {
call_path,
generic_parameters: type_parameters,
variants,
visibility,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
attributes: _,
} = self;
call_path.hash(state);
variants.hash(state, engines);
type_parameters.hash(state, engines);
visibility.hash(state);
}
}
impl SubstTypes for TyEnumDecl {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
self.variants.subst(ctx);
self.generic_parameters.subst(ctx);
}
}
}
impl Spanned for TyEnumDecl {
fn span(&self) -> Span {
self.span.clone()
}
}
impl IsConcrete for TyEnumDecl {
fn is_concrete(&self, handler: &Handler, engines: &Engines) -> bool {
self.generic_parameters
.iter()
.all(|tp| tp.is_concrete(handler, engines))
}
}
impl MonomorphizeHelper for TyEnumDecl {
fn type_parameters(&self) -> &[TypeParameter] {
&self.generic_parameters
}
fn name(&self) -> &Ident {
&self.call_path.suffix
}
fn has_self_type_param(&self) -> bool {
false
}
}
impl MaterializeConstGenerics for TyEnumDecl {
fn materialize_const_generics(
&mut self,
engines: &Engines,
handler: &Handler,
name: &str,
value: &crate::language::ty::TyExpression,
) -> Result<(), ErrorEmitted> {
for p in self.generic_parameters.iter_mut() {
match p {
TypeParameter::Const(p) if p.name.as_str() == name => {
p.expr = Some(ConstGenericExpr::from_ty_expression(handler, value)?);
}
TypeParameter::Type(p) => {
p.type_id
.materialize_const_generics(engines, handler, name, value)?;
}
_ => {}
}
}
for variant in self.variants.iter_mut() {
variant
.type_argument
.type_id
.materialize_const_generics(engines, handler, name, value)?;
}
Ok(())
}
}
impl TyEnumDecl {
pub(crate) fn expect_variant_from_name(
&self,
handler: &Handler,
variant_name: &Ident,
) -> Result<&TyEnumVariant, ErrorEmitted> {
match self
.variants
.iter()
.find(|x| x.name.as_str() == variant_name.as_str())
{
Some(variant) => Ok(variant),
None => Err(handler.emit_err(CompileError::UnknownEnumVariant {
enum_name: self.call_path.suffix.clone(),
variant_name: variant_name.clone(),
span: variant_name.span(),
})),
}
}
}
impl Spanned for TyEnumVariant {
fn span(&self) -> Span {
self.span.clone()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TyEnumVariant {
pub name: Ident,
pub type_argument: GenericTypeArgument,
pub(crate) tag: usize,
pub span: Span,
pub attributes: transform::Attributes,
}
impl HashWithEngines for TyEnumVariant {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
self.name.hash(state);
self.type_argument.hash(state, engines);
self.tag.hash(state);
}
}
impl EqWithEngines for TyEnumVariant {}
impl PartialEqWithEngines for TyEnumVariant {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.type_argument.eq(&other.type_argument, ctx)
&& self.tag == other.tag
}
}
impl OrdWithEngines for TyEnumVariant {
fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering {
let TyEnumVariant {
name: ln,
type_argument: lta,
tag: lt,
// these fields are not compared because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
attributes: _,
} = self;
let TyEnumVariant {
name: rn,
type_argument: rta,
tag: rt,
// these fields are not compared because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
attributes: _,
} = other;
ln.cmp(rn)
.then_with(|| lta.cmp(rta, ctx))
.then_with(|| lt.cmp(rt))
}
}
impl SubstTypes for TyEnumVariant {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
self.type_argument.subst_inner(ctx)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/declaration/trait_type.rs | sway-core/src/language/ty/declaration/trait_type.rs | use crate::{
engine_threading::*, has_changes, language::parsed::TraitTypeDeclaration,
language::ty::TyDeclParsedType, transform, type_system::*,
};
use serde::{Deserialize, Serialize};
use std::{
fmt,
hash::{Hash, Hasher},
};
use sway_error::handler::Handler;
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyTraitType {
pub name: Ident,
pub attributes: transform::Attributes,
pub ty: Option<GenericArgument>,
pub implementing_type: TypeId,
pub span: Span,
}
impl TyDeclParsedType for TyTraitType {
type ParsedType = TraitTypeDeclaration;
}
impl DebugWithEngines for TyTraitType {
fn fmt(&self, f: &mut fmt::Formatter<'_>, _engines: &Engines) -> fmt::Result {
write!(f, "{}", self.name)
}
}
impl Named for TyTraitType {
fn name(&self) -> &Ident {
&self.name
}
}
impl IsConcrete for TyTraitType {
fn is_concrete(&self, _: &Handler, engines: &Engines) -> bool {
if let Some(ty) = &self.ty {
ty.type_id().is_concrete(engines, TreatNumericAs::Concrete)
} else {
false
}
}
}
impl EqWithEngines for TyTraitType {}
impl PartialEqWithEngines for TyTraitType {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.ty.eq(&other.ty, ctx)
&& self.implementing_type.eq(&other.implementing_type)
}
}
impl HashWithEngines for TyTraitType {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyTraitType {
name,
ty,
implementing_type,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
attributes: _,
} = self;
name.hash(state);
ty.hash(state, engines);
implementing_type.hash(state);
}
}
impl SubstTypes for TyTraitType {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
self.ty.subst(ctx);
self.implementing_type.subst(ctx);
}
}
}
impl Spanned for TyTraitType {
fn span(&self) -> Span {
self.span.clone()
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/expression/intrinsic_function.rs | sway-core/src/language/ty/expression/intrinsic_function.rs | use crate::{engine_threading::*, has_changes, language::ty::*, type_system::*, types::*};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::{
fmt,
hash::{Hash, Hasher},
};
use sway_ast::Intrinsic;
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::{Span, Spanned};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TyIntrinsicFunctionKind {
pub kind: Intrinsic,
pub arguments: Vec<TyExpression>,
pub type_arguments: Vec<GenericArgument>,
pub span: Span,
}
impl EqWithEngines for TyIntrinsicFunctionKind {}
impl PartialEqWithEngines for TyIntrinsicFunctionKind {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.kind == other.kind
&& self.arguments.eq(&other.arguments, ctx)
&& self.type_arguments.eq(&other.type_arguments, ctx)
}
}
impl HashWithEngines for TyIntrinsicFunctionKind {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyIntrinsicFunctionKind {
kind,
arguments,
type_arguments,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
} = self;
kind.hash(state);
arguments.hash(state, engines);
type_arguments.hash(state, engines);
}
}
impl SubstTypes for TyIntrinsicFunctionKind {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
self.arguments.subst(ctx);
self.type_arguments.subst(ctx);
}
}
}
impl DebugWithEngines for TyIntrinsicFunctionKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
let targs = self
.type_arguments
.iter()
.map(|targ| format!("{:?}", engines.help_out(targ.type_id())))
.join(", ");
let args = self
.arguments
.iter()
.map(|e| format!("{:?}", engines.help_out(e)))
.join(", ");
write!(f, "{}::<{}>::({})", self.kind, targs, args)
}
}
impl CollectTypesMetadata for TyIntrinsicFunctionKind {
fn collect_types_metadata(
&self,
handler: &Handler,
ctx: &mut CollectTypesMetadataContext,
) -> Result<Vec<TypeMetadata>, ErrorEmitted> {
let mut types_metadata = vec![];
for type_arg in self.type_arguments.iter() {
ctx.call_site_insert(type_arg.type_id(), type_arg.span());
types_metadata.append(&mut type_arg.type_id().collect_types_metadata(handler, ctx)?);
}
for arg in self.arguments.iter() {
types_metadata.append(&mut arg.collect_types_metadata(handler, ctx)?);
}
match self.kind {
Intrinsic::Log => {
let logged_type_id = TypeMetadata::get_logged_type_id(
&self.arguments[0],
ctx.experimental.new_encoding,
)
.map_err(|err| handler.emit_err(err))?;
let logged_type = TypeMetadata::new_logged_type(
handler,
ctx.engines,
logged_type_id,
ctx.program_name.clone(),
)?;
types_metadata.push(logged_type);
}
Intrinsic::Smo => {
types_metadata.push(TypeMetadata::MessageType(
MessageId::new(ctx.message_id_counter()),
self.arguments[1].return_type,
));
*ctx.message_id_counter_mut() += 1;
}
_ => {}
}
Ok(types_metadata)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/expression/struct_exp_field.rs | sway-core/src/language/ty/expression/struct_exp_field.rs | use crate::{
decl_engine::*,
engine_threading::*,
language::ty::*,
semantic_analysis::{TypeCheckContext, TypeCheckFinalization, TypeCheckFinalizationContext},
type_system::*,
};
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::Ident;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyStructExpressionField {
pub name: Ident,
pub value: TyExpression,
}
impl EqWithEngines for TyStructExpressionField {}
impl PartialEqWithEngines for TyStructExpressionField {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name && self.value.eq(&other.value, ctx)
}
}
impl HashWithEngines for TyStructExpressionField {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyStructExpressionField { name, value } = self;
name.hash(state);
value.hash(state, engines);
}
}
impl SubstTypes for TyStructExpressionField {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
self.value.subst(ctx)
}
}
impl ReplaceDecls for TyStructExpressionField {
fn replace_decls_inner(
&mut self,
decl_mapping: &DeclMapping,
handler: &Handler,
ctx: &mut TypeCheckContext,
) -> Result<bool, ErrorEmitted> {
self.value.replace_decls(decl_mapping, handler, ctx)
}
}
impl TypeCheckFinalization for TyStructExpressionField {
fn type_check_finalize(
&mut self,
handler: &Handler,
ctx: &mut TypeCheckFinalizationContext,
) -> Result<(), ErrorEmitted> {
self.value.type_check_finalize(handler, ctx)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/expression/contract.rs | sway-core/src/language/ty/expression/contract.rs | use crate::language::ty::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ContractCallParams {
// This is none in encoding V1
pub(crate) func_selector: Option<[u8; 4]>,
pub(crate) contract_address: Box<TyExpression>,
pub(crate) contract_caller: Box<TyExpression>,
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/expression/asm.rs | sway-core/src/language/ty/expression/asm.rs | use crate::{engine_threading::*, language::ty::*, type_system::*};
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use sway_types::Ident;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyAsmRegisterDeclaration {
pub initializer: Option<TyExpression>,
pub(crate) name: Ident,
}
impl PartialEqWithEngines for TyAsmRegisterDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& if let (Some(l), Some(r)) = (&self.initializer, &other.initializer) {
l.eq(r, ctx)
} else {
true
}
}
}
impl HashWithEngines for TyAsmRegisterDeclaration {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyAsmRegisterDeclaration { initializer, name } = self;
name.hash(state);
if let Some(x) = initializer.as_ref() {
x.hash(state, engines)
}
}
}
impl SubstTypes for TyAsmRegisterDeclaration {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
self.initializer.subst(ctx)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/expression/scrutinee.rs | sway-core/src/language/ty/expression/scrutinee.rs | use crate::{
decl_engine::{DeclRefEnum, DeclRefStruct},
language::{ty::*, *},
type_system::*,
};
use serde::{Deserialize, Serialize};
use sway_types::{Ident, Span};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TyScrutinee {
pub variant: TyScrutineeVariant,
pub type_id: TypeId,
pub span: Span,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(clippy::large_enum_variant)]
pub enum TyScrutineeVariant {
Or(Vec<TyScrutinee>),
CatchAll,
Literal(Literal),
Variable(Ident),
Constant(Ident, Literal, TyConstantDecl),
StructScrutinee {
struct_ref: DeclRefStruct,
fields: Vec<TyStructScrutineeField>,
instantiation_call_path: CallPath,
},
EnumScrutinee {
enum_ref: DeclRefEnum,
variant: Box<TyEnumVariant>,
/// Should contain a TyDecl to either an enum or a type alias.
call_path_decl: ty::TyDecl,
value: Box<TyScrutinee>,
instantiation_call_path: CallPath,
},
Tuple(Vec<TyScrutinee>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TyStructScrutineeField {
pub field: Ident,
pub scrutinee: Option<TyScrutinee>,
pub span: Span,
pub field_def_name: Ident,
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/expression/match_expression.rs | sway-core/src/language/ty/expression/match_expression.rs | use sway_types::{Ident, Span};
use crate::{language::ty::*, type_system::*};
/// [TyExpression] of type bool that contains the condition to be used
/// in the desugared if expression or `None` if the match arm is
/// a catch-all arm without condition.
/// E.g., a condition might look like:
/// `__matched_value_1.x == 11 && __matched_value_1.y == 22 || __matched_value_1.x == 33 && __matched_value_1.y == 44`
pub(crate) type MatchBranchCondition = Option<TyExpression>;
/// [TyExpression]s of the form `let <ident> = <expression>` where
/// `<ident>` is a name of a generated variable that holds the
/// index of the matched OR variant.
/// `<expression>` is an `if-else` expression that returns
/// the 1-based index of the matched OR variant or zero
/// if non of the variants match.
pub(crate) type MatchedOrVariantIndexVars = Vec<(Ident, TyExpression)>;
#[derive(Debug)]
pub(crate) struct TyMatchExpression {
pub(crate) value_type_id: TypeId,
pub(crate) branches: Vec<TyMatchBranch>,
pub(crate) return_type_id: TypeId,
pub(crate) span: Span,
}
#[derive(Debug)]
pub(crate) struct TyMatchBranch {
/// Declarations of the variables that hold the 1-based index
/// of a matched OR variant or zero if non of the variants match.
pub(crate) matched_or_variant_index_vars: MatchedOrVariantIndexVars,
/// A boolean expression that represents the total match arm requirement,
/// or `None` if the match arm is a catch-all arm.
pub(crate) condition: MatchBranchCondition,
/// The resulting [crate::ty::TyCodeBlock] that includes the match arm variable declarations
/// and the typed result from the original untyped branch result.
pub(crate) result: TyExpression,
#[allow(dead_code)]
pub(crate) span: Span,
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/expression/storage.rs | sway-core/src/language/ty/expression/storage.rs | use super::TyExpression;
use crate::{engine_threading::*, type_system::TypeId};
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use sway_types::{Ident, Span, Spanned};
/// Describes the full storage access including all the subfields
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyStorageAccess {
pub fields: Vec<TyStorageAccessDescriptor>,
pub storage_field_names: Vec<String>,
pub struct_field_names: Vec<String>,
pub key_expression: Option<Box<TyExpression>>,
pub storage_keyword_span: Span,
}
impl EqWithEngines for TyStorageAccess {}
impl PartialEqWithEngines for TyStorageAccess {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.fields.len() == other.fields.len()
&& self.fields.eq(&other.fields, ctx)
&& self.storage_field_names.len() == other.storage_field_names.len()
&& self.storage_field_names.eq(&other.storage_field_names)
&& self.struct_field_names.len() == other.struct_field_names.len()
&& self.struct_field_names.eq(&other.struct_field_names)
&& self.key_expression.eq(&other.key_expression, ctx)
}
}
impl HashWithEngines for TyStorageAccess {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyStorageAccess {
fields,
storage_keyword_span,
storage_field_names,
struct_field_names,
key_expression,
} = self;
fields.hash(state, engines);
storage_field_names.hash(state);
struct_field_names.hash(state);
key_expression.hash(state, engines);
storage_keyword_span.hash(state);
}
}
impl Spanned for TyStorageAccess {
fn span(&self) -> Span {
// TODO: Use Span::join_all().
self.fields
.iter()
.fold(self.fields[0].span.clone(), |acc, field| {
Span::join(acc, &field.span)
})
}
}
impl TyStorageAccess {
pub fn storage_field_name(&self) -> Ident {
self.fields[0].name.clone()
}
}
/// Describes a single subfield access in the sequence when accessing a subfield within storage.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyStorageAccessDescriptor {
pub name: Ident,
pub type_id: TypeId,
pub(crate) span: Span,
}
impl EqWithEngines for TyStorageAccessDescriptor {}
impl PartialEqWithEngines for TyStorageAccessDescriptor {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let type_engine = ctx.engines().te();
self.name == other.name
&& type_engine
.get(self.type_id)
.eq(&type_engine.get(other.type_id), ctx)
}
}
impl HashWithEngines for TyStorageAccessDescriptor {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyStorageAccessDescriptor {
name,
type_id,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
} = self;
let type_engine = engines.te();
name.hash(state);
type_engine.get(*type_id).hash(state, engines);
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/expression/expression.rs | sway-core/src/language/ty/expression/expression.rs | use crate::{
decl_engine::*,
engine_threading::*,
has_changes,
language::{ty::*, Literal},
semantic_analysis::{
TypeCheckAnalysis, TypeCheckAnalysisContext, TypeCheckContext, TypeCheckFinalization,
TypeCheckFinalizationContext,
},
transform::{AllowDeprecatedState, Attributes},
type_system::*,
types::*,
};
use serde::{Deserialize, Serialize};
use std::{fmt, hash::Hasher};
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
type_error::TypeError,
warning::{CompileWarning, DeprecatedElement, Warning},
};
use sway_types::{Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyExpression {
pub expression: TyExpressionVariant,
pub return_type: TypeId,
pub span: Span,
}
impl EqWithEngines for TyExpression {}
impl PartialEqWithEngines for TyExpression {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let type_engine = ctx.engines().te();
self.expression.eq(&other.expression, ctx)
&& type_engine
.get(self.return_type)
.eq(&type_engine.get(other.return_type), ctx)
}
}
impl HashWithEngines for TyExpression {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyExpression {
expression,
return_type,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
} = self;
let type_engine = engines.te();
expression.hash(state, engines);
type_engine.get(*return_type).hash(state, engines);
}
}
impl SubstTypes for TyExpression {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
self.return_type.subst(ctx);
self.expression.subst(ctx);
}
}
}
impl ReplaceDecls for TyExpression {
fn replace_decls_inner(
&mut self,
decl_mapping: &DeclMapping,
handler: &Handler,
ctx: &mut TypeCheckContext,
) -> Result<bool, ErrorEmitted> {
self.expression.replace_decls(decl_mapping, handler, ctx)
}
}
impl UpdateConstantExpression for TyExpression {
fn update_constant_expression(&mut self, engines: &Engines, implementing_type: &TyDecl) {
self.expression
.update_constant_expression(engines, implementing_type)
}
}
impl DisplayWithEngines for TyExpression {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(
f,
"{} ({})",
engines.help_out(&self.expression),
engines.help_out(self.return_type)
)
}
}
impl DebugWithEngines for TyExpression {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(
f,
"{:?} ({:?})",
engines.help_out(&self.expression),
engines.help_out(self.return_type)
)
}
}
impl TypeCheckAnalysis for TyExpression {
fn type_check_analyze(
&self,
handler: &Handler,
ctx: &mut TypeCheckAnalysisContext,
) -> Result<(), ErrorEmitted> {
match &self.expression {
// Check literal "fits" into assigned typed.
TyExpressionVariant::Literal(Literal::Numeric(literal_value)) => {
let t = ctx.engines.te().get(self.return_type);
if let TypeInfo::UnsignedInteger(bits) = &*t {
if bits.would_overflow(*literal_value) {
handler.emit_err(CompileError::TypeError(TypeError::LiteralOverflow {
expected: format!("{:?}", ctx.engines.help_out(t)),
span: self.span.clone(),
}));
}
}
}
TyExpressionVariant::ArrayExplicit { .. } => {
self.as_array_unify_elements(handler, ctx.engines);
}
_ => {}
}
self.expression.type_check_analyze(handler, ctx)
}
}
impl TypeCheckFinalization for TyExpression {
fn type_check_finalize(
&mut self,
handler: &Handler,
ctx: &mut TypeCheckFinalizationContext,
) -> Result<(), ErrorEmitted> {
let res = self.expression.type_check_finalize(handler, ctx);
if let TyExpressionVariant::FunctionApplication { fn_ref, .. } = &self.expression {
let method = ctx.engines.de().get_function(fn_ref);
self.return_type = method.return_type.type_id;
}
res
}
}
impl CollectTypesMetadata for TyExpression {
fn collect_types_metadata(
&self,
handler: &Handler,
ctx: &mut CollectTypesMetadataContext,
) -> Result<Vec<TypeMetadata>, ErrorEmitted> {
use TyExpressionVariant::*;
let decl_engine = ctx.engines.de();
let mut res = self.return_type.collect_types_metadata(handler, ctx)?;
match &self.expression {
FunctionApplication {
arguments,
fn_ref,
call_path,
type_binding,
..
} => {
for arg in arguments.iter() {
res.append(&mut arg.1.collect_types_metadata(handler, ctx)?);
}
let function_decl = decl_engine.get_function(fn_ref);
ctx.call_site_push();
for (idx, p) in function_decl
.type_parameters
.iter()
.filter_map(|x| x.as_type_parameter())
.enumerate()
{
ctx.call_site_insert(p.type_id, call_path.span());
// Verify type arguments are concrete
res.extend(
p.type_id
.collect_types_metadata(handler, ctx)?
.into_iter()
// try to use the caller span for better error messages
.map(|x| match x {
TypeMetadata::UnresolvedType(ident, original_span) => {
let span = type_binding
.as_ref()
.and_then(|type_binding| {
type_binding.type_arguments.as_slice().get(idx)
})
.map(|type_argument| Some(type_argument.span()))
.unwrap_or(original_span);
TypeMetadata::UnresolvedType(ident, span)
}
x => x,
}),
);
}
for content in function_decl.body.contents.iter() {
res.append(&mut content.collect_types_metadata(handler, ctx)?);
}
ctx.call_site_pop();
}
Tuple { fields } => {
for field in fields.iter() {
res.append(&mut field.collect_types_metadata(handler, ctx)?);
}
}
AsmExpression { registers, .. } => {
for register in registers.iter() {
if let Some(init) = register.initializer.as_ref() {
res.append(&mut init.collect_types_metadata(handler, ctx)?);
}
}
}
StructExpression {
fields,
instantiation_span,
struct_id,
..
} => {
let struct_decl = decl_engine.get_struct(struct_id);
for p in &struct_decl.generic_parameters {
match p {
TypeParameter::Type(p) => {
ctx.call_site_insert(p.type_id, instantiation_span.clone());
}
TypeParameter::Const(_) => {}
}
}
if let TypeInfo::Struct(decl_ref) = &*ctx.engines.te().get(self.return_type) {
let decl = decl_engine.get_struct(decl_ref);
for p in &decl.generic_parameters {
match p {
TypeParameter::Type(p) => {
ctx.call_site_insert(p.type_id, instantiation_span.clone());
}
TypeParameter::Const(_) => {}
}
}
}
for field in fields.iter() {
res.append(&mut field.value.collect_types_metadata(handler, ctx)?);
}
}
LazyOperator { lhs, rhs, .. } => {
res.append(&mut lhs.collect_types_metadata(handler, ctx)?);
res.append(&mut rhs.collect_types_metadata(handler, ctx)?);
}
ArrayExplicit {
elem_type: _,
contents,
} => {
for content in contents.iter() {
res.append(&mut content.collect_types_metadata(handler, ctx)?);
}
}
ArrayRepeat {
elem_type: _,
value,
length,
} => {
res.append(&mut value.collect_types_metadata(handler, ctx)?);
res.append(&mut length.collect_types_metadata(handler, ctx)?);
}
ArrayIndex { prefix, index } => {
res.append(&mut (**prefix).collect_types_metadata(handler, ctx)?);
res.append(&mut (**index).collect_types_metadata(handler, ctx)?);
}
CodeBlock(block) => {
for content in block.contents.iter() {
res.append(&mut content.collect_types_metadata(handler, ctx)?);
}
}
MatchExp { desugared, .. } => {
res.append(&mut desugared.collect_types_metadata(handler, ctx)?)
}
IfExp {
condition,
then,
r#else,
} => {
res.append(&mut condition.collect_types_metadata(handler, ctx)?);
res.append(&mut then.collect_types_metadata(handler, ctx)?);
if let Some(r#else) = r#else {
res.append(&mut r#else.collect_types_metadata(handler, ctx)?);
}
}
StructFieldAccess {
prefix,
resolved_type_of_parent,
..
} => {
res.append(&mut prefix.collect_types_metadata(handler, ctx)?);
res.append(&mut resolved_type_of_parent.collect_types_metadata(handler, ctx)?);
}
TupleElemAccess {
prefix,
resolved_type_of_parent,
..
} => {
res.append(&mut prefix.collect_types_metadata(handler, ctx)?);
res.append(&mut resolved_type_of_parent.collect_types_metadata(handler, ctx)?);
}
EnumInstantiation {
enum_ref,
contents,
call_path_binding,
..
} => {
let enum_decl = decl_engine.get_enum(enum_ref);
for p in enum_decl.generic_parameters.iter() {
match p {
TypeParameter::Type(p) => {
ctx.call_site_insert(p.type_id, call_path_binding.inner.suffix.span())
}
TypeParameter::Const(_) => {}
}
}
if let Some(contents) = contents {
res.append(&mut contents.collect_types_metadata(handler, ctx)?);
}
for variant in enum_decl.variants.iter() {
res.append(
&mut variant
.type_argument
.type_id
.collect_types_metadata(handler, ctx)?,
);
}
for p in enum_decl.generic_parameters.iter() {
match p {
TypeParameter::Type(p) => {
res.append(&mut p.type_id.collect_types_metadata(handler, ctx)?);
}
TypeParameter::Const(_) => {}
}
}
}
AbiCast { address, .. } => {
res.append(&mut address.collect_types_metadata(handler, ctx)?);
}
IntrinsicFunction(kind) => {
res.append(&mut kind.collect_types_metadata(handler, ctx)?);
}
EnumTag { exp } => {
res.append(&mut exp.collect_types_metadata(handler, ctx)?);
}
UnsafeDowncast {
exp,
variant,
call_path_decl: _,
} => {
res.append(&mut exp.collect_types_metadata(handler, ctx)?);
res.append(
&mut variant
.type_argument
.type_id
.collect_types_metadata(handler, ctx)?,
);
}
WhileLoop { condition, body } => {
res.append(&mut condition.collect_types_metadata(handler, ctx)?);
for content in body.contents.iter() {
res.append(&mut content.collect_types_metadata(handler, ctx)?);
}
}
ForLoop { desugared } => {
res.append(&mut desugared.collect_types_metadata(handler, ctx)?);
}
ImplicitReturn(exp) | Return(exp) => {
res.append(&mut exp.collect_types_metadata(handler, ctx)?)
}
Panic(exp) => {
// Register the type of the `panic` argument as a logged type.
let logged_type_id =
TypeMetadata::get_logged_type_id(exp, ctx.experimental.new_encoding)
.map_err(|err| handler.emit_err(err))?;
res.push(TypeMetadata::new_logged_type(
handler,
ctx.engines,
logged_type_id,
ctx.program_name.clone(),
)?);
// We still need to dive into the expression because it can have additional types to collect.
// E.g., `revert some_function_that_returns_error_enum_and_internally_logs_some_types()`;
res.append(&mut exp.collect_types_metadata(handler, ctx)?)
}
Ref(exp) | Deref(exp) => res.append(&mut exp.collect_types_metadata(handler, ctx)?),
// storage access can never be generic
// variable expressions don't ever have return types themselves, they're stored in
// `TyExpression::return_type`. Variable expressions are just names of variables.
VariableExpression { .. }
| ConstantExpression { .. }
| ConfigurableExpression { .. }
| ConstGenericExpression { .. }
| StorageAccess { .. }
| Literal(_)
| AbiName(_)
| Break
| Continue
| FunctionParameter => {}
Reassignment(reassignment) => {
res.append(&mut reassignment.rhs.collect_types_metadata(handler, ctx)?);
}
}
Ok(res)
}
}
impl MaterializeConstGenerics for TyExpression {
fn materialize_const_generics(
&mut self,
engines: &Engines,
handler: &Handler,
name: &str,
value: &TyExpression,
) -> Result<(), ErrorEmitted> {
self.return_type
.materialize_const_generics(engines, handler, name, value)?;
match &mut self.expression {
TyExpressionVariant::CodeBlock(block) => {
for node in block.contents.iter_mut() {
node.materialize_const_generics(engines, handler, name, value)?;
}
Ok(())
}
TyExpressionVariant::ConstGenericExpression { decl, .. } => {
decl.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::ImplicitReturn(expr) => {
expr.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::FunctionApplication {
arguments,
type_binding,
fn_ref,
..
} => {
// Materialize non dummy fns
let new_decl = engines.de().get(fn_ref.id());
if !new_decl.is_trait_method_dummy {
let mut type_subst_map = TypeSubstMap::new();
type_subst_map
.const_generics_materialization
.insert(name.to_string(), value.clone());
let mut new_decl = TyFunctionDecl::clone(&*new_decl);
let r = new_decl.subst_inner(&SubstTypesContext {
handler,
engines,
type_subst_map: Some(&type_subst_map),
subst_function_body: true,
});
if matches!(r, HasChanges::Yes) {
*fn_ref = engines.de().insert(new_decl, None);
}
}
if let Some(type_binding) = type_binding.as_mut() {
type_binding
.type_arguments
.to_vec_mut()
.materialize_const_generics(engines, handler, name, value)?;
}
for (_, expr) in arguments {
expr.materialize_const_generics(engines, handler, name, value)?;
}
Ok(())
}
TyExpressionVariant::IntrinsicFunction(TyIntrinsicFunctionKind {
arguments,
type_arguments,
..
}) => {
type_arguments.materialize_const_generics(engines, handler, name, value)?;
arguments.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::Return(expr) => {
expr.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::IfExp {
condition,
then,
r#else,
} => {
condition.materialize_const_generics(engines, handler, name, value)?;
then.materialize_const_generics(engines, handler, name, value)?;
if let Some(e) = r#else.as_mut() {
e.materialize_const_generics(engines, handler, name, value)?;
}
Ok(())
}
TyExpressionVariant::WhileLoop { condition, body } => {
condition.materialize_const_generics(engines, handler, name, value)?;
body.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::Reassignment(expr) => expr
.rhs
.materialize_const_generics(engines, handler, name, value),
TyExpressionVariant::ArrayIndex { prefix, index } => {
prefix.materialize_const_generics(engines, handler, name, value)?;
index.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::Literal(_) | TyExpressionVariant::VariableExpression { .. } => {
Ok(())
}
TyExpressionVariant::ArrayExplicit {
elem_type,
contents,
} => {
elem_type.materialize_const_generics(engines, handler, name, value)?;
for item in contents.iter_mut() {
item.materialize_const_generics(engines, handler, name, value)?;
}
Ok(())
}
TyExpressionVariant::ArrayRepeat {
elem_type,
value: elem_value,
length,
} => {
elem_type.materialize_const_generics(engines, handler, name, value)?;
elem_value.materialize_const_generics(engines, handler, name, value)?;
length.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::Ref(r) => {
r.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::Deref(r) => {
r.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::MatchExp { desugared, .. } => {
desugared.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::EnumInstantiation { contents, .. } => {
if let Some(contents) = contents.as_mut() {
contents.materialize_const_generics(engines, handler, name, value)?;
}
Ok(())
}
TyExpressionVariant::EnumTag { exp } => {
exp.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::Tuple { fields } => {
for f in fields {
f.materialize_const_generics(engines, handler, name, value)?;
}
Ok(())
}
TyExpressionVariant::TupleElemAccess {
prefix,
resolved_type_of_parent,
..
} => {
prefix.materialize_const_generics(engines, handler, name, value)?;
resolved_type_of_parent
.materialize_const_generics(engines, handler, name, value)?;
Ok(())
}
TyExpressionVariant::LazyOperator { lhs, rhs, .. } => {
lhs.materialize_const_generics(engines, handler, name, value)?;
rhs.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::AsmExpression { registers, .. } => {
for r in registers.iter_mut() {
if let Some(init) = r.initializer.as_mut() {
init.materialize_const_generics(engines, handler, name, value)?;
}
}
Ok(())
}
TyExpressionVariant::ConstantExpression { decl, .. } => {
decl.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::StructExpression { fields, .. } => {
for f in fields {
f.value
.materialize_const_generics(engines, handler, name, value)?;
}
Ok(())
}
TyExpressionVariant::StructFieldAccess {
prefix,
resolved_type_of_parent,
..
} => {
prefix.materialize_const_generics(engines, handler, name, value)?;
resolved_type_of_parent.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::UnsafeDowncast { exp, .. } => {
exp.materialize_const_generics(engines, handler, name, value)
}
TyExpressionVariant::Continue | TyExpressionVariant::Break => Ok(()),
TyExpressionVariant::AbiCast { address, .. } => {
address.materialize_const_generics(engines, handler, name, value)
}
_ => Err(handler.emit_err(
sway_error::error::CompileError::ConstGenericNotSupportedHere {
span: self.span.clone(),
},
)),
}
}
}
impl TyExpression {
pub(crate) fn error(err: ErrorEmitted, span: Span, engines: &Engines) -> TyExpression {
let type_engine = engines.te();
TyExpression {
expression: TyExpressionVariant::Tuple { fields: vec![] },
return_type: type_engine.id_of_error_recovery(err),
span,
}
}
/// gathers the mutability of the expressions within
pub(crate) fn gather_mutability(&self) -> VariableMutability {
match &self.expression {
TyExpressionVariant::VariableExpression { mutability, .. } => *mutability,
_ => VariableMutability::Immutable,
}
}
/// Returns `self` as a literal, if possible.
pub(crate) fn extract_literal_value(&self) -> Option<Literal> {
self.expression.extract_literal_value()
}
// Checks if this expression references a deprecated item
// TODO: Extend checks in this function to fully implement deprecation.
// See: https://github.com/FuelLabs/sway/issues/6942
pub(crate) fn check_deprecated(
&self,
engines: &Engines,
handler: &Handler,
allow_deprecated: &mut AllowDeprecatedState,
) {
fn emit_warning_if_deprecated(
attributes: &Attributes,
span: &Span,
handler: &Handler,
deprecated_element: DeprecatedElement,
deprecated_element_name: &str,
allow_deprecated: &mut AllowDeprecatedState,
) {
if allow_deprecated.is_allowed() {
return;
}
let Some(deprecated_attr) = attributes.deprecated() else {
return;
};
let help = deprecated_attr
.args
.iter()
// Last "note" argument wins ;-)
.rfind(|arg| arg.is_deprecated_note())
.and_then(|note_arg| match note_arg.get_string_opt(handler) {
Ok(note) => note.cloned(),
// We treat invalid values here as not having the "note" provided.
// Attribute checking will emit errors.
Err(_) => None,
});
handler.emit_warn(CompileWarning {
span: span.clone(),
warning_content: Warning::UsingDeprecated {
deprecated_element,
deprecated_element_name: deprecated_element_name.to_string(),
help,
},
})
}
match &self.expression {
TyExpressionVariant::Literal(..) => {}
TyExpressionVariant::FunctionApplication {
call_path,
fn_ref,
arguments,
..
} => {
for (_, expr) in arguments {
expr.check_deprecated(engines, handler, allow_deprecated);
}
let fn_ty = engines.de().get(fn_ref);
if let Some(TyDecl::ImplSelfOrTrait(t)) = &fn_ty.implementing_type {
let t = &engines.de().get(&t.decl_id).implementing_for;
if let TypeInfo::Struct(struct_id) = &*engines.te().get(t.type_id) {
let s = engines.de().get(struct_id);
emit_warning_if_deprecated(
&s.attributes,
&call_path.span(),
handler,
DeprecatedElement::Struct,
s.call_path.suffix.as_str(),
allow_deprecated,
);
}
}
emit_warning_if_deprecated(
&fn_ty.attributes,
&call_path.span(),
handler,
DeprecatedElement::Function,
fn_ty.call_path.suffix.as_str(),
allow_deprecated,
);
}
TyExpressionVariant::LazyOperator { lhs, rhs, .. } => {
lhs.check_deprecated(engines, handler, allow_deprecated);
rhs.check_deprecated(engines, handler, allow_deprecated);
}
TyExpressionVariant::ConstantExpression { span, decl, .. } => {
emit_warning_if_deprecated(
&decl.attributes,
span,
handler,
DeprecatedElement::Const,
decl.call_path.suffix.as_str(),
allow_deprecated,
);
}
TyExpressionVariant::ConfigurableExpression { span, decl, .. } => {
emit_warning_if_deprecated(
&decl.attributes,
span,
handler,
DeprecatedElement::Configurable,
decl.call_path.suffix.as_str(),
allow_deprecated,
);
}
// Const generics don´t have attributes, so deprecation warnings cannot be turned off.
TyExpressionVariant::ConstGenericExpression { .. } => {}
TyExpressionVariant::VariableExpression { .. } => {}
TyExpressionVariant::Tuple { fields } => {
for e in fields {
e.check_deprecated(engines, handler, allow_deprecated);
}
}
TyExpressionVariant::ArrayExplicit { contents, .. } => {
for e in contents {
e.check_deprecated(engines, handler, allow_deprecated);
}
}
TyExpressionVariant::ArrayRepeat { value, length, .. } => {
value.check_deprecated(engines, handler, allow_deprecated);
length.check_deprecated(engines, handler, allow_deprecated);
}
TyExpressionVariant::ArrayIndex { prefix, index } => {
prefix.check_deprecated(engines, handler, allow_deprecated);
index.check_deprecated(engines, handler, allow_deprecated);
}
TyExpressionVariant::StructExpression {
struct_id,
instantiation_span,
..
} => {
let struct_decl = engines.de().get(struct_id);
emit_warning_if_deprecated(
&struct_decl.attributes,
instantiation_span,
handler,
DeprecatedElement::Struct,
struct_decl.call_path.suffix.as_str(),
allow_deprecated,
);
}
TyExpressionVariant::CodeBlock(block) => {
block.check_deprecated(engines, handler, allow_deprecated);
}
TyExpressionVariant::FunctionParameter => {}
TyExpressionVariant::MatchExp {
desugared,
// TODO: Check the scrutinees.
// See: https://github.com/FuelLabs/sway/issues/6942
..
} => {
desugared.check_deprecated(engines, handler, allow_deprecated);
}
TyExpressionVariant::IfExp {
condition,
then,
r#else,
} => {
condition.check_deprecated(engines, handler, allow_deprecated);
then.check_deprecated(engines, handler, allow_deprecated);
if let Some(e) = r#else {
e.check_deprecated(engines, handler, allow_deprecated);
}
}
TyExpressionVariant::AsmExpression { .. } => {}
TyExpressionVariant::StructFieldAccess {
prefix,
field_to_access,
field_instantiation_span,
..
} => {
prefix.check_deprecated(engines, handler, allow_deprecated);
emit_warning_if_deprecated(
&field_to_access.attributes,
field_instantiation_span,
handler,
DeprecatedElement::StructField,
field_to_access.name.as_str(),
allow_deprecated,
);
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/expression/mod.rs | sway-core/src/language/ty/expression/mod.rs | mod asm;
mod contract;
#[allow(clippy::module_inception)]
mod expression;
mod expression_variant;
mod intrinsic_function;
mod match_expression;
mod reassignment;
mod scrutinee;
mod storage;
mod struct_exp_field;
pub use asm::*;
pub use contract::*;
pub use expression::*;
pub use expression_variant::*;
pub use intrinsic_function::*;
pub(crate) use match_expression::*;
pub use reassignment::*;
pub use scrutinee::*;
pub use storage::*;
pub use struct_exp_field::*;
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/expression/expression_variant.rs | sway-core/src/language/ty/expression/expression_variant.rs | use crate::{
decl_engine::*,
engine_threading::*,
has_changes,
language::{ty::*, *},
semantic_analysis::{
TyNodeDepGraphEdge, TyNodeDepGraphEdgeInfo, TypeCheckAnalysis, TypeCheckAnalysisContext,
TypeCheckContext, TypeCheckFinalization, TypeCheckFinalizationContext,
},
type_system::*,
};
use ast_elements::type_parameter::GenericTypeParameter;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::{
fmt::{self, Write},
hash::{Hash, Hasher},
};
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::{Ident, Named, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TyExpressionVariant {
Literal(Literal),
FunctionApplication {
call_path: CallPath,
arguments: Vec<(Ident, TyExpression)>,
fn_ref: DeclRefFunction,
selector: Option<ContractCallParams>,
/// Optional binding information for the LSP.
type_binding: Option<TypeBinding<()>>,
/// In case of a method call, a [TypeId] of the method target (self).
/// E.g., `method_target.some_method()`.
method_target: Option<TypeId>,
contract_call_params: IndexMap<String, TyExpression>,
contract_caller: Option<Box<TyExpression>>,
},
LazyOperator {
op: LazyOp,
lhs: Box<TyExpression>,
rhs: Box<TyExpression>,
},
ConstantExpression {
span: Span,
decl: Box<TyConstantDecl>,
call_path: Option<CallPath>,
},
ConfigurableExpression {
span: Span,
decl: Box<TyConfigurableDecl>,
call_path: Option<CallPath>,
},
ConstGenericExpression {
span: Span,
decl: Box<TyConstGenericDecl>,
call_path: CallPath,
},
VariableExpression {
name: Ident,
span: Span,
mutability: VariableMutability,
call_path: Option<CallPath>,
},
Tuple {
fields: Vec<TyExpression>,
},
ArrayExplicit {
elem_type: TypeId,
contents: Vec<TyExpression>,
},
ArrayRepeat {
elem_type: TypeId,
value: Box<TyExpression>,
length: Box<TyExpression>,
},
ArrayIndex {
prefix: Box<TyExpression>,
index: Box<TyExpression>,
},
StructExpression {
struct_id: DeclId<TyStructDecl>,
fields: Vec<TyStructExpressionField>,
instantiation_span: Span,
call_path_binding: TypeBinding<CallPath>,
},
CodeBlock(TyCodeBlock),
// a flag that this value will later be provided as a parameter, but is currently unknown
FunctionParameter,
MatchExp {
desugared: Box<TyExpression>,
scrutinees: Vec<TyScrutinee>,
},
IfExp {
condition: Box<TyExpression>,
then: Box<TyExpression>,
r#else: Option<Box<TyExpression>>,
},
AsmExpression {
registers: Vec<TyAsmRegisterDeclaration>,
body: Vec<AsmOp>,
returns: Option<(AsmRegister, Span)>,
whole_block_span: Span,
},
// like a variable expression but it has multiple parts,
// like looking up a field in a struct
StructFieldAccess {
prefix: Box<TyExpression>,
field_to_access: TyStructField,
field_instantiation_span: Span,
/// Final resolved type of the `prefix` part
/// of the expression. This will always be
/// a [TypeId] of a struct, never an alias
/// or a reference to a struct.
/// The original parent might be an alias
/// or a direct or indirect reference to a
/// struct.
resolved_type_of_parent: TypeId,
},
TupleElemAccess {
prefix: Box<TyExpression>,
elem_to_access_num: usize,
/// Final resolved type of the `prefix` part
/// of the expression. This will always be
/// a [TypeId] of a tuple, never an alias
/// or a reference to a tuple.
/// The original parent might be an alias
/// or a direct or indirect reference to a
/// tuple.
resolved_type_of_parent: TypeId,
elem_to_access_span: Span,
},
EnumInstantiation {
enum_ref: DeclRef<DeclId<TyEnumDecl>>,
/// for printing
variant_name: Ident,
tag: usize,
contents: Option<Box<TyExpression>>,
/// If there is an error regarding this instantiation of the enum,
/// use these spans as it points to the call site and not the declaration.
/// They are also used in the language server.
variant_instantiation_span: Span,
call_path_binding: TypeBinding<CallPath>,
/// The enum type, can be a type alias.
call_path_decl: ty::TyDecl,
},
AbiCast {
abi_name: CallPath,
address: Box<TyExpression>,
#[allow(dead_code)]
// this span may be used for errors in the future, although it is not right now.
span: Span,
},
StorageAccess(TyStorageAccess),
IntrinsicFunction(TyIntrinsicFunctionKind),
/// a zero-sized type-system-only compile-time thing that is used for constructing ABI casts.
AbiName(AbiName),
/// grabs the enum tag from the particular enum and variant of the `exp`
EnumTag {
exp: Box<TyExpression>,
},
/// performs an unsafe cast from the `exp` to the type of the given enum `variant`
UnsafeDowncast {
exp: Box<TyExpression>,
variant: TyEnumVariant,
/// Should contain a TyDecl to either an enum or a type alias.
call_path_decl: ty::TyDecl,
},
WhileLoop {
condition: Box<TyExpression>,
body: TyCodeBlock,
},
ForLoop {
desugared: Box<TyExpression>,
},
Break,
Continue,
Reassignment(Box<TyReassignment>),
ImplicitReturn(Box<TyExpression>),
Return(Box<TyExpression>),
Panic(Box<TyExpression>),
Ref(Box<TyExpression>),
Deref(Box<TyExpression>),
}
impl TyExpressionVariant {
pub fn as_literal(&self) -> Option<&Literal> {
match self {
TyExpressionVariant::Literal(v) => Some(v),
_ => None,
}
}
}
impl EqWithEngines for TyExpressionVariant {}
impl PartialEqWithEngines for TyExpressionVariant {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let type_engine = ctx.engines().te();
match (self, other) {
(Self::Literal(l0), Self::Literal(r0)) => l0 == r0,
(
Self::FunctionApplication {
call_path: l_name,
arguments: l_arguments,
fn_ref: l_fn_ref,
..
},
Self::FunctionApplication {
call_path: r_name,
arguments: r_arguments,
fn_ref: r_fn_ref,
..
},
) => {
l_name == r_name
&& l_arguments.len() == r_arguments.len()
&& l_arguments
.iter()
.zip(r_arguments.iter())
.all(|((xa, xb), (ya, yb))| xa == ya && xb.eq(yb, ctx))
&& l_fn_ref.eq(r_fn_ref, ctx)
}
(
Self::LazyOperator {
op: l_op,
lhs: l_lhs,
rhs: l_rhs,
},
Self::LazyOperator {
op: r_op,
lhs: r_lhs,
rhs: r_rhs,
},
) => l_op == r_op && (**l_lhs).eq(&(**r_lhs), ctx) && (**l_rhs).eq(&(**r_rhs), ctx),
(
Self::ConstantExpression {
call_path: l_call_path,
span: l_span,
decl: _,
},
Self::ConstantExpression {
call_path: r_call_path,
span: r_span,
decl: _,
},
) => l_call_path == r_call_path && l_span == r_span,
(
Self::VariableExpression {
name: l_name,
span: l_span,
mutability: l_mutability,
call_path: _,
},
Self::VariableExpression {
name: r_name,
span: r_span,
mutability: r_mutability,
call_path: _,
},
) => l_name == r_name && l_span == r_span && l_mutability == r_mutability,
(Self::Tuple { fields: l_fields }, Self::Tuple { fields: r_fields }) => {
l_fields.eq(r_fields, ctx)
}
(
Self::ArrayExplicit {
contents: l_contents,
..
},
Self::ArrayExplicit {
contents: r_contents,
..
},
) => l_contents.eq(r_contents, ctx),
(
Self::ArrayIndex {
prefix: l_prefix,
index: l_index,
},
Self::ArrayIndex {
prefix: r_prefix,
index: r_index,
},
) => (**l_prefix).eq(&**r_prefix, ctx) && (**l_index).eq(&**r_index, ctx),
(
Self::StructExpression {
struct_id: l_struct_id,
fields: l_fields,
instantiation_span: l_span,
call_path_binding: _,
},
Self::StructExpression {
struct_id: r_struct_id,
fields: r_fields,
instantiation_span: r_span,
call_path_binding: _,
},
) => {
PartialEqWithEngines::eq(&l_struct_id, &r_struct_id, ctx)
&& l_fields.eq(r_fields, ctx)
&& l_span == r_span
}
(Self::CodeBlock(l0), Self::CodeBlock(r0)) => l0.eq(r0, ctx),
(
Self::IfExp {
condition: l_condition,
then: l_then,
r#else: l_r,
},
Self::IfExp {
condition: r_condition,
then: r_then,
r#else: r_r,
},
) => {
(**l_condition).eq(&**r_condition, ctx)
&& (**l_then).eq(&**r_then, ctx)
&& if let (Some(l), Some(r)) = (l_r, r_r) {
(**l).eq(&**r, ctx)
} else {
true
}
}
(
Self::AsmExpression {
registers: l_registers,
body: l_body,
returns: l_returns,
..
},
Self::AsmExpression {
registers: r_registers,
body: r_body,
returns: r_returns,
..
},
) => {
l_registers.eq(r_registers, ctx)
&& l_body.clone() == r_body.clone()
&& l_returns == r_returns
}
(
Self::StructFieldAccess {
prefix: l_prefix,
field_to_access: l_field_to_access,
resolved_type_of_parent: l_resolved_type_of_parent,
..
},
Self::StructFieldAccess {
prefix: r_prefix,
field_to_access: r_field_to_access,
resolved_type_of_parent: r_resolved_type_of_parent,
..
},
) => {
(**l_prefix).eq(&**r_prefix, ctx)
&& l_field_to_access.eq(r_field_to_access, ctx)
&& type_engine
.get(*l_resolved_type_of_parent)
.eq(&type_engine.get(*r_resolved_type_of_parent), ctx)
}
(
Self::TupleElemAccess {
prefix: l_prefix,
elem_to_access_num: l_elem_to_access_num,
resolved_type_of_parent: l_resolved_type_of_parent,
..
},
Self::TupleElemAccess {
prefix: r_prefix,
elem_to_access_num: r_elem_to_access_num,
resolved_type_of_parent: r_resolved_type_of_parent,
..
},
) => {
(**l_prefix).eq(&**r_prefix, ctx)
&& l_elem_to_access_num == r_elem_to_access_num
&& type_engine
.get(*l_resolved_type_of_parent)
.eq(&type_engine.get(*r_resolved_type_of_parent), ctx)
}
(
Self::EnumInstantiation {
enum_ref: l_enum_ref,
variant_name: l_variant_name,
tag: l_tag,
contents: l_contents,
..
},
Self::EnumInstantiation {
enum_ref: r_enum_ref,
variant_name: r_variant_name,
tag: r_tag,
contents: r_contents,
..
},
) => {
l_enum_ref.eq(r_enum_ref, ctx)
&& l_variant_name == r_variant_name
&& l_tag == r_tag
&& if let (Some(l_contents), Some(r_contents)) = (l_contents, r_contents) {
(**l_contents).eq(&**r_contents, ctx)
} else {
true
}
}
(
Self::AbiCast {
abi_name: l_abi_name,
address: l_address,
..
},
Self::AbiCast {
abi_name: r_abi_name,
address: r_address,
..
},
) => l_abi_name == r_abi_name && (**l_address).eq(&**r_address, ctx),
(Self::IntrinsicFunction(l_kind), Self::IntrinsicFunction(r_kind)) => {
l_kind.eq(r_kind, ctx)
}
(
Self::UnsafeDowncast {
exp: l_exp,
variant: l_variant,
call_path_decl: _,
},
Self::UnsafeDowncast {
exp: r_exp,
variant: r_variant,
call_path_decl: _,
},
) => l_exp.eq(r_exp, ctx) && l_variant.eq(r_variant, ctx),
(Self::EnumTag { exp: l_exp }, Self::EnumTag { exp: r_exp }) => l_exp.eq(r_exp, ctx),
(Self::StorageAccess(l_exp), Self::StorageAccess(r_exp)) => l_exp.eq(r_exp, ctx),
(
Self::WhileLoop {
body: l_body,
condition: l_condition,
},
Self::WhileLoop {
body: r_body,
condition: r_condition,
},
) => l_body.eq(r_body, ctx) && l_condition.eq(r_condition, ctx),
(l, r) => std::mem::discriminant(l) == std::mem::discriminant(r),
}
}
}
impl HashWithEngines for TyExpressionVariant {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let type_engine = engines.te();
std::mem::discriminant(self).hash(state);
match self {
Self::Literal(lit) => {
lit.hash(state);
}
Self::FunctionApplication {
call_path,
arguments,
fn_ref,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
contract_call_params: _,
selector: _,
type_binding: _,
method_target: _,
..
} => {
call_path.hash(state);
fn_ref.hash(state, engines);
arguments.iter().for_each(|(name, arg)| {
name.hash(state);
arg.hash(state, engines);
});
}
Self::LazyOperator { op, lhs, rhs } => {
op.hash(state);
lhs.hash(state, engines);
rhs.hash(state, engines);
}
Self::ConstantExpression {
decl: const_decl,
span: _,
call_path: _,
} => {
const_decl.hash(state, engines);
}
Self::ConfigurableExpression {
decl: const_decl,
span: _,
call_path: _,
} => {
const_decl.hash(state, engines);
}
Self::ConstGenericExpression {
decl: const_generic_decl,
span: _,
call_path: _,
} => {
const_generic_decl.name().hash(state);
}
Self::VariableExpression {
name,
mutability,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
call_path: _,
span: _,
} => {
name.hash(state);
mutability.hash(state);
}
Self::Tuple { fields } => {
fields.hash(state, engines);
}
Self::ArrayExplicit {
contents,
elem_type: _,
} => {
contents.hash(state, engines);
}
Self::ArrayRepeat {
value,
length,
elem_type: _,
} => {
value.hash(state, engines);
length.hash(state, engines);
}
Self::ArrayIndex { prefix, index } => {
prefix.hash(state, engines);
index.hash(state, engines);
}
Self::StructExpression {
struct_id,
fields,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
instantiation_span: _,
call_path_binding: _,
} => {
HashWithEngines::hash(&struct_id, state, engines);
fields.hash(state, engines);
}
Self::CodeBlock(contents) => {
contents.hash(state, engines);
}
Self::MatchExp {
desugared,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
scrutinees: _,
} => {
desugared.hash(state, engines);
}
Self::IfExp {
condition,
then,
r#else,
} => {
condition.hash(state, engines);
then.hash(state, engines);
if let Some(x) = r#else.as_ref() {
x.hash(state, engines)
}
}
Self::AsmExpression {
registers,
body,
returns,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
whole_block_span: _,
} => {
registers.hash(state, engines);
body.hash(state);
returns.hash(state);
}
Self::StructFieldAccess {
prefix,
field_to_access,
resolved_type_of_parent,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
field_instantiation_span: _,
} => {
prefix.hash(state, engines);
field_to_access.hash(state, engines);
type_engine
.get(*resolved_type_of_parent)
.hash(state, engines);
}
Self::TupleElemAccess {
prefix,
elem_to_access_num,
resolved_type_of_parent,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
elem_to_access_span: _,
} => {
prefix.hash(state, engines);
elem_to_access_num.hash(state);
type_engine
.get(*resolved_type_of_parent)
.hash(state, engines);
}
Self::EnumInstantiation {
enum_ref,
variant_name,
tag,
contents,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
variant_instantiation_span: _,
call_path_binding: _,
call_path_decl: _,
} => {
enum_ref.hash(state, engines);
variant_name.hash(state);
tag.hash(state);
if let Some(x) = contents.as_ref() {
x.hash(state, engines)
}
}
Self::AbiCast {
abi_name,
address,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
} => {
abi_name.hash(state);
address.hash(state, engines);
}
Self::StorageAccess(exp) => {
exp.hash(state, engines);
}
Self::IntrinsicFunction(exp) => {
exp.hash(state, engines);
}
Self::AbiName(name) => {
name.hash(state);
}
Self::EnumTag { exp } => {
exp.hash(state, engines);
}
Self::UnsafeDowncast {
exp,
variant,
call_path_decl: _,
} => {
exp.hash(state, engines);
variant.hash(state, engines);
}
Self::WhileLoop { condition, body } => {
condition.hash(state, engines);
body.hash(state, engines);
}
Self::ForLoop { desugared } => {
desugared.hash(state, engines);
}
Self::Break | Self::Continue | Self::FunctionParameter => {}
Self::Reassignment(exp) => {
exp.hash(state, engines);
}
Self::ImplicitReturn(exp) | Self::Return(exp) => {
exp.hash(state, engines);
}
Self::Panic(exp) => {
exp.hash(state, engines);
}
Self::Ref(exp) | Self::Deref(exp) => {
exp.hash(state, engines);
}
}
}
}
impl SubstTypes for TyExpressionVariant {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
use TyExpressionVariant::*;
match self {
Literal(..) => HasChanges::No,
FunctionApplication {
arguments,
ref mut fn_ref,
ref mut method_target,
..
} => has_changes! {
arguments.subst(ctx);
if let Some(new_decl_ref) = fn_ref
.clone()
.subst_types_and_insert_new_with_parent(ctx)
{
fn_ref.replace_id(*new_decl_ref.id());
HasChanges::Yes
} else {
HasChanges::No
};
method_target.subst(ctx);
},
LazyOperator { lhs, rhs, .. } => has_changes! {
lhs.subst(ctx);
rhs.subst(ctx);
},
ConstantExpression { decl, .. } => decl.subst(ctx),
ConfigurableExpression { decl, .. } => decl.subst(ctx),
ConstGenericExpression { decl, .. } => decl.subst(ctx),
VariableExpression { .. } => HasChanges::No,
Tuple { fields } => fields.subst(ctx),
ArrayExplicit {
ref mut elem_type,
contents,
} => has_changes! {
elem_type.subst(ctx);
contents.subst(ctx);
},
ArrayRepeat {
ref mut elem_type,
value,
length,
} => has_changes! {
elem_type.subst(ctx);
value.subst(ctx);
length.subst(ctx);
},
ArrayIndex { prefix, index } => has_changes! {
prefix.subst(ctx);
index.subst(ctx);
},
StructExpression {
struct_id,
fields,
instantiation_span: _,
call_path_binding: _,
} => has_changes! {
if let Some(new_struct_ref) = struct_id
.clone()
.subst_types_and_insert_new(ctx) {
struct_id.replace_id(*new_struct_ref.id());
HasChanges::Yes
} else {
HasChanges::No
};
fields.subst(ctx);
},
CodeBlock(block) => block.subst(ctx),
FunctionParameter => HasChanges::No,
MatchExp { desugared, .. } => desugared.subst(ctx),
IfExp {
condition,
then,
r#else,
} => has_changes! {
condition.subst(ctx);
then.subst(ctx);
r#else.subst(ctx);
},
AsmExpression {
registers, //: Vec<TyAsmRegisterDeclaration>,
..
} => registers.subst(ctx),
// like a variable expression but it has multiple parts,
// like looking up a field in a struct
StructFieldAccess {
prefix,
field_to_access,
ref mut resolved_type_of_parent,
..
} => has_changes! {
resolved_type_of_parent.subst(ctx);
field_to_access.subst(ctx);
prefix.subst(ctx);
},
TupleElemAccess {
prefix,
ref mut resolved_type_of_parent,
..
} => has_changes! {
resolved_type_of_parent.subst(ctx);
prefix.subst(ctx);
},
EnumInstantiation {
enum_ref, contents, ..
} => has_changes! {
if let Some(new_enum_ref) = enum_ref
.clone()
.subst_types_and_insert_new(ctx)
{
enum_ref.replace_id(*new_enum_ref.id());
HasChanges::Yes
} else {
HasChanges::No
};
contents.subst(ctx);
},
AbiCast { address, .. } => address.subst(ctx),
// storage is never generic and cannot be monomorphized
StorageAccess { .. } => HasChanges::No,
IntrinsicFunction(kind) => kind.subst(ctx),
EnumTag { exp } => exp.subst(ctx),
UnsafeDowncast {
exp,
variant,
call_path_decl: _,
} => has_changes! {
exp.subst(ctx);
variant.subst(ctx);
},
AbiName(_) => HasChanges::No,
WhileLoop {
ref mut condition,
ref mut body,
} => {
condition.subst(ctx);
body.subst(ctx)
}
ForLoop { ref mut desugared } => desugared.subst(ctx),
Break => HasChanges::No,
Continue => HasChanges::No,
Reassignment(reassignment) => reassignment.subst(ctx),
ImplicitReturn(expr) | Return(expr) => expr.subst(ctx),
Panic(expr) => expr.subst(ctx),
Ref(exp) | Deref(exp) => exp.subst(ctx),
}
}
}
impl ReplaceDecls for TyExpressionVariant {
fn replace_decls_inner(
&mut self,
decl_mapping: &DeclMapping,
handler: &Handler,
ctx: &mut TypeCheckContext,
) -> Result<bool, ErrorEmitted> {
handler.scope(|handler| {
use TyExpressionVariant::*;
match self {
Literal(..) => Ok(false),
FunctionApplication {
ref mut fn_ref,
ref mut arguments,
call_path,
..
} => {
let mut has_changes = false;
has_changes |= fn_ref.replace_decls(decl_mapping, handler, ctx)?;
for (_, arg) in arguments.iter_mut() {
if let Ok(r) = arg.replace_decls(decl_mapping, handler, ctx) {
has_changes |= r;
}
}
let decl_engine = ctx.engines().de();
let mut method = (*decl_engine.get(fn_ref)).clone();
// Finds method implementation for method dummy and replaces it.
// This is required because dummy methods don't have type parameters from impl traits.
// Thus we use the implemented method that already contains all the required type parameters,
// including those from the impl trait.
if method.is_trait_method_dummy {
if let Some(implementing_for) = method.implementing_for {
let arguments_types = arguments
.iter()
.map(|a| a.1.return_type)
.collect::<Vec<_>>();
// find method and improve error
let find_handler = Handler::default();
let r = ctx.find_method_for_type(
&find_handler,
implementing_for,
&[ctx.namespace().current_package_name().clone()],
&call_path.suffix,
method.return_type.type_id,
&arguments_types,
None,
);
let _ =
handler.map_and_emit_errors_from(find_handler, |err| match err {
CompileError::MultipleApplicableItemsInScope {
span,
item_name,
item_kind,
as_traits,
} => {
if let Some(ty) = call_path.prefixes.get(1) {
Some(CompileError::MultipleApplicableItemsInScope {
span,
item_name,
item_kind,
as_traits: as_traits
.into_iter()
.map(|(tt, _)| (tt, ty.as_str().to_string()))
.collect(),
})
} else {
Some(CompileError::MultipleApplicableItemsInScope {
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/language/ty/expression/reassignment.rs | sway-core/src/language/ty/expression/reassignment.rs | use crate::{
decl_engine::*,
engine_threading::*,
has_changes,
language::ty::*,
semantic_analysis::{
TypeCheckAnalysis, TypeCheckAnalysisContext, TypeCheckContext, TypeCheckFinalization,
TypeCheckFinalizationContext,
},
type_system::*,
};
use serde::{Deserialize, Serialize};
use std::{
borrow::Cow,
hash::{Hash, Hasher},
};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::{Ident, Span, Spanned};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TyReassignment {
pub lhs: TyReassignmentTarget,
pub rhs: TyExpression,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TyReassignmentTarget {
/// An [TyExpression] representing a single variable or a path
/// to a part of an aggregate.
/// E.g.:
/// - `my_variable`
/// - `array[0].field.x.1`
ElementAccess {
/// [Ident] of the single variable, or the starting variable
/// of the path to a part of an aggregate.
base_name: Ident,
/// [TypeId] of the variable behind the `base_name`.
base_type: TypeId,
/// Indices representing the path from the `base_name` to the
/// final part of an aggregate.
/// Empty if the LHS of the reassignment is a single variable.
indices: Vec<ProjectionKind>,
},
/// An dereferencing [TyExpression] representing dereferencing
/// of an arbitrary reference expression with optional indices.
/// E.g.:
/// - *my_ref
/// - **if x > 0 { &mut &mut a } else { &mut &mut b }
/// - (*my_ref)\[0\]
/// - (**my_ref)\[0\]
///
/// The [TyExpression] is guaranteed to be of [TyExpressionVariant::Deref].
DerefAccess {
/// [TyExpression] of one or multiple nested [TyExpressionVariant::Deref].
exp: Box<TyExpression>,
/// Indices representing the path from the `base_name` to the
/// final part of an aggregate.
/// Empty if the LHS of the reassignment is a single variable.
indices: Vec<ProjectionKind>,
},
}
impl EqWithEngines for TyReassignmentTarget {}
impl PartialEqWithEngines for TyReassignmentTarget {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
let type_engine = ctx.engines().te();
match (self, other) {
(
TyReassignmentTarget::DerefAccess {
exp: l,
indices: l_indices,
},
TyReassignmentTarget::DerefAccess {
exp: r,
indices: r_indices,
},
) => (*l).eq(r, ctx) && l_indices.eq(r_indices, ctx),
(
TyReassignmentTarget::ElementAccess {
base_name: l_name,
base_type: l_type,
indices: l_indices,
},
TyReassignmentTarget::ElementAccess {
base_name: r_name,
base_type: r_type,
indices: r_indices,
},
) => {
l_name == r_name
&& (l_type == r_type
|| type_engine.get(*l_type).eq(&type_engine.get(*r_type), ctx))
&& l_indices.eq(r_indices, ctx)
}
_ => false,
}
}
}
impl EqWithEngines for TyReassignment {}
impl PartialEqWithEngines for TyReassignment {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.lhs.eq(&other.lhs, ctx) && self.rhs.eq(&other.rhs, ctx)
}
}
impl HashWithEngines for TyReassignmentTarget {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let type_engine = engines.te();
match self {
TyReassignmentTarget::DerefAccess { exp, indices } => {
exp.hash(state, engines);
indices.hash(state, engines);
}
TyReassignmentTarget::ElementAccess {
base_name,
base_type,
indices,
} => {
base_name.hash(state);
type_engine.get(*base_type).hash(state, engines);
indices.hash(state, engines);
}
};
}
}
impl HashWithEngines for TyReassignment {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyReassignment { lhs, rhs } = self;
lhs.hash(state, engines);
rhs.hash(state, engines);
}
}
impl SubstTypes for TyReassignmentTarget {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
match self {
TyReassignmentTarget::DerefAccess{exp, indices} => {
has_changes! {
exp.subst(ctx);
indices.subst(ctx);
}
},
TyReassignmentTarget::ElementAccess { base_type, indices, .. } => {
has_changes! {
base_type.subst(ctx);
indices.subst(ctx);
}
}
};
}
}
}
impl SubstTypes for TyReassignment {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
has_changes! {
self.lhs.subst(ctx);
self.rhs.subst(ctx);
}
}
}
impl ReplaceDecls for TyReassignmentTarget {
fn replace_decls_inner(
&mut self,
decl_mapping: &DeclMapping,
handler: &Handler,
ctx: &mut TypeCheckContext,
) -> Result<bool, ErrorEmitted> {
Ok(match self {
TyReassignmentTarget::DerefAccess { exp, indices } => {
let mut changed = exp.replace_decls(decl_mapping, handler, ctx)?;
changed |= indices
.iter_mut()
.map(|i| i.replace_decls(decl_mapping, handler, ctx))
.collect::<Result<Vec<bool>, _>>()?
.iter()
.any(|is_changed| *is_changed);
changed
}
TyReassignmentTarget::ElementAccess { indices, .. } => indices
.iter_mut()
.map(|i| i.replace_decls(decl_mapping, handler, ctx))
.collect::<Result<Vec<bool>, _>>()?
.iter()
.any(|is_changed| *is_changed),
})
}
}
impl ReplaceDecls for TyReassignment {
fn replace_decls_inner(
&mut self,
decl_mapping: &DeclMapping,
handler: &Handler,
ctx: &mut TypeCheckContext,
) -> Result<bool, ErrorEmitted> {
let lhs_changed = self.lhs.replace_decls(decl_mapping, handler, ctx)?;
let rhs_changed = self.rhs.replace_decls(decl_mapping, handler, ctx)?;
Ok(lhs_changed || rhs_changed)
}
}
impl TypeCheckAnalysis for TyReassignmentTarget {
fn type_check_analyze(
&self,
handler: &Handler,
ctx: &mut TypeCheckAnalysisContext,
) -> Result<(), ErrorEmitted> {
match self {
TyReassignmentTarget::DerefAccess { exp, indices } => {
exp.type_check_analyze(handler, ctx)?;
indices
.iter()
.map(|i| i.type_check_analyze(handler, ctx))
.collect::<Result<Vec<()>, _>>()
.map(|_| ())?
}
TyReassignmentTarget::ElementAccess { indices, .. } => indices
.iter()
.map(|i| i.type_check_analyze(handler, ctx))
.collect::<Result<Vec<()>, _>>()
.map(|_| ())?,
};
Ok(())
}
}
impl TypeCheckAnalysis for TyReassignment {
fn type_check_analyze(
&self,
handler: &Handler,
ctx: &mut TypeCheckAnalysisContext,
) -> Result<(), ErrorEmitted> {
self.lhs.type_check_analyze(handler, ctx)?;
self.rhs.type_check_analyze(handler, ctx)?;
Ok(())
}
}
impl TypeCheckFinalization for TyReassignmentTarget {
fn type_check_finalize(
&mut self,
handler: &Handler,
ctx: &mut TypeCheckFinalizationContext,
) -> Result<(), ErrorEmitted> {
match self {
TyReassignmentTarget::DerefAccess { exp, indices } => {
exp.type_check_finalize(handler, ctx)?;
indices
.iter_mut()
.map(|i| i.type_check_finalize(handler, ctx))
.collect::<Result<Vec<()>, _>>()
.map(|_| ())?;
}
TyReassignmentTarget::ElementAccess { indices, .. } => indices
.iter_mut()
.map(|i| i.type_check_finalize(handler, ctx))
.collect::<Result<Vec<()>, _>>()
.map(|_| ())?,
};
Ok(())
}
}
impl TypeCheckFinalization for TyReassignment {
fn type_check_finalize(
&mut self,
handler: &Handler,
ctx: &mut TypeCheckFinalizationContext,
) -> Result<(), ErrorEmitted> {
self.lhs.type_check_finalize(handler, ctx)?;
self.rhs.type_check_finalize(handler, ctx)?;
Ok(())
}
}
impl UpdateConstantExpression for TyReassignmentTarget {
fn update_constant_expression(&mut self, engines: &Engines, implementing_type: &TyDecl) {
match self {
TyReassignmentTarget::DerefAccess { exp, indices } => {
exp.update_constant_expression(engines, implementing_type);
indices
.iter_mut()
.for_each(|i| i.update_constant_expression(engines, implementing_type));
}
TyReassignmentTarget::ElementAccess { indices, .. } => {
indices
.iter_mut()
.for_each(|i| i.update_constant_expression(engines, implementing_type));
}
};
}
}
impl UpdateConstantExpression for TyReassignment {
fn update_constant_expression(&mut self, engines: &Engines, implementing_type: &TyDecl) {
self.lhs
.update_constant_expression(engines, implementing_type);
self.rhs
.update_constant_expression(engines, implementing_type);
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ProjectionKind {
StructField {
name: Ident,
field_to_access: Option<Box<TyStructField>>,
},
TupleField {
index: usize,
index_span: Span,
},
ArrayIndex {
index: Box<TyExpression>,
index_span: Span,
},
}
impl EqWithEngines for ProjectionKind {}
impl PartialEqWithEngines for ProjectionKind {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(
ProjectionKind::StructField {
name: l_name,
field_to_access: _,
},
ProjectionKind::StructField {
name: r_name,
field_to_access: _,
},
) => l_name == r_name,
(
ProjectionKind::TupleField {
index: l_index,
index_span: l_index_span,
},
ProjectionKind::TupleField {
index: r_index,
index_span: r_index_span,
},
) => l_index == r_index && l_index_span == r_index_span,
(
ProjectionKind::ArrayIndex {
index: l_index,
index_span: l_index_span,
},
ProjectionKind::ArrayIndex {
index: r_index,
index_span: r_index_span,
},
) => l_index.eq(r_index, ctx) && l_index_span == r_index_span,
_ => false,
}
}
}
impl HashWithEngines for ProjectionKind {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
use ProjectionKind::*;
std::mem::discriminant(self).hash(state);
match self {
StructField {
name,
field_to_access: _,
} => name.hash(state),
TupleField {
index,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
index_span: _,
} => index.hash(state),
ArrayIndex {
index,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
index_span: _,
} => {
index.hash(state, engines);
}
}
}
}
impl SubstTypes for ProjectionKind {
fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
use ProjectionKind::*;
match self {
ArrayIndex { index, .. } => index.subst(ctx),
_ => HasChanges::No,
}
}
}
impl ReplaceDecls for ProjectionKind {
fn replace_decls_inner(
&mut self,
decl_mapping: &DeclMapping,
handler: &Handler,
ctx: &mut TypeCheckContext,
) -> Result<bool, ErrorEmitted> {
use ProjectionKind::*;
match self {
ArrayIndex { index, .. } => index.replace_decls(decl_mapping, handler, ctx),
_ => Ok(false),
}
}
}
impl TypeCheckAnalysis for ProjectionKind {
fn type_check_analyze(
&self,
handler: &Handler,
ctx: &mut TypeCheckAnalysisContext,
) -> Result<(), ErrorEmitted> {
use ProjectionKind::*;
match self {
ArrayIndex { index, .. } => index.type_check_analyze(handler, ctx),
_ => Ok(()),
}
}
}
impl TypeCheckFinalization for ProjectionKind {
fn type_check_finalize(
&mut self,
handler: &Handler,
ctx: &mut TypeCheckFinalizationContext,
) -> Result<(), ErrorEmitted> {
use ProjectionKind::*;
match self {
ArrayIndex { index, .. } => index.type_check_finalize(handler, ctx),
_ => Ok(()),
}
}
}
impl UpdateConstantExpression for ProjectionKind {
fn update_constant_expression(&mut self, engines: &Engines, implementing_type: &TyDecl) {
use ProjectionKind::*;
#[allow(clippy::single_match)]
// To keep it consistent and same looking as the above implementations.
match self {
ArrayIndex { index, .. } => {
index.update_constant_expression(engines, implementing_type)
}
_ => (),
}
}
}
impl Spanned for ProjectionKind {
fn span(&self) -> Span {
match self {
ProjectionKind::StructField {
name,
field_to_access: _,
} => name.span(),
ProjectionKind::TupleField { index_span, .. } => index_span.clone(),
ProjectionKind::ArrayIndex { index_span, .. } => index_span.clone(),
}
}
}
impl ProjectionKind {
pub(crate) fn pretty_print(&self) -> Cow<'_, str> {
match self {
ProjectionKind::StructField {
name,
field_to_access: _,
} => Cow::Borrowed(name.as_str()),
ProjectionKind::TupleField { index, .. } => Cow::Owned(index.to_string()),
ProjectionKind::ArrayIndex { index, .. } => Cow::Owned(format!("{index:#?}")),
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/type_check_context.rs | sway-core/src/semantic_analysis/type_check_context.rs | #![allow(clippy::mutable_key_type)]
use std::collections::BTreeMap;
use crate::{
decl_engine::{DeclEngineGet, MaterializeConstGenerics},
engine_threading::*,
language::{
parsed::TreeType,
ty::{self, TyDecl, TyExpression},
CallPath, QualifiedCallPath, Visibility,
},
monomorphization::{monomorphize_with_modpath, MonomorphizeHelper},
namespace::{
IsExtendingExistingImpl, IsImplSelf, ModulePath, ResolvedDeclaration,
ResolvedTraitImplItem, TraitMap,
},
semantic_analysis::{
ast_node::{AbiMode, ConstShadowingMode},
Namespace,
},
type_system::{GenericArgument, SubstTypes, TypeId, TypeInfo},
EnforceTypeArguments, SubstTypesContext, TraitConstraint, TypeParameter, TypeSubstMap,
};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_features::ExperimentalFeatures;
use sway_types::{span::Span, Ident};
use super::{
namespace::{IsImplInterfaceSurface, Items, LexicalScopeId},
symbol_collection_context::SymbolCollectionContext,
type_resolve::{resolve_call_path, resolve_qualified_call_path, resolve_type, VisibilityCheck},
GenericShadowingMode,
};
/// Contextual state tracked and accumulated throughout type-checking.
pub struct TypeCheckContext<'a> {
/// The namespace context accumulated throughout type-checking.
///
/// Internally, this includes:
///
/// - The `root` module from which all other modules maybe be accessed using absolute paths.
/// - The `init` module used to initialize submodule namespaces.
/// - A `mod_path` that represents the current module being type-checked. This is automatically
/// updated upon entering/exiting submodules via the `enter_submodule` method.
pub(crate) namespace: &'a mut Namespace,
pub engines: &'a Engines,
/// Set of experimental flags.
pub(crate) experimental: ExperimentalFeatures,
/// Keeps the accumulated symbols previously collected.
pub(crate) collection_ctx: &'a mut SymbolCollectionContext,
// The following set of fields are intentionally private. When a `TypeCheckContext` is passed
// into a new node during type checking, these fields should be updated using the `with_*`
// methods which provides a new `TypeCheckContext`, ensuring we don't leak our changes into
// the parent nodes.
/// While type-checking an expression, this indicates the expected type.
///
/// Assists type inference.
type_annotation: TypeId,
/// Assists type inference.
function_type_annotation: TypeId,
/// When true unify_with_type_annotation will use unify_with_generic instead of the default unify.
/// This ensures that expected generic types are unified to more specific received types.
unify_generic: bool,
/// While type-checking an `impl` (whether inherent or for a `trait`/`abi`) this represents the
/// type for which we are implementing. For example in `impl Foo {}` or `impl Trait for Foo
/// {}`, this represents the type ID of `Foo`.
self_type: Option<TypeId>,
/// While type-checking an expression, this indicates the types to be substituted when a
/// type is resolved. This is required is to replace associated types, namely TypeInfo::TraitType.
type_subst: TypeSubstMap,
/// Whether or not we're within an `abi` implementation.
///
/// This is `ImplAbiFn` while checking `abi` implementations whether at their original impl
/// declaration or within an abi cast expression.
abi_mode: AbiMode,
/// Whether or not a const declaration shadows previous const declarations sequentially.
///
/// This is `Sequential` while checking const declarations in functions, otherwise `ItemStyle`.
pub(crate) const_shadowing_mode: ConstShadowingMode,
/// Whether or not a generic type parameters shadows previous generic type parameters.
///
/// This is `Disallow` everywhere except while checking type parameters bounds in struct instantiation.
generic_shadowing_mode: GenericShadowingMode,
/// Provides "help text" to `TypeError`s during unification.
// TODO: We probably shouldn't carry this through the `Context`, but instead pass it directly
// to `unify` as necessary?
help_text: &'static str,
/// Provides the kind of the module.
/// This is useful for example to throw an error when while loops are present in predicates.
kind: TreeType,
/// Indicates when semantic analysis should disallow functions. (i.e.
/// disallowing functions from being defined inside of another function
/// body).
disallow_functions: bool,
/// Indicates when semantic analysis is type checking storage declaration.
storage_declaration: bool,
// Indicates when we are collecting unifications.
collecting_unifications: bool,
// Indicates when we are doing the first pass of the code block type checking.
// In some nested places of the first pass we want to disable the first pass optimizations
// To disable those optimizations we can set this to false.
code_block_first_pass: bool,
}
impl<'a> TypeCheckContext<'a> {
/// Initialize a type-checking context with a namespace.
pub fn from_namespace(
namespace: &'a mut Namespace,
collection_ctx: &'a mut SymbolCollectionContext,
engines: &'a Engines,
experimental: ExperimentalFeatures,
) -> Self {
Self {
namespace,
engines,
collection_ctx,
type_annotation: engines.te().new_unknown(),
function_type_annotation: engines.te().new_unknown(),
unify_generic: false,
self_type: None,
type_subst: TypeSubstMap::new(),
help_text: "",
abi_mode: AbiMode::NonAbi,
const_shadowing_mode: ConstShadowingMode::ItemStyle,
generic_shadowing_mode: GenericShadowingMode::Disallow,
kind: TreeType::Contract,
disallow_functions: false,
storage_declaration: false,
experimental,
collecting_unifications: false,
code_block_first_pass: false,
}
}
/// Initialize a context at the top-level of a module with its namespace.
///
/// Initializes with:
///
/// - type_annotation: unknown
/// - mode: NoneAbi
/// - help_text: ""
pub fn from_root(
root_namespace: &'a mut Namespace,
collection_ctx: &'a mut SymbolCollectionContext,
engines: &'a Engines,
experimental: ExperimentalFeatures,
) -> Self {
Self::from_module_namespace(root_namespace, collection_ctx, engines, experimental)
}
fn from_module_namespace(
namespace: &'a mut Namespace,
collection_ctx: &'a mut SymbolCollectionContext,
engines: &'a Engines,
experimental: ExperimentalFeatures,
) -> Self {
Self {
collection_ctx,
namespace,
engines,
type_annotation: engines.te().new_unknown(),
function_type_annotation: engines.te().new_unknown(),
unify_generic: false,
self_type: None,
type_subst: TypeSubstMap::new(),
help_text: "",
abi_mode: AbiMode::NonAbi,
const_shadowing_mode: ConstShadowingMode::ItemStyle,
generic_shadowing_mode: GenericShadowingMode::Disallow,
kind: TreeType::Contract,
disallow_functions: false,
storage_declaration: false,
experimental,
collecting_unifications: false,
code_block_first_pass: false,
}
}
/// Create a new context that mutably borrows the inner `namespace` with a lifetime bound by
/// `self`.
///
/// This is particularly useful when type-checking a node that has more than one child node
/// (very often the case). By taking the context with the namespace lifetime bound to `self`
/// rather than the original namespace reference, we instead restrict the returned context to
/// the local scope and avoid consuming the original context when providing context to the
/// first visited child node.
pub fn by_ref(&mut self) -> TypeCheckContext<'_> {
TypeCheckContext {
namespace: self.namespace,
collection_ctx: self.collection_ctx,
type_annotation: self.type_annotation,
function_type_annotation: self.function_type_annotation,
unify_generic: self.unify_generic,
self_type: self.self_type,
type_subst: self.type_subst.clone(),
abi_mode: self.abi_mode.clone(),
const_shadowing_mode: self.const_shadowing_mode,
generic_shadowing_mode: self.generic_shadowing_mode,
help_text: self.help_text,
kind: self.kind,
engines: self.engines,
disallow_functions: self.disallow_functions,
storage_declaration: self.storage_declaration,
experimental: self.experimental,
collecting_unifications: self.collecting_unifications,
code_block_first_pass: self.code_block_first_pass,
}
}
/// Scope the `TypeCheckContext` with a new lexical scope, and set up the collection context
/// so it enters the lexical scope corresponding to the given span.
pub fn scoped<T>(
&mut self,
handler: &Handler,
span: Option<Span>,
with_scoped_ctx: impl FnOnce(&mut TypeCheckContext) -> Result<T, ErrorEmitted>,
) -> Result<T, ErrorEmitted> {
self.scoped_and_lexical_scope_id(handler, span, with_scoped_ctx)
.0
}
/// Scope the `TypeCheckContext` with a new lexical scope, and set up the collection context
/// so it enters the lexical scope corresponding to the given span.
pub fn scoped_and_lexical_scope_id<T>(
&mut self,
handler: &Handler,
span: Option<Span>,
with_scoped_ctx: impl FnOnce(&mut TypeCheckContext) -> Result<T, ErrorEmitted>,
) -> (Result<T, ErrorEmitted>, LexicalScopeId) {
let engines = self.engines;
if let Some(span) = span {
self.namespace_scoped(engines, |ctx| {
ctx.collection_ctx.enter_lexical_scope(
handler,
ctx.engines,
span,
|scoped_collection_ctx| {
let mut ctx = TypeCheckContext {
collection_ctx: scoped_collection_ctx,
namespace: ctx.namespace,
type_annotation: ctx.type_annotation,
function_type_annotation: ctx.function_type_annotation,
unify_generic: ctx.unify_generic,
self_type: ctx.self_type,
type_subst: ctx.type_subst.clone(),
abi_mode: ctx.abi_mode.clone(),
const_shadowing_mode: ctx.const_shadowing_mode,
generic_shadowing_mode: ctx.generic_shadowing_mode,
help_text: ctx.help_text,
kind: ctx.kind,
engines: ctx.engines,
disallow_functions: ctx.disallow_functions,
storage_declaration: ctx.storage_declaration,
experimental: ctx.experimental,
collecting_unifications: ctx.collecting_unifications,
code_block_first_pass: ctx.code_block_first_pass,
};
with_scoped_ctx(&mut ctx)
},
)
})
} else {
self.namespace_scoped(engines, |ctx| with_scoped_ctx(ctx))
}
}
/// Scope the `CollectionContext` with a new lexical scope.
pub fn namespace_scoped<T>(
&mut self,
engines: &Engines,
with_scoped_ctx: impl FnOnce(&mut TypeCheckContext) -> Result<T, ErrorEmitted>,
) -> (Result<T, ErrorEmitted>, LexicalScopeId) {
let lexical_scope_id: LexicalScopeId = self
.namespace
.current_module_mut()
.write(engines, |m| m.push_new_lexical_scope(Span::dummy(), None));
let ret = with_scoped_ctx(self);
self.namespace
.current_module_mut()
.write(engines, |m| m.pop_lexical_scope());
(ret, lexical_scope_id)
}
/// Enter the submodule with the given name and produce a type-check context ready for
/// type-checking its content.
///
/// Returns the result of the given `with_submod_ctx` function.
pub fn enter_submodule<T>(
&mut self,
handler: &Handler,
mod_name: Ident,
visibility: Visibility,
module_span: Span,
with_submod_ctx: impl FnOnce(TypeCheckContext) -> T,
) -> Result<T, ErrorEmitted> {
let experimental = self.experimental;
// We're checking a submodule, so no need to pass through anything other than the
// namespace and the engines.
let engines = self.engines;
self.namespace.enter_submodule(
handler,
engines,
mod_name.clone(),
visibility,
module_span.clone(),
true,
)?;
self.collection_ctx.enter_submodule(
handler,
engines,
mod_name,
visibility,
module_span,
|submod_collection_ctx| {
let submod_ctx = TypeCheckContext::from_namespace(
self.namespace,
submod_collection_ctx,
engines,
experimental,
);
let ret = with_submod_ctx(submod_ctx);
self.namespace.pop_submodule();
ret
},
)
}
/// Returns a mutable reference to the current namespace.
pub fn namespace_mut(&mut self) -> &mut Namespace {
self.namespace
}
/// Returns a reference to the current namespace.
pub fn namespace(&self) -> &Namespace {
self.namespace
}
/// Map this `TypeCheckContext` instance to a new one with the given `help_text`.
pub(crate) fn with_help_text(self, help_text: &'static str) -> Self {
Self { help_text, ..self }
}
/// Map this `TypeCheckContext` instance to a new one with the given type annotation.
pub(crate) fn with_type_annotation(self, type_annotation: TypeId) -> Self {
Self {
type_annotation,
..self
}
}
/// Map this `TypeCheckContext` instance to a new one with the given type annotation.
pub(crate) fn with_function_type_annotation(self, function_type_annotation: TypeId) -> Self {
Self {
function_type_annotation,
..self
}
}
/// Map this `TypeCheckContext` instance to a new one with the given type annotation.
pub(crate) fn with_unify_generic(self, unify_generic: bool) -> Self {
Self {
unify_generic,
..self
}
}
/// Map this `TypeCheckContext` instance to a new one with the given type subst.
pub(crate) fn with_type_subst(self, type_subst: &TypeSubstMap) -> Self {
Self {
type_subst: type_subst.clone(),
..self
}
}
/// Map this `TypeCheckContext` instance to a new one with the given ABI `mode`.
pub(crate) fn with_abi_mode(self, abi_mode: AbiMode) -> Self {
Self { abi_mode, ..self }
}
/// Map this `TypeCheckContext` instance to a new one with the given const shadowing `mode`.
pub(crate) fn with_const_shadowing_mode(
self,
const_shadowing_mode: ConstShadowingMode,
) -> Self {
Self {
const_shadowing_mode,
..self
}
}
/// Map this `TypeCheckContext` instance to a new one with the given generic shadowing `mode`.
pub(crate) fn with_generic_shadowing_mode(
self,
generic_shadowing_mode: GenericShadowingMode,
) -> Self {
Self {
generic_shadowing_mode,
..self
}
}
/// Map this `TypeCheckContext` instance to a new one with the given module kind.
pub(crate) fn with_kind(self, kind: TreeType) -> Self {
Self { kind, ..self }
}
/// Map this `TypeCheckContext` instance to a new one with the given self type.
pub(crate) fn with_self_type(self, self_type: Option<TypeId>) -> Self {
Self { self_type, ..self }
}
pub(crate) fn with_collecting_unifications(self) -> Self {
Self {
collecting_unifications: true,
..self
}
}
pub(crate) fn with_code_block_first_pass(self, value: bool) -> Self {
Self {
code_block_first_pass: value,
..self
}
}
/// Map this `TypeCheckContext` instance to a new one with
/// `disallow_functions` set to `true`.
pub(crate) fn disallow_functions(self) -> Self {
Self {
disallow_functions: true,
..self
}
}
/// Map this `TypeCheckContext` instance to a new one with
/// `disallow_functions` set to `false`.
pub(crate) fn allow_functions(self) -> Self {
Self {
disallow_functions: false,
..self
}
}
/// Map this `TypeCheckContext` instance to a new one with
/// `storage_declaration` set to `true`.
pub(crate) fn with_storage_declaration(self) -> Self {
Self {
storage_declaration: true,
..self
}
}
// A set of accessor methods. We do this rather than making the fields `pub` in order to ensure
// that these are only updated via the `with_*` methods that produce a new `TypeCheckContext`.
pub(crate) fn help_text(&self) -> &'static str {
self.help_text
}
pub(crate) fn type_annotation(&self) -> TypeId {
self.type_annotation
}
pub(crate) fn function_type_annotation(&self) -> TypeId {
self.function_type_annotation
}
pub(crate) fn unify_generic(&self) -> bool {
self.unify_generic
}
pub(crate) fn self_type(&self) -> Option<TypeId> {
self.self_type
}
pub(crate) fn subst_ctx(&self, handler: &'a Handler) -> SubstTypesContext {
SubstTypesContext::new(
handler,
self.engines(),
&self.type_subst,
!self.code_block_first_pass(),
)
}
pub(crate) fn abi_mode(&self) -> AbiMode {
self.abi_mode.clone()
}
#[allow(dead_code)]
pub(crate) fn kind(&self) -> TreeType {
self.kind
}
pub(crate) fn functions_disallowed(&self) -> bool {
self.disallow_functions
}
pub(crate) fn storage_declaration(&self) -> bool {
self.storage_declaration
}
pub(crate) fn collecting_unifications(&self) -> bool {
self.collecting_unifications
}
pub(crate) fn code_block_first_pass(&self) -> bool {
self.code_block_first_pass
}
/// Get the engines needed for engine threading.
pub(crate) fn engines(&self) -> &'a Engines {
self.engines
}
// Provide some convenience functions around the inner context.
/// Short-hand for calling the `monomorphize` function in the type engine
pub(crate) fn monomorphize<T>(
&mut self,
handler: &Handler,
value: &mut T,
type_arguments: &mut [GenericArgument],
const_generics: BTreeMap<String, TyExpression>,
enforce_type_arguments: EnforceTypeArguments,
call_site_span: &Span,
) -> Result<(), ErrorEmitted>
where
T: MonomorphizeHelper + SubstTypes + MaterializeConstGenerics,
{
let mod_path = self.namespace().current_mod_path().clone();
monomorphize_with_modpath(
handler,
self.engines(),
self.namespace(),
value,
type_arguments,
const_generics,
enforce_type_arguments,
call_site_span,
&mod_path,
self.self_type(),
&self.subst_ctx(handler),
)
}
/// Short-hand around `type_system::unify_`, where the `TypeCheckContext`
/// provides the type annotation and help text.
pub(crate) fn unify_with_type_annotation(&self, handler: &Handler, ty: TypeId, span: &Span) {
if self.unify_generic() {
self.engines.te().unify_with_generic(
handler,
self.engines(),
ty,
self.type_annotation(),
span,
self.help_text(),
|| None,
)
} else {
self.engines.te().unify(
handler,
self.engines(),
ty,
self.type_annotation(),
span,
self.help_text(),
|| None,
)
}
}
/// Short-hand for calling [Namespace::insert_symbol] with the `const_shadowing_mode` provided by
/// the `TypeCheckContext`.
pub(crate) fn insert_symbol(
&mut self,
handler: &Handler,
name: Ident,
item: TyDecl,
) -> Result<(), ErrorEmitted> {
let const_shadowing_mode = self.const_shadowing_mode;
let generic_shadowing_mode = self.generic_shadowing_mode;
let collecting_unifications = self.collecting_unifications;
let engines = self.engines();
Items::insert_symbol(
handler,
engines,
self.namespace_mut().current_module_mut(),
name,
ResolvedDeclaration::Typed(item),
const_shadowing_mode,
generic_shadowing_mode,
collecting_unifications,
)
}
/// Short-hand for calling [resolve_type] on `root` with the `mod_path`.
pub(crate) fn resolve_type(
&self,
handler: &Handler,
type_id: TypeId,
span: &Span,
enforce_type_arguments: EnforceTypeArguments,
type_info_prefix: Option<&ModulePath>,
) -> Result<TypeId, ErrorEmitted> {
let mod_path = self.namespace().current_mod_path().clone();
resolve_type(
handler,
self.engines(),
self.namespace(),
&mod_path,
type_id,
span,
enforce_type_arguments,
type_info_prefix,
self.self_type(),
&self.subst_ctx(handler),
VisibilityCheck::Yes,
)
}
pub(crate) fn resolve_qualified_call_path(
&mut self,
handler: &Handler,
qualified_call_path: &QualifiedCallPath,
) -> Result<ty::TyDecl, ErrorEmitted> {
resolve_qualified_call_path(
handler,
self.engines(),
self.namespace(),
&self.namespace().current_mod_path().clone(),
qualified_call_path,
self.self_type(),
&self.subst_ctx(handler),
VisibilityCheck::Yes,
)
.map(|d| d.expect_typed())
}
/// Short-hand for calling [Root::resolve_symbol] on `root` with the `mod_path`.
pub(crate) fn resolve_symbol(
&self,
handler: &Handler,
symbol: &Ident,
) -> Result<ty::TyDecl, ErrorEmitted> {
resolve_call_path(
handler,
self.engines(),
self.namespace(),
self.namespace().current_mod_path(),
&symbol.clone().into(),
self.self_type(),
VisibilityCheck::No,
)
.map(|d| d.expect_typed())
}
/// Short-hand for calling [Root::resolve_call_path_with_visibility_check] on `root` with the `mod_path`.
pub(crate) fn resolve_call_path_with_visibility_check(
&self,
handler: &Handler,
call_path: &CallPath,
) -> Result<ty::TyDecl, ErrorEmitted> {
resolve_call_path(
handler,
self.engines(),
self.namespace(),
self.namespace().current_mod_path(),
call_path,
self.self_type(),
VisibilityCheck::Yes,
)
.map(|d| d.expect_typed())
}
/// Short-hand for calling [Root::resolve_call_path] on `root` with the `mod_path`.
pub(crate) fn resolve_call_path(
&self,
handler: &Handler,
call_path: &CallPath,
) -> Result<ty::TyDecl, ErrorEmitted> {
resolve_call_path(
handler,
self.engines(),
self.namespace(),
self.namespace().current_mod_path(),
call_path,
self.self_type(),
VisibilityCheck::No,
)
.map(|d| d.expect_typed())
}
/// Short-hand for performing a [Module::star_import] with `mod_path` as the destination.
pub(crate) fn star_import(
&mut self,
handler: &Handler,
src: &ModulePath,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
let engines = self.engines;
self.namespace_mut()
.star_import_to_current_module(handler, engines, src, visibility)
}
/// Short-hand for performing a [Module::variant_star_import] with `mod_path` as the destination.
pub(crate) fn variant_star_import(
&mut self,
handler: &Handler,
src: &ModulePath,
enum_name: &Ident,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
let engines = self.engines;
self.namespace_mut()
.variant_star_import_to_current_module(handler, engines, src, enum_name, visibility)
}
/// Short-hand for performing a [Module::self_import] with `mod_path` as the destination.
pub(crate) fn self_import(
&mut self,
handler: &Handler,
src: &ModulePath,
alias: Option<Ident>,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
let engines = self.engines;
self.namespace_mut()
.self_import_to_current_module(handler, engines, src, alias, visibility)
}
// Import all impls for a struct/enum. Do nothing for other types.
pub(crate) fn impls_import(&mut self, engines: &Engines, type_id: TypeId) {
let type_info = engines.te().get(type_id);
let decl_call_path = match &*type_info {
TypeInfo::Enum(decl_id) => {
let decl = engines.de().get(decl_id);
decl.call_path.clone()
}
TypeInfo::Struct(decl_id) => {
let decl = engines.de().get(decl_id);
decl.call_path.clone()
}
_ => return,
};
let mut impls_to_insert = TraitMap::default();
let Some(src_mod) = &self
.namespace()
.module_from_absolute_path(&decl_call_path.prefixes)
else {
return;
};
let _ = src_mod.walk_scope_chain_early_return(|lexical_scope| {
impls_to_insert.extend(
lexical_scope
.items
.implemented_traits
.filter_by_type_item_import(type_id, engines),
engines,
);
Ok(None::<()>)
});
let dst_mod = self.namespace_mut().current_module_mut();
dst_mod
.current_items_mut()
.implemented_traits
.extend(impls_to_insert, engines);
}
/// Short-hand for performing a [Module::item_import] with `mod_path` as the destination.
pub(crate) fn item_import(
&mut self,
handler: &Handler,
src: &ModulePath,
item: &Ident,
alias: Option<Ident>,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
let engines = self.engines;
self.namespace_mut()
.item_import_to_current_module(handler, engines, src, item, alias, visibility)
}
/// Short-hand for performing a [Module::variant_import] with `mod_path` as the destination.
#[allow(clippy::too_many_arguments)]
pub(crate) fn variant_import(
&mut self,
handler: &Handler,
src: &ModulePath,
enum_name: &Ident,
variant_name: &Ident,
alias: Option<Ident>,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
let engines = self.engines;
self.namespace_mut().variant_import_to_current_module(
handler,
engines,
src,
enum_name,
variant_name,
alias,
visibility,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn insert_trait_implementation(
&mut self,
handler: &Handler,
trait_name: CallPath,
trait_type_args: Vec<GenericArgument>,
type_id: TypeId,
mut impl_type_parameters: Vec<TypeParameter>,
items: &[ty::TyImplItem],
impl_span: &Span,
trait_decl_span: Option<Span>,
is_impl_self: IsImplSelf,
is_extending_existing_impl: IsExtendingExistingImpl,
is_impl_interface_surface: IsImplInterfaceSurface,
) -> Result<(), ErrorEmitted> {
let engines = self.engines;
// Use trait name with full path, improves consistency between
// this inserting and getting in `get_methods_for_type_and_trait_name`.
for tc in impl_type_parameters
.iter_mut()
.filter_map(|x| x.as_type_parameter_mut())
.flat_map(|x| x.trait_constraints.iter_mut())
{
tc.trait_name = tc.trait_name.to_fullpath(self.engines(), self.namespace())
}
let impl_type_parameters_ids = impl_type_parameters
.iter()
.map(|type_parameter| engines.te().new_type_param(type_parameter.clone()))
.collect::<Vec<_>>();
// CallPath::to_fullpath gives a resolvable path, but is not guaranteed to provide the path
// to the actual trait declaration. Since the path of the trait declaration is used as a key
// in the trait map, we need to find the actual declaration path.
let canonical_trait_path = trait_name.to_canonical_path(self.engines(), self.namespace());
let items = items
.iter()
.map(|item| ResolvedTraitImplItem::Typed(item.clone()))
.collect::<Vec<_>>();
self.namespace_mut()
.current_module_mut()
.current_items_mut()
.implemented_traits
.insert(
handler,
canonical_trait_path,
trait_type_args,
type_id,
impl_type_parameters_ids,
&items,
impl_span,
trait_decl_span,
is_impl_self,
is_extending_existing_impl,
is_impl_interface_surface,
engines,
)
}
pub(crate) fn get_items_for_type_and_trait_name(
&self,
handler: &Handler,
type_id: TypeId,
trait_name: &CallPath,
) -> Vec<ty::TyTraitItem> {
self.get_items_for_type_and_trait_name_and_trait_type_arguments(
handler,
type_id,
trait_name,
&[],
)
}
pub(crate) fn get_items_for_type_and_trait_name_and_trait_type_arguments(
&self,
handler: &Handler,
type_id: TypeId,
trait_name: &CallPath,
trait_type_args: &[GenericArgument],
) -> Vec<ty::TyTraitItem> {
// CallPath::to_fullpath gives a resolvable path, but is not guaranteed to provide the path
// to the actual trait declaration. Since the path of the trait declaration is used as a key
// in the trait map, we need to find the actual declaration path.
let canonical_trait_path = trait_name.to_canonical_path(self.engines(), self.namespace());
TraitMap::get_items_for_type_and_trait_name_and_trait_type_arguments_typed(
handler,
self.namespace().current_module(),
self.engines,
type_id,
&canonical_trait_path,
trait_type_args,
)
}
pub fn check_type_impls_traits(
&mut self,
type_id: TypeId,
constraints: &[TraitConstraint],
) -> bool {
let handler = Handler::default();
let engines = self.engines;
TraitMap::check_if_trait_constraints_are_satisfied_for_type(
&handler,
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/type_check_finalization.rs | sway-core/src/semantic_analysis/type_check_finalization.rs | //! This module handles the process of iterating through the typed AST and finishing the type
//! checking step, for type checking steps that need to look at information that was computed
//! from the initial type checked tree.
use sway_error::handler::{ErrorEmitted, Handler};
use crate::Engines;
use super::TypeCheckContext;
// A simple context that is used to finish type checking.
pub struct TypeCheckFinalizationContext<'eng, 'ctx> {
pub(crate) engines: &'eng Engines,
#[allow(dead_code)]
pub(crate) type_check_ctx: TypeCheckContext<'ctx>,
}
impl<'eng, 'ctx> TypeCheckFinalizationContext<'eng, 'ctx> {
pub fn new(engines: &'eng Engines, type_check_ctx: TypeCheckContext<'ctx>) -> Self {
Self {
engines,
type_check_ctx,
}
}
}
pub(crate) trait TypeCheckFinalization {
fn type_check_finalize(
&mut self,
handler: &Handler,
ctx: &mut TypeCheckFinalizationContext,
) -> Result<(), ErrorEmitted>;
}
impl<T: TypeCheckFinalization + Clone> TypeCheckFinalization for std::sync::Arc<T> {
fn type_check_finalize(
&mut self,
handler: &Handler,
ctx: &mut TypeCheckFinalizationContext,
) -> Result<(), ErrorEmitted> {
if let Some(item) = std::sync::Arc::get_mut(self) {
item.type_check_finalize(handler, ctx)
} else {
let mut item = self.as_ref().clone();
item.type_check_finalize(handler, ctx)?;
*self = std::sync::Arc::new(item);
Ok(())
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/symbol_resolve.rs | sway-core/src/semantic_analysis/symbol_resolve.rs | use sway_error::{error::CompileError, handler::Handler};
use crate::{
ast_elements::{binding::SymbolResolveTypeBinding, type_argument::GenericTypeArgument},
decl_engine::{parsed_engine::ParsedDeclEngineReplace, parsed_id::ParsedDeclId},
language::{
parsed::{
AbiDeclaration, ArrayExpression, AstNode, AstNodeContent, CodeBlock,
ConfigurableDeclaration, ConstantDeclaration, Declaration, EnumDeclaration,
EnumVariant, Expression, ExpressionKind, FunctionDeclaration, FunctionParameter,
ImplItem, ImplSelfOrTrait, ParseModule, ParseProgram, ReassignmentTarget, Scrutinee,
StorageDeclaration, StorageEntry, StructDeclaration, StructExpressionField,
StructField, StructScrutineeField, Supertrait, TraitDeclaration, TraitFn, TraitItem,
TraitTypeDeclaration, TypeAliasDeclaration, VariableDeclaration,
},
CallPath, CallPathTree, ResolvedCallPath,
},
GenericArgument, TraitConstraint, TypeBinding, TypeParameter,
};
use super::symbol_resolve_context::SymbolResolveContext;
pub trait ResolveSymbols {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext);
}
impl ResolveSymbols for ParseProgram {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
let ParseProgram { root, .. } = self;
root.resolve_symbols(handler, ctx.by_ref());
}
}
impl ResolveSymbols for ParseModule {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
let ParseModule {
submodules,
tree,
module_eval_order,
attributes: _,
span: _,
hash: _,
..
} = self;
// Analyze submodules first in order of evaluation previously computed by the dependency graph.
module_eval_order.iter().for_each(|eval_mod_name| {
let (_name, submodule) = submodules
.iter_mut()
.find(|(submod_name, _submodule)| eval_mod_name == submod_name)
.unwrap();
submodule.module.resolve_symbols(handler, ctx.by_ref());
});
tree.root_nodes
.iter_mut()
.for_each(|node| node.resolve_symbols(handler, ctx.by_ref()))
}
}
impl ResolveSymbols for AstNode {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
match &mut self.content {
AstNodeContent::UseStatement(_) => {}
AstNodeContent::Declaration(decl) => decl.resolve_symbols(handler, ctx),
AstNodeContent::Expression(expr) => expr.resolve_symbols(handler, ctx),
AstNodeContent::IncludeStatement(_) => {}
AstNodeContent::Error(_, _) => {}
}
}
}
impl ResolveSymbols for Declaration {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
match self {
Declaration::VariableDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::FunctionDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::TraitDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::StructDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::EnumDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::EnumVariantDeclaration(_decl) => unreachable!(),
Declaration::ImplSelfOrTrait(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::AbiDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::ConstantDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::StorageDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::TypeAliasDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::TraitTypeDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::TraitFnDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::ConfigurableDeclaration(decl_id) => decl_id.resolve_symbols(handler, ctx),
Declaration::ConstGenericDeclaration(_) => {
handler.emit_err(CompileError::Internal(
"Unexpected error on const generics",
self.span(ctx.engines),
));
}
}
}
}
impl ResolveSymbols for ParsedDeclId<VariableDeclaration> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut var_decl = pe.get_variable(self).as_ref().clone();
var_decl.body.resolve_symbols(handler, ctx);
pe.replace(*self, var_decl);
}
}
impl ResolveSymbols for ParsedDeclId<FunctionDeclaration> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut fn_decl = pe.get_function(self).as_ref().clone();
fn_decl.body.resolve_symbols(handler, ctx);
pe.replace(*self, fn_decl);
}
}
impl ResolveSymbols for ParsedDeclId<TraitDeclaration> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut trait_decl = ctx.engines().pe().get_trait(self).as_ref().clone();
trait_decl.resolve_symbols(handler, ctx);
pe.replace(*self, trait_decl);
}
}
impl ResolveSymbols for ParsedDeclId<StructDeclaration> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut struct_decl = ctx.engines().pe().get_struct(self).as_ref().clone();
struct_decl.resolve_symbols(handler, ctx);
pe.replace(*self, struct_decl);
}
}
impl ResolveSymbols for ParsedDeclId<EnumDeclaration> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut enum_decl = ctx.engines().pe().get_enum(self).as_ref().clone();
enum_decl.resolve_symbols(handler, ctx);
pe.replace(*self, enum_decl);
}
}
impl ResolveSymbols for ParsedDeclId<ConfigurableDeclaration> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut configurable_decl = ctx.engines().pe().get_configurable(self).as_ref().clone();
configurable_decl.resolve_symbols(handler, ctx);
pe.replace(*self, configurable_decl);
}
}
impl ResolveSymbols for ParsedDeclId<ConstantDeclaration> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut constant_decl = ctx.engines().pe().get_constant(self).as_ref().clone();
constant_decl.resolve_symbols(handler, ctx);
pe.replace(*self, constant_decl);
}
}
impl ResolveSymbols for ParsedDeclId<TraitTypeDeclaration> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut trait_type_decl = ctx.engines().pe().get_trait_type(self).as_ref().clone();
trait_type_decl.resolve_symbols(handler, ctx);
pe.replace(*self, trait_type_decl);
}
}
impl ResolveSymbols for ParsedDeclId<TraitFn> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut trait_fn_decl = ctx.engines().pe().get_trait_fn(self).as_ref().clone();
trait_fn_decl.resolve_symbols(handler, ctx);
pe.replace(*self, trait_fn_decl);
}
}
impl ResolveSymbols for ParsedDeclId<ImplSelfOrTrait> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut impl_self_or_trait = ctx
.engines()
.pe()
.get_impl_self_or_trait(self)
.as_ref()
.clone();
impl_self_or_trait.resolve_symbols(handler, ctx);
pe.replace(*self, impl_self_or_trait);
}
}
impl ResolveSymbols for ParsedDeclId<AbiDeclaration> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut abi_decl = ctx.engines().pe().get_abi(self).as_ref().clone();
abi_decl.resolve_symbols(handler, ctx);
pe.replace(*self, abi_decl);
}
}
impl ResolveSymbols for ParsedDeclId<StorageDeclaration> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut storage_decl = ctx.engines().pe().get_storage(self).as_ref().clone();
storage_decl.resolve_symbols(handler, ctx);
pe.replace(*self, storage_decl);
}
}
impl ResolveSymbols for ParsedDeclId<TypeAliasDeclaration> {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
let pe = ctx.engines().pe();
let mut type_alias = ctx.engines().pe().get_type_alias(self).as_ref().clone();
type_alias.resolve_symbols(handler, ctx);
pe.replace(*self, type_alias);
}
}
impl ResolveSymbols for ConfigurableDeclaration {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.type_ascription.resolve_symbols(handler, ctx.by_ref());
if let Some(value) = self.value.as_mut() {
value.resolve_symbols(handler, ctx.by_ref())
}
}
}
impl ResolveSymbols for ConstantDeclaration {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.type_ascription.resolve_symbols(handler, ctx.by_ref());
if let Some(value) = self.value.as_mut() {
value.resolve_symbols(handler, ctx.by_ref())
}
}
}
impl ResolveSymbols for StructDeclaration {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.type_parameters
.iter_mut()
.for_each(|tp| tp.resolve_symbols(handler, ctx.by_ref()));
self.fields
.iter_mut()
.for_each(|f| f.resolve_symbols(handler, ctx.by_ref()));
}
}
impl ResolveSymbols for StructField {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
self.type_argument.resolve_symbols(handler, ctx);
}
}
impl ResolveSymbols for EnumDeclaration {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.type_parameters
.iter_mut()
.for_each(|tp| tp.resolve_symbols(handler, ctx.by_ref()));
self.variants
.iter_mut()
.for_each(|f| f.resolve_symbols(handler, ctx.by_ref()));
}
}
impl ResolveSymbols for EnumVariant {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
self.type_argument.resolve_symbols(handler, ctx);
}
}
impl ResolveSymbols for TraitDeclaration {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.supertraits
.iter_mut()
.for_each(|st| st.resolve_symbols(handler, ctx.by_ref()));
self.interface_surface
.iter_mut()
.for_each(|item| item.resolve_symbols(handler, ctx.by_ref()));
self.methods
.iter_mut()
.for_each(|m| m.resolve_symbols(handler, ctx.by_ref()));
}
}
impl ResolveSymbols for AbiDeclaration {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.supertraits
.iter_mut()
.for_each(|st| st.resolve_symbols(handler, ctx.by_ref()));
self.interface_surface
.iter_mut()
.for_each(|item| item.resolve_symbols(handler, ctx.by_ref()));
self.methods
.iter_mut()
.for_each(|m| m.resolve_symbols(handler, ctx.by_ref()));
}
}
impl ResolveSymbols for TraitItem {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
match self {
TraitItem::TraitFn(ref mut id) => id.resolve_symbols(handler, ctx.by_ref()),
TraitItem::Constant(ref mut id) => id.resolve_symbols(handler, ctx.by_ref()),
TraitItem::Type(ref mut id) => id.resolve_symbols(handler, ctx.by_ref()),
TraitItem::Error(_, _) => {}
}
}
}
impl ResolveSymbols for TraitFn {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.parameters
.iter_mut()
.for_each(|f| f.resolve_symbols(handler, ctx.by_ref()));
self.return_type.resolve_symbols(handler, ctx.by_ref());
}
}
impl ResolveSymbols for Supertrait {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.name.resolve_symbols(handler, ctx.by_ref());
}
}
impl ResolveSymbols for FunctionParameter {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.type_argument.resolve_symbols(handler, ctx.by_ref());
}
}
impl ResolveSymbols for ImplSelfOrTrait {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.impl_type_parameters
.iter_mut()
.for_each(|f| f.resolve_symbols(handler, ctx.by_ref()));
self.trait_name.resolve_symbols(handler, ctx.by_ref());
self.trait_type_arguments
.iter_mut()
.for_each(|tp| tp.resolve_symbols(handler, ctx.by_ref()));
self.implementing_for.resolve_symbols(handler, ctx.by_ref());
self.items
.iter_mut()
.for_each(|tp| tp.resolve_symbols(handler, ctx.by_ref()));
}
}
impl ResolveSymbols for ImplItem {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
match self {
ImplItem::Fn(decl_id) => decl_id.resolve_symbols(handler, ctx),
ImplItem::Constant(decl_id) => decl_id.resolve_symbols(handler, ctx),
ImplItem::Type(decl_id) => decl_id.resolve_symbols(handler, ctx),
}
}
}
impl ResolveSymbols for TraitTypeDeclaration {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
if let Some(ty) = self.ty_opt.as_mut() {
ty.resolve_symbols(handler, ctx)
}
}
}
impl ResolveSymbols for StorageDeclaration {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.entries
.iter_mut()
.for_each(|e| e.resolve_symbols(handler, ctx.by_ref()));
}
}
impl ResolveSymbols for StorageEntry {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
match self {
StorageEntry::Namespace(ref mut ns) => {
ns.entries
.iter_mut()
.for_each(|e| e.resolve_symbols(handler, ctx.by_ref()));
}
StorageEntry::Field(ref mut f) => {
f.type_argument.resolve_symbols(handler, ctx.by_ref());
f.initializer.resolve_symbols(handler, ctx.by_ref());
}
}
}
}
impl ResolveSymbols for TypeAliasDeclaration {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
self.ty.resolve_symbols(handler, ctx)
}
}
impl ResolveSymbols for GenericArgument {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
match self {
GenericArgument::Type(arg) => {
arg.resolve_symbols(handler, ctx);
}
GenericArgument::Const(_) => {}
}
}
}
impl ResolveSymbols for GenericTypeArgument {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
if let Some(call_path_tree) = self.call_path_tree.as_mut() {
call_path_tree.resolve_symbols(handler, ctx);
}
}
}
impl ResolveSymbols for TypeParameter {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
match self {
TypeParameter::Type(p) => p
.trait_constraints
.iter_mut()
.for_each(|tc| tc.resolve_symbols(handler, ctx.by_ref())),
TypeParameter::Const(_) => todo!(),
}
}
}
impl ResolveSymbols for TraitConstraint {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
self.trait_name.resolve_symbols(handler, ctx.by_ref());
self.type_arguments
.iter_mut()
.for_each(|tc| tc.resolve_symbols(handler, ctx.by_ref()));
}
}
impl ResolveSymbols for CallPath {
fn resolve_symbols(&mut self, _handler: &Handler, _ctx: SymbolResolveContext) {}
}
impl ResolveSymbols for CallPathTree {
fn resolve_symbols(&mut self, _handler: &Handler, _ctx: SymbolResolveContext) {}
}
impl ResolveSymbols for CodeBlock {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
for expr in self.contents.iter_mut() {
expr.resolve_symbols(handler, ctx.by_ref())
}
}
}
impl ResolveSymbols for StructExpressionField {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
self.value.resolve_symbols(handler, ctx);
}
}
impl ResolveSymbols for Scrutinee {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
match self {
Scrutinee::Or {
ref mut elems,
span: _,
} => elems
.iter_mut()
.for_each(|e| e.resolve_symbols(handler, ctx.by_ref())),
Scrutinee::CatchAll { .. } => {}
Scrutinee::Literal { .. } => {}
Scrutinee::Variable { .. } => {}
Scrutinee::AmbiguousSingleIdent(_) => {}
Scrutinee::StructScrutinee {
struct_name,
fields,
span: _,
} => {
struct_name.resolve_symbols(handler, ctx.by_ref());
fields
.iter_mut()
.for_each(|f| f.resolve_symbols(handler, ctx.by_ref()))
}
Scrutinee::EnumScrutinee {
call_path,
value,
span: _,
} => {
call_path.resolve_symbols(handler, ctx.by_ref());
value.resolve_symbols(handler, ctx.by_ref());
}
Scrutinee::Tuple { elems, span: _ } => {
elems
.iter_mut()
.for_each(|s| s.resolve_symbols(handler, ctx.by_ref()));
}
Scrutinee::Error { .. } => {}
}
}
}
impl ResolveSymbols for StructScrutineeField {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
match self {
StructScrutineeField::Rest { .. } => {}
StructScrutineeField::Field {
field: _,
scrutinee,
span: _,
} => {
if let Some(scrutinee) = scrutinee.as_mut() {
scrutinee.resolve_symbols(handler, ctx.by_ref());
}
}
}
}
}
impl ResolveSymbols for Expression {
fn resolve_symbols(&mut self, handler: &Handler, ctx: SymbolResolveContext) {
self.kind.resolve_symbols(handler, ctx);
}
}
impl ResolveSymbols for ExpressionKind {
fn resolve_symbols(&mut self, handler: &Handler, mut ctx: SymbolResolveContext) {
match self {
ExpressionKind::Error(_, _) => {}
ExpressionKind::Literal(_) => {}
ExpressionKind::AmbiguousPathExpression(_) => {}
ExpressionKind::FunctionApplication(expr) => {
let result = SymbolResolveTypeBinding::resolve_symbol(
&mut expr.call_path_binding,
&Handler::default(),
ctx.by_ref(),
);
if let Ok(result) = result {
expr.resolved_call_path_binding = Some(TypeBinding::<
ResolvedCallPath<ParsedDeclId<FunctionDeclaration>>,
> {
inner: ResolvedCallPath {
decl: result,
unresolved_call_path: expr.call_path_binding.inner.clone(),
},
span: expr.call_path_binding.span.clone(),
type_arguments: expr.call_path_binding.type_arguments.clone(),
});
}
expr.arguments
.iter_mut()
.for_each(|a| a.resolve_symbols(handler, ctx.by_ref()))
}
ExpressionKind::LazyOperator(expr) => {
expr.lhs.resolve_symbols(handler, ctx.by_ref());
expr.rhs.resolve_symbols(handler, ctx.by_ref());
}
ExpressionKind::AmbiguousVariableExpression(_) => {}
ExpressionKind::Variable(_) => {}
ExpressionKind::Tuple(exprs) => {
exprs
.iter_mut()
.for_each(|expr| expr.resolve_symbols(handler, ctx.by_ref()));
}
ExpressionKind::TupleIndex(expr) => {
expr.prefix.resolve_symbols(handler, ctx.by_ref());
}
ExpressionKind::Array(ArrayExpression::Explicit { contents, .. }) => contents
.iter_mut()
.for_each(|e| e.resolve_symbols(handler, ctx.by_ref())),
ExpressionKind::Array(ArrayExpression::Repeat { value, length }) => {
value.resolve_symbols(handler, ctx.by_ref());
length.resolve_symbols(handler, ctx.by_ref());
}
ExpressionKind::Struct(expr) => {
expr.call_path_binding
.resolve_symbols(handler, ctx.by_ref());
let result = SymbolResolveTypeBinding::resolve_symbol(
&mut expr.call_path_binding,
&Handler::default(),
ctx.by_ref(),
);
if let Ok(result) = result {
expr.resolved_call_path_binding = Some(TypeBinding::<
ResolvedCallPath<ParsedDeclId<StructDeclaration>>,
> {
inner: ResolvedCallPath {
decl: result,
unresolved_call_path: expr.call_path_binding.inner.clone(),
},
span: expr.call_path_binding.span.clone(),
type_arguments: expr.call_path_binding.type_arguments.clone(),
});
}
}
ExpressionKind::CodeBlock(block) => {
block
.contents
.iter_mut()
.for_each(|node| node.resolve_symbols(handler, ctx.by_ref()));
}
ExpressionKind::If(expr) => {
expr.condition.resolve_symbols(handler, ctx.by_ref());
expr.then.resolve_symbols(handler, ctx.by_ref());
if let Some(r#else) = expr.r#else.as_mut() {
r#else.resolve_symbols(handler, ctx.by_ref());
}
}
ExpressionKind::Match(expr) => {
expr.value.resolve_symbols(handler, ctx.by_ref());
expr.branches.iter_mut().for_each(|branch| {
branch.scrutinee.resolve_symbols(handler, ctx.by_ref());
branch.result.resolve_symbols(handler, ctx.by_ref());
});
}
ExpressionKind::Asm(asm_expr) => asm_expr.registers.iter_mut().for_each(|reg| {
if let Some(initializer) = reg.initializer.as_mut() {
initializer.resolve_symbols(handler, ctx.by_ref());
}
}),
ExpressionKind::MethodApplication(expr) => {
expr.method_name_binding
.resolve_symbols(handler, ctx.by_ref());
expr.contract_call_params
.iter_mut()
.for_each(|field| field.resolve_symbols(handler, ctx.by_ref()));
expr.arguments
.iter_mut()
.for_each(|arg| arg.resolve_symbols(handler, ctx.by_ref()));
}
ExpressionKind::Subfield(expr) => expr.prefix.resolve_symbols(handler, ctx),
ExpressionKind::DelineatedPath(expr) => {
expr.call_path_binding.resolve_symbols(handler, ctx)
}
ExpressionKind::AbiCast(expr) => {
expr.abi_name.resolve_symbols(handler, ctx.by_ref());
expr.address.resolve_symbols(handler, ctx.by_ref());
}
ExpressionKind::ArrayIndex(expr) => {
expr.index.resolve_symbols(handler, ctx.by_ref());
expr.prefix.resolve_symbols(handler, ctx.by_ref());
}
ExpressionKind::StorageAccess(_expr) => {}
ExpressionKind::IntrinsicFunction(expr) => {
expr.arguments
.iter_mut()
.for_each(|arg| arg.resolve_symbols(handler, ctx.by_ref()));
expr.kind_binding.resolve_symbols(handler, ctx);
}
ExpressionKind::WhileLoop(expr) => {
expr.condition.resolve_symbols(handler, ctx.by_ref());
expr.body.resolve_symbols(handler, ctx.by_ref());
}
ExpressionKind::ForLoop(expr) => expr.desugared.resolve_symbols(handler, ctx.by_ref()),
ExpressionKind::Break => {}
ExpressionKind::Continue => {}
ExpressionKind::Reassignment(expr) => {
match &mut expr.lhs {
ReassignmentTarget::ElementAccess(expr) => {
expr.resolve_symbols(handler, ctx.by_ref())
}
ReassignmentTarget::Deref(expr) => expr.resolve_symbols(handler, ctx.by_ref()),
};
expr.rhs.resolve_symbols(handler, ctx.by_ref());
}
ExpressionKind::ImplicitReturn(expr) => expr.resolve_symbols(handler, ctx),
ExpressionKind::Return(expr) => expr.resolve_symbols(handler, ctx.by_ref()),
ExpressionKind::Panic(expr) => expr.resolve_symbols(handler, ctx.by_ref()),
ExpressionKind::Ref(expr) => expr.value.resolve_symbols(handler, ctx.by_ref()),
ExpressionKind::Deref(expr) => expr.resolve_symbols(handler, ctx.by_ref()),
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/cei_pattern_analysis.rs | sway-core/src/semantic_analysis/cei_pattern_analysis.rs | // CEI stands for "Checks, Effects, Interactions". We check that no storage writes
// (effects) occur after calling external contracts (interaction) and issue warnings
// if it's the case.
// See this [blog post](https://fravoll.github.io/solidity-patterns/checks_effects_interactions.html)
// for more detail on vulnerabilities in case of storage modification after interaction
// and this [blog post](https://chainsecurity.com/curve-lp-oracle-manipulation-post-mortem)
// for more information on storage reads after interaction.
// We also treat the balance tree reads and writes separately,
// as well as modifying output messages.
use crate::{
decl_engine::*,
language::{
ty::{self, TyFunctionDecl, TyImplSelfOrTrait},
AsmOp,
},
Engines,
};
use std::fmt;
use std::{collections::HashSet, sync::Arc};
use sway_error::warning::{CompileWarning, Warning};
use sway_types::{Ident, Span, Spanned};
#[derive(PartialEq, Eq, Hash, Clone)]
enum Effect {
Interaction, // interaction with external contracts
StorageWrite, // storage modification
StorageRead, // storage read
// Note: there are no operations that only write to the balance tree
BalanceTreeRead, // balance tree read operation
BalanceTreeReadWrite, // balance tree read and write operation
OutputMessage, // operation creates a new `Output::Message`
MintAsset, // mint operation
BurnAsset, // burn operation
}
impl fmt::Display for Effect {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use Effect::*;
match self {
Interaction => write!(f, "Interaction"),
StorageWrite => write!(f, "Storage write"),
StorageRead => write!(f, "Storage read"),
BalanceTreeRead => write!(f, "Balance tree read"),
BalanceTreeReadWrite => write!(f, "Balance tree update"),
OutputMessage => write!(f, "Output message sent"),
MintAsset => write!(f, "Asset minted"),
BurnAsset => write!(f, "Asset burned"),
}
}
}
impl Effect {
fn to_suggestion(&self) -> String {
use Effect::*;
String::from(match self {
Interaction => "making all interactions",
StorageWrite => "making all storage writes",
StorageRead => "making all storage reads",
BalanceTreeRead => "making all balance tree reads",
BalanceTreeReadWrite => "making all balance tree updates",
OutputMessage => "sending all output messages",
MintAsset => "minting assets",
BurnAsset => "burning assets",
})
}
}
// The algorithm that searches for storage operations after interaction
// is organized as an automaton.
// After an interaction is found in a code block, we keep looking either for
// storage reads or writes.
enum CEIAnalysisState {
LookingForInteraction, // initial state of the automaton
LookingForEffect,
}
pub(crate) fn analyze_program(engines: &Engines, prog: &ty::TyProgram) -> Vec<CompileWarning> {
match &prog.kind {
// Libraries, scripts, or predicates can't access storage
// so we don't analyze these
ty::TyProgramKind::Library { .. }
| ty::TyProgramKind::Script { .. }
| ty::TyProgramKind::Predicate { .. } => vec![],
ty::TyProgramKind::Contract { .. } => {
analyze_contract(engines, &prog.root_module.all_nodes)
}
}
}
fn analyze_contract(engines: &Engines, ast_nodes: &[ty::TyAstNode]) -> Vec<CompileWarning> {
let decl_engine = engines.de();
let mut warnings: Vec<CompileWarning> = vec![];
for fn_decl in contract_entry_points(decl_engine, ast_nodes) {
// no need to analyze the entry fn
if fn_decl.name.as_str() == "__entry" {
continue;
}
analyze_code_block(engines, &fn_decl.body, &fn_decl.name, &mut warnings);
}
warnings
}
// standalone functions and methods
fn contract_entry_points(
decl_engine: &DeclEngine,
ast_nodes: &[ty::TyAstNode],
) -> Vec<Arc<ty::TyFunctionDecl>> {
use crate::ty::TyAstNodeContent::Declaration;
ast_nodes
.iter()
.flat_map(|ast_node| match &ast_node.content {
Declaration(ty::TyDecl::FunctionDecl(ty::FunctionDecl { decl_id, .. })) => {
decl_id_to_fn_decls(decl_engine, decl_id)
}
Declaration(ty::TyDecl::ImplSelfOrTrait(ty::ImplSelfOrTrait { decl_id, .. })) => {
impl_trait_methods(decl_engine, decl_id)
}
_ => vec![],
})
.collect()
}
fn decl_id_to_fn_decls(
decl_engine: &DeclEngine,
decl_id: &DeclId<TyFunctionDecl>,
) -> Vec<Arc<TyFunctionDecl>> {
vec![decl_engine.get_function(decl_id)]
}
fn impl_trait_methods(
decl_engine: &DeclEngine,
impl_trait_decl_id: &DeclId<TyImplSelfOrTrait>,
) -> Vec<Arc<ty::TyFunctionDecl>> {
let impl_trait = decl_engine.get_impl_self_or_trait(impl_trait_decl_id);
impl_trait
.items
.iter()
.flat_map(|item| match item {
ty::TyImplItem::Fn(fn_decl) => Some(fn_decl),
ty::TyImplItem::Constant(_) => None,
ty::TyImplItem::Type(_) => None,
})
.flat_map(|fn_decl| decl_id_to_fn_decls(decl_engine, &fn_decl.id().clone()))
.collect()
}
// This is the main part of the analysis algorithm:
// we are looking for various effects after contract interaction
fn analyze_code_block(
engines: &Engines,
codeblock: &ty::TyCodeBlock,
block_name: &Ident,
warnings: &mut Vec<CompileWarning>,
) -> HashSet<Effect> {
let mut interaction_span: Span = Span::dummy();
let mut codeblock_effects = HashSet::new();
let mut analysis_state: CEIAnalysisState = CEIAnalysisState::LookingForInteraction;
for ast_node in &codeblock.contents {
let codeblock_entry_effects =
analyze_code_block_entry(engines, ast_node, block_name, warnings);
match analysis_state {
CEIAnalysisState::LookingForInteraction => {
if codeblock_entry_effects.contains(&Effect::Interaction) {
analysis_state = CEIAnalysisState::LookingForEffect;
interaction_span = ast_node.span.clone();
}
}
CEIAnalysisState::LookingForEffect => warn_after_interaction(
&codeblock_entry_effects,
&interaction_span,
&ast_node.span,
block_name,
warnings,
),
};
codeblock_effects.extend(codeblock_entry_effects)
}
codeblock_effects
}
fn analyze_code_block_entry(
engines: &Engines,
entry: &ty::TyAstNode,
block_name: &Ident,
warnings: &mut Vec<CompileWarning>,
) -> HashSet<Effect> {
match &entry.content {
ty::TyAstNodeContent::Declaration(decl) => {
analyze_codeblock_decl(engines, decl, block_name, warnings)
}
ty::TyAstNodeContent::Expression(expr) => {
analyze_expression(engines, expr, block_name, warnings)
}
ty::TyAstNodeContent::SideEffect(_) | ty::TyAstNodeContent::Error(_, _) => HashSet::new(),
}
}
fn analyze_codeblock_decl(
engines: &Engines,
decl: &ty::TyDecl,
block_name: &Ident,
warnings: &mut Vec<CompileWarning>,
) -> HashSet<Effect> {
// Declarations (except variable declarations) are not allowed in a codeblock
use crate::ty::TyDecl::*;
match decl {
VariableDecl(var_decl) => analyze_expression(engines, &var_decl.body, block_name, warnings),
_ => HashSet::new(),
}
}
fn analyze_expression(
engines: &Engines,
expr: &ty::TyExpression,
block_name: &Ident,
warnings: &mut Vec<CompileWarning>,
) -> HashSet<Effect> {
use crate::ty::TyExpressionVariant::*;
let decl_engine = engines.de();
match &expr.expression {
// base cases: no warnings can be emitted
Literal(_)
| ConstantExpression { .. }
| ConfigurableExpression { .. }
| ConstGenericExpression { .. }
| VariableExpression { .. }
| FunctionParameter
| StorageAccess(_)
| Break
| Continue
| AbiName(_) => effects_of_expression(engines, expr),
Reassignment(reassgn) => analyze_expression(engines, &reassgn.rhs, block_name, warnings),
CodeBlock(codeblock) => analyze_code_block(engines, codeblock, block_name, warnings),
LazyOperator {
lhs: left,
rhs: right,
..
}
| ArrayIndex {
prefix: left,
index: right,
} => analyze_two_expressions(engines, left, right, block_name, warnings),
FunctionApplication {
arguments,
fn_ref,
selector,
call_path,
..
} => {
let func = decl_engine.get_function(fn_ref);
// we don't need to run full analysis on the function body as it will be covered
// as a separate step of the whole contract analysis
// we just need function's effects at this point
let fn_effs = effects_of_codeblock(engines, &func.body);
// assuming left-to-right arguments evaluation
// we run CEI violation analysis as if the arguments form a code block
let args_effs = analyze_expressions(
engines,
arguments.iter().map(|(_, e)| e),
block_name,
warnings,
);
if args_effs.contains(&Effect::Interaction) {
// TODO: interaction span has to be more precise and point to an argument which performs interaction
let last_arg_span = &arguments.last().unwrap().1.span;
warn_after_interaction(
&fn_effs,
&call_path.span(),
last_arg_span,
block_name,
warnings,
)
}
let mut result_effs = set_union(fn_effs, args_effs);
if selector.is_some() {
// external contract call (a.k.a. interaction)
result_effs.extend(HashSet::from([Effect::Interaction]))
};
result_effs
}
IntrinsicFunction(intrinsic) => {
let intr_effs = effects_of_intrinsic(&intrinsic.kind);
// assuming left-to-right arguments evaluation
let args_effs =
analyze_expressions(engines, intrinsic.arguments.iter(), block_name, warnings);
if args_effs.contains(&Effect::Interaction) {
// TODO: interaction span has to be more precise and point to an argument which performs interaction
warn_after_interaction(&intr_effs, &expr.span, &expr.span, block_name, warnings)
}
set_union(intr_effs, args_effs)
}
Tuple { fields: exprs }
| ArrayExplicit {
elem_type: _,
contents: exprs,
} => {
// assuming left-to-right fields/elements evaluation
analyze_expressions(engines, exprs.iter(), block_name, warnings)
}
ArrayRepeat {
elem_type: _,
value,
length,
} => {
// assuming left-to-right fields/elements evaluation
let mut cond_then_effs = analyze_expression(engines, value, block_name, warnings);
cond_then_effs.extend(analyze_expression(engines, length, block_name, warnings));
cond_then_effs
}
StructExpression { fields, .. } => {
// assuming left-to-right fields evaluation
analyze_expressions(
engines,
fields.iter().map(|e| &e.value),
block_name,
warnings,
)
}
StructFieldAccess { prefix: expr, .. }
| TupleElemAccess { prefix: expr, .. }
| ImplicitReturn(expr)
| Return(expr)
| Panic(expr)
| EnumTag { exp: expr }
| UnsafeDowncast { exp: expr, .. }
| AbiCast { address: expr, .. }
| Ref(expr)
| Deref(expr) => analyze_expression(engines, expr, block_name, warnings),
EnumInstantiation { contents, .. } => match contents {
Some(expr) => analyze_expression(engines, expr, block_name, warnings),
None => HashSet::new(),
},
MatchExp { desugared, .. } => analyze_expression(engines, desugared, block_name, warnings),
IfExp {
condition,
then,
r#else,
} => {
let cond_then_effs =
analyze_two_expressions(engines, condition, then, block_name, warnings);
let cond_else_effs = match r#else {
Some(else_exp) => {
analyze_two_expressions(engines, condition, else_exp, block_name, warnings)
}
None => HashSet::new(),
};
set_union(cond_then_effs, cond_else_effs)
}
WhileLoop { condition, body } => {
// if the loop (condition + body) contains both interaction and state effects
// in _any_ order, we report CEI pattern violation
let cond_effs = analyze_expression(engines, condition, block_name, warnings);
let body_effs = analyze_code_block(engines, body, block_name, warnings);
let res_effs = set_union(cond_effs, body_effs);
if res_effs.contains(&Effect::Interaction) {
// TODO: the span is not very precise, we can do better here, but this
// will need a bit of refactoring of the CEI analysis
let span = expr.span.clone();
warn_after_interaction(&res_effs, &span, &span, &block_name.clone(), warnings)
}
res_effs
}
ForLoop { desugared } => analyze_expression(engines, desugared, block_name, warnings),
AsmExpression {
registers, body, ..
} => {
let init_exprs = registers
.iter()
.filter_map(|rdecl| rdecl.initializer.as_ref());
let init_effs = analyze_expressions(engines, init_exprs, block_name, warnings);
let asmblock_effs = analyze_asm_block(body, block_name, warnings);
if init_effs.contains(&Effect::Interaction) {
// TODO: improve locations accuracy
warn_after_interaction(&asmblock_effs, &expr.span, &expr.span, block_name, warnings)
}
set_union(init_effs, asmblock_effs)
}
}
}
fn analyze_two_expressions(
engines: &Engines,
first: &ty::TyExpression,
second: &ty::TyExpression,
block_name: &Ident,
warnings: &mut Vec<CompileWarning>,
) -> HashSet<Effect> {
let first_effs = analyze_expression(engines, first, block_name, warnings);
let second_effs = analyze_expression(engines, second, block_name, warnings);
if first_effs.contains(&Effect::Interaction) {
warn_after_interaction(
&second_effs,
&first.span,
&second.span,
block_name,
warnings,
)
}
set_union(first_effs, second_effs)
}
// Analyze a sequence of expressions
// TODO: analyze_expressions, analyze_codeblock and analyze_asm_block (see below) are very similar in structure
// looks like the algorithm implementation should be generalized
fn analyze_expressions<'a>(
engines: &Engines,
expressions: impl Iterator<Item = &'a ty::TyExpression>,
block_name: &Ident,
warnings: &mut Vec<CompileWarning>,
) -> HashSet<Effect> {
let mut interaction_span: Span = Span::dummy();
let mut accumulated_effects = HashSet::new();
let mut analysis_state: CEIAnalysisState = CEIAnalysisState::LookingForInteraction;
for expr in expressions {
let expr_effs = analyze_expression(engines, expr, block_name, warnings);
match analysis_state {
CEIAnalysisState::LookingForInteraction => {
if expr_effs.contains(&Effect::Interaction) {
analysis_state = CEIAnalysisState::LookingForEffect;
interaction_span = expr.span.clone();
}
}
CEIAnalysisState::LookingForEffect => warn_after_interaction(
&expr_effs,
&interaction_span,
&expr.span,
block_name,
warnings,
),
};
accumulated_effects.extend(expr_effs)
}
accumulated_effects
}
// No need to worry about jumps because they are not allowed in `asm` blocks.
fn analyze_asm_block(
asm_block: &Vec<AsmOp>,
block_name: &Ident,
warnings: &mut Vec<CompileWarning>,
) -> HashSet<Effect> {
let mut interaction_span: Span = Span::dummy();
let mut accumulated_effects = HashSet::new();
let mut analysis_state: CEIAnalysisState = CEIAnalysisState::LookingForInteraction;
for asm_op in asm_block {
let asm_op_effs = effects_of_asm_op(asm_op);
match analysis_state {
CEIAnalysisState::LookingForInteraction => {
if asm_op_effs.contains(&Effect::Interaction) {
analysis_state = CEIAnalysisState::LookingForEffect;
interaction_span = asm_op.span.clone();
}
}
CEIAnalysisState::LookingForEffect => warn_after_interaction(
&asm_op_effs,
&interaction_span,
&asm_op.span,
block_name,
warnings,
),
};
accumulated_effects.extend(asm_op_effs)
}
accumulated_effects
}
fn warn_after_interaction(
ast_node_effects: &HashSet<Effect>,
interaction_span: &Span,
effect_span: &Span,
block_name: &Ident,
warnings: &mut Vec<CompileWarning>,
) {
let interaction_singleton = HashSet::from([Effect::Interaction]);
let state_effects = ast_node_effects.difference(&interaction_singleton);
for eff in state_effects {
warnings.push(CompileWarning {
span: Span::join(interaction_span.clone(), effect_span),
warning_content: Warning::EffectAfterInteraction {
effect: eff.to_string(),
effect_in_suggestion: Effect::to_suggestion(eff),
block_name: block_name.clone(),
},
});
}
}
fn effects_of_codeblock_entry(engines: &Engines, ast_node: &ty::TyAstNode) -> HashSet<Effect> {
match &ast_node.content {
ty::TyAstNodeContent::Declaration(decl) => effects_of_codeblock_decl(engines, decl),
ty::TyAstNodeContent::Expression(expr) => effects_of_expression(engines, expr),
ty::TyAstNodeContent::SideEffect(_) | ty::TyAstNodeContent::Error(_, _) => HashSet::new(),
}
}
fn effects_of_codeblock_decl(engines: &Engines, decl: &ty::TyDecl) -> HashSet<Effect> {
use crate::ty::TyDecl::*;
match decl {
VariableDecl(var_decl) => effects_of_expression(engines, &var_decl.body),
// Declarations (except variable declarations) are not allowed in the body of a function
_ => HashSet::new(),
}
}
fn effects_of_expression(engines: &Engines, expr: &ty::TyExpression) -> HashSet<Effect> {
use crate::ty::TyExpressionVariant::*;
let type_engine = engines.te();
let decl_engine = engines.de();
match &expr.expression {
Literal(_)
| ConstantExpression { .. }
| ConfigurableExpression { .. }
| VariableExpression { .. }
| FunctionParameter
| Break
| Continue
| ConstGenericExpression { .. }
| AbiName(_) => HashSet::new(),
// this type of assignment only mutates local variables and not storage
Reassignment(reassgn) => effects_of_expression(engines, &reassgn.rhs),
StorageAccess(_) => match &*type_engine.get(expr.return_type) {
// accessing a storage map's method (or a storage vector's method),
// which is represented using a struct with empty fields
// does not result in a storage read
crate::TypeInfo::Struct(decl_ref)
if decl_engine.get_struct(decl_ref).fields.is_empty() =>
{
HashSet::new()
}
// if it's an empty enum then it cannot be constructed and hence cannot be read
// adding this check here just to be on the safe side
crate::TypeInfo::Enum(decl_ref)
if decl_engine.get_enum(decl_ref).variants.is_empty() =>
{
HashSet::new()
}
_ => HashSet::from([Effect::StorageRead]),
},
LazyOperator { lhs, rhs, .. }
| ArrayIndex {
prefix: lhs,
index: rhs,
} => {
let mut effs = effects_of_expression(engines, lhs);
let rhs_effs = effects_of_expression(engines, rhs);
effs.extend(rhs_effs);
effs
}
Tuple { fields: exprs }
| ArrayExplicit {
elem_type: _,
contents: exprs,
} => effects_of_expressions(engines, exprs),
ArrayRepeat {
elem_type: _,
value,
length,
} => {
let mut effs = effects_of_expression(engines, value);
effs.extend(effects_of_expression(engines, length));
effs
}
StructExpression { fields, .. } => effects_of_struct_expressions(engines, fields),
CodeBlock(codeblock) => effects_of_codeblock(engines, codeblock),
MatchExp { desugared, .. } => effects_of_expression(engines, desugared),
IfExp {
condition,
then,
r#else,
} => {
let mut effs = effects_of_expression(engines, condition);
effs.extend(effects_of_expression(engines, then));
let else_effs = match r#else {
Some(expr) => effects_of_expression(engines, expr),
None => HashSet::new(),
};
effs.extend(else_effs);
effs
}
StructFieldAccess { prefix: expr, .. }
| TupleElemAccess { prefix: expr, .. }
| EnumTag { exp: expr }
| UnsafeDowncast { exp: expr, .. }
| ImplicitReturn(expr)
| Return(expr)
| Panic(expr)
| Ref(expr)
| Deref(expr) => effects_of_expression(engines, expr),
EnumInstantiation { contents, .. } => match contents {
Some(expr) => effects_of_expression(engines, expr),
None => HashSet::new(),
},
AbiCast { address, .. } => effects_of_expression(engines, address),
IntrinsicFunction(intr_fn) => effects_of_expressions(engines, &intr_fn.arguments)
.union(&effects_of_intrinsic(&intr_fn.kind))
.cloned()
.collect(),
WhileLoop { condition, body } => effects_of_expression(engines, condition)
.union(&effects_of_codeblock(engines, body))
.cloned()
.collect(),
ForLoop { desugared } => effects_of_expression(engines, desugared),
FunctionApplication {
fn_ref,
arguments,
selector,
..
} => {
let fn_body = &decl_engine.get_function(fn_ref).body;
let mut effs = effects_of_codeblock(engines, fn_body);
let args_effs = map_hashsets_union(arguments, |e| effects_of_expression(engines, &e.1));
effs.extend(args_effs);
if selector.is_some() {
// external contract call (a.k.a. interaction)
effs.extend(HashSet::from([Effect::Interaction]))
};
effs
}
AsmExpression {
registers,
body,
whole_block_span: _,
..
} => effects_of_register_initializers(engines, registers)
.union(&effects_of_asm_ops(body))
.cloned()
.collect(),
}
}
fn effects_of_intrinsic(intr: &sway_ast::Intrinsic) -> HashSet<Effect> {
use sway_ast::Intrinsic::*;
match intr {
StateClear | StateStoreWord | StateStoreQuad => HashSet::from([Effect::StorageWrite]),
StateLoadWord | StateLoadQuad => HashSet::from([Effect::StorageRead]),
Smo => HashSet::from([Effect::OutputMessage]),
ContractCall => HashSet::from([Effect::Interaction]),
Revert
| JmpMem
| IsReferenceType
| IsStrArray
| SizeOfType
| SizeOfVal
| SizeOfStr
| ContractRet
| AssertIsStrArray
| ToStrArray
| Eq
| Gt
| Lt
| Gtf
| AddrOf
| Log
| Add
| Sub
| Mul
| Div
| And
| Or
| Xor
| Mod
| Rsh
| Lsh
| PtrAdd
| PtrSub
| Not
| EncodeBufferEmpty
| EncodeBufferAppend
| EncodeBufferAsRawSlice
| Slice
| ElemAt
| Transmute
| Dbg
| Alloc
| RuntimeMemoryId
| EncodingMemoryId => HashSet::new(),
}
}
fn effects_of_asm_op(op: &AsmOp) -> HashSet<Effect> {
match op.op_name.as_str().to_lowercase().as_str() {
"scwq" | "sww" | "swwq" => HashSet::from([Effect::StorageWrite]),
"srw" | "srwq" => HashSet::from([Effect::StorageRead]),
"tr" | "tro" => HashSet::from([Effect::BalanceTreeReadWrite]),
"bal" => HashSet::from([Effect::BalanceTreeRead]),
"smo" => HashSet::from([Effect::OutputMessage]),
"call" => HashSet::from([Effect::Interaction]),
"mint" => HashSet::from([Effect::MintAsset]),
"burn" => HashSet::from([Effect::BurnAsset]),
// the rest of the assembly instructions are considered to not have effects
_ => HashSet::new(),
}
}
fn set_union<E>(set1: HashSet<E>, set2: HashSet<E>) -> HashSet<E>
where
E: std::hash::Hash + Eq + Clone,
{
set1.union(&set2).cloned().collect()
}
fn map_hashsets_union<T, F, E>(elems: &[T], to_set: F) -> HashSet<E>
where
F: Fn(&T) -> HashSet<E>,
E: std::hash::Hash + Eq + Clone,
{
elems
.iter()
.fold(HashSet::new(), |set, e| set_union(to_set(e), set))
}
fn effects_of_codeblock(engines: &Engines, codeblock: &ty::TyCodeBlock) -> HashSet<Effect> {
map_hashsets_union(&codeblock.contents, |entry| {
effects_of_codeblock_entry(engines, entry)
})
}
fn effects_of_expressions(engines: &Engines, exprs: &[ty::TyExpression]) -> HashSet<Effect> {
map_hashsets_union(exprs, |e| effects_of_expression(engines, e))
}
fn effects_of_struct_expressions(
engines: &Engines,
struct_exprs: &[ty::TyStructExpressionField],
) -> HashSet<Effect> {
map_hashsets_union(struct_exprs, |se| effects_of_expression(engines, &se.value))
}
fn effects_of_asm_ops(asm_ops: &[AsmOp]) -> HashSet<Effect> {
map_hashsets_union(asm_ops, effects_of_asm_op)
}
fn effects_of_register_initializers(
engines: &Engines,
initializers: &[ty::TyAsmRegisterDeclaration],
) -> HashSet<Effect> {
map_hashsets_union(initializers, |asm_reg_decl| {
asm_reg_decl
.initializer
.as_ref()
.map_or(HashSet::new(), |e| effects_of_expression(engines, e))
})
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/method_lookup.rs | sway-core/src/semantic_analysis/method_lookup.rs | use std::collections::{BTreeMap, HashSet};
use itertools::Itertools;
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::{span::Span, Ident, Spanned};
use crate::{
decl_engine::DeclRefFunction,
language::{
parsed::MethodName,
ty::{self, TyFunctionDisplay},
CallPath, QualifiedCallPath,
},
namespace::{
IsImplInterfaceSurface, Module, ModulePath, ResolvedTraitImplItem, TraitKey, TraitMap,
TraitSuffix,
},
type_system::{GenericArgument, TypeId, TypeInfo, TypeParameter},
EnforceTypeArguments, Engines, TraitConstraint, UnifyCheck,
};
use super::{
type_check_context::TypeCheckContext,
type_resolve::{resolve_type, VisibilityCheck},
};
struct MethodCandidate {
decl_ref: DeclRefFunction,
params: Vec<TypeId>,
ret: TypeId,
is_contract_call: bool,
}
enum MatchScore {
Exact,
Coercible,
Incompatible,
}
#[derive(Clone)]
pub(crate) struct CandidateTraitItem {
item: ty::TyTraitItem,
trait_key: TraitKey,
original_type_id: TypeId,
resolved_type_id: TypeId,
}
fn trait_paths_equivalent(
allowed: &CallPath<TraitSuffix>,
other: &CallPath<TraitSuffix>,
unify_check: &UnifyCheck,
) -> bool {
if allowed
.prefixes
.iter()
.zip(other.prefixes.iter())
.any(|(a, b)| a != b)
{
return false;
}
if allowed.suffix.name != other.suffix.name {
return false;
}
if allowed.suffix.args.len() != other.suffix.args.len() {
return false;
}
allowed
.suffix
.args
.iter()
.zip(other.suffix.args.iter())
.all(|(a, b)| unify_check.check(a.type_id(), b.type_id()))
}
type TraitImplId = crate::decl_engine::DeclId<ty::TyImplSelfOrTrait>;
type GroupingKey = (TraitImplId, Option<TypeId>);
struct GroupingResult {
trait_methods: BTreeMap<GroupingKey, DeclRefFunction>,
impl_self_method: Option<DeclRefFunction>,
qualified_call_path: Option<QualifiedCallPath>,
}
impl TypeCheckContext<'_> {
/// Given a name and a type (plus a `self_type` to potentially
/// resolve it), find items matching in the namespace.
pub(crate) fn find_items_for_type(
&self,
handler: &Handler,
type_id: TypeId,
item_prefix: &ModulePath,
item_name: &Ident,
method_name: &Option<&MethodName>,
) -> Result<Vec<CandidateTraitItem>, ErrorEmitted> {
let type_engine = self.engines.te();
let original_type_id = type_id;
// If the type that we are looking for is the error recovery type, then
// we want to return the error case without creating a new error
// message.
if let TypeInfo::ErrorRecovery(err) = &*type_engine.get(type_id) {
return Err(*err);
}
// resolve the type
let resolved_type_id = resolve_type(
handler,
self.engines(),
self.namespace(),
item_prefix,
type_id,
&item_name.span(),
EnforceTypeArguments::No,
None,
self.self_type(),
&self.subst_ctx(handler),
VisibilityCheck::Yes,
)
.unwrap_or_else(|err| type_engine.id_of_error_recovery(err));
// grab the local module
let local_module = self
.namespace()
.require_module_from_absolute_path(handler, &self.namespace().current_mod_path)?;
// grab the local items from the local module
let mut matching_items = vec![];
let mut filter_item = |item: ResolvedTraitImplItem, trait_key: TraitKey| match &item {
ResolvedTraitImplItem::Parsed(_) => todo!(),
ResolvedTraitImplItem::Typed(ty_item) => match ty_item {
ty::TyTraitItem::Fn(decl_ref) if decl_ref.name() == item_name => {
matching_items.push(CandidateTraitItem {
item: ty_item.clone(),
trait_key: trait_key.clone(),
original_type_id,
resolved_type_id,
});
}
ty::TyTraitItem::Constant(decl_ref) if decl_ref.name() == item_name => {
matching_items.push(CandidateTraitItem {
item: ty_item.clone(),
trait_key: trait_key.clone(),
original_type_id,
resolved_type_id,
});
}
ty::TyTraitItem::Type(decl_ref) if decl_ref.name() == item_name => {
matching_items.push(CandidateTraitItem {
item: ty_item.clone(),
trait_key: trait_key.clone(),
original_type_id,
resolved_type_id,
});
}
_ => {}
},
};
TraitMap::find_items_and_trait_key_for_type(
local_module,
self.engines,
resolved_type_id,
&mut filter_item,
);
// grab the items from where the argument type is declared
if let Some(MethodName::FromTrait { .. }) = method_name {
let type_module = self.get_namespace_module_from_type_id(resolved_type_id);
if let Ok(type_module) = type_module {
TraitMap::find_items_and_trait_key_for_type(
type_module,
self.engines,
resolved_type_id,
&mut filter_item,
);
}
}
if item_prefix != self.namespace().current_mod_path.as_slice() {
// grab the module where the type itself is declared
let type_module = self
.namespace()
.require_module_from_absolute_path(handler, item_prefix)?;
// grab the items from where the type is declared
TraitMap::find_items_and_trait_key_for_type(
type_module,
self.engines,
resolved_type_id,
&mut filter_item,
);
}
Ok(matching_items)
}
fn get_namespace_module_from_type_id(&self, type_id: TypeId) -> Result<&Module, ErrorEmitted> {
let type_info = self.engines().te().get(type_id);
if type_info.is_alias() {
if let TypeInfo::Alias { ty, .. } = &*type_info {
return self.get_namespace_module_from_type_id(ty.type_id);
}
}
let handler = Handler::default();
let call_path = match *type_info {
TypeInfo::Enum(decl_id) => self.engines().de().get_enum(&decl_id).call_path.clone(),
TypeInfo::Struct(decl_id) => self.engines().de().get_struct(&decl_id).call_path.clone(),
_ => {
return Err(handler.emit_err(CompileError::Internal(
"No call path for type id",
Span::dummy(),
)))
}
};
let call_path = call_path.rshift();
self.namespace()
.require_module_from_absolute_path(&handler, &call_path.as_vec_ident())
}
fn default_numeric_if_needed(
&self,
handler: &Handler,
type_id: TypeId,
method_name: &Ident,
) -> Result<(), ErrorEmitted> {
let type_engine = self.engines.te();
// Default numeric types to u64
if type_engine.contains_numeric(self.engines, type_id) {
// While collecting unifications we don't decay numeric and will ignore this error.
if self.collecting_unifications() {
return Err(handler.emit_err(CompileError::MethodNotFound {
called_method: method_name.into(),
expected_signature: method_name.clone().as_str().to_string(),
type_name: self.engines.help_out(type_id).to_string(),
matching_methods: vec![],
}));
}
type_engine.decay_numeric(handler, self.engines, type_id, &method_name.span())?;
}
Ok(())
}
/// Collect all candidate trait items that might provide the method:
/// - Items directly available for `type_id`
/// - Plus items from any annotation-type inner that can coerce to `type_id`
fn collect_candidate_items(
&self,
handler: &Handler,
type_id: TypeId,
method_prefix: &ModulePath,
method_ident: &Ident,
method_name: &Option<&MethodName>,
) -> Result<Vec<ty::TyTraitItem>, ErrorEmitted> {
// Start with items for the concrete type.
let mut items =
self.find_items_for_type(handler, type_id, method_prefix, method_ident, method_name)?;
if method_name.is_none() {
return Ok(items.into_iter().map(|candidate| candidate.item).collect());
}
if let Some(method_name) = method_name {
let method_constraints = self.trait_constraints_from_method_name(handler, method_name);
self.filter_items_by_trait_access(&mut items, method_constraints.as_ref());
}
Ok(items.into_iter().map(|candidate| candidate.item).collect())
}
fn trait_constraints_from_method_name(
&self,
handler: &Handler,
method_name: &MethodName,
) -> Option<(TypeId, Vec<TraitConstraint>)> {
let _ = handler;
let MethodName::FromType {
call_path_binding, ..
} = method_name
else {
return None;
};
let (_, type_ident) = &call_path_binding.inner.suffix;
let resolve_handler = Handler::default();
let Ok((resolved_decl, _)) = self.namespace().current_module().resolve_symbol(
&resolve_handler,
self.engines(),
type_ident,
) else {
return None;
};
match resolved_decl.expect_typed() {
ty::TyDecl::GenericTypeForFunctionScope(ty::GenericTypeForFunctionScope {
type_id,
..
}) => {
let mut constraints = Vec::new();
let mut visited = HashSet::new();
self.collect_trait_constraints_recursive(type_id, &mut constraints, &mut visited);
Some((type_id, constraints))
}
_ => None,
}
}
/// Filter the candidate trait items so that only methods whose traits satisfy the relevant
/// trait bounds remain. Groups corresponding to other generic parameters are left untouched.
fn filter_items_by_trait_access(
&self,
items: &mut Vec<CandidateTraitItem>,
method_constraints: Option<&(TypeId, Vec<TraitConstraint>)>,
) {
if items.is_empty() {
return;
}
// Group candidates by the (possibly still generic) type they originated from so we can
// later apply trait bounds per generic parameter.
let mut grouped: BTreeMap<TypeId, Vec<CandidateTraitItem>> = BTreeMap::new();
for item in items.drain(..) {
grouped
.entry(
self.engines
.te()
.get_unaliased_type_id(item.resolved_type_id),
)
.or_default()
.push(item);
}
// If this lookup is resolving a concrete method name, pre-compute the generic type whose
// bounds we collected so we only apply those bounds to matching groups.
let method_constraint_info = method_constraints.and_then(|(type_id, constraints)| {
(!constraints.is_empty()).then_some((*type_id, constraints.as_slice()))
});
let type_engine = self.engines.te();
let mut filtered = Vec::new();
for (type_id, group) in grouped {
let type_info = type_engine.get(type_id);
if !matches!(
*type_info,
TypeInfo::UnknownGeneric { .. } | TypeInfo::Placeholder(_)
) {
filtered.extend(group);
continue;
}
let (interface_items, impl_items): (Vec<_>, Vec<_>) =
group.into_iter().partition(|item| {
matches!(
item.trait_key.is_impl_interface_surface,
IsImplInterfaceSurface::Yes
)
});
// Only groups born from the same generic parameter as the method call need to honour
// the method's trait bounds. Other generic parameters can pass through untouched.
let extra_constraints =
method_constraint_info.and_then(|(constraint_type_id, constraints)| {
let applies_to_group =
interface_items.iter().chain(impl_items.iter()).any(|item| {
self.engines
.te()
.get_unaliased_type_id(item.original_type_id)
== constraint_type_id
});
applies_to_group.then_some(constraints)
});
let allowed_traits =
self.allowed_traits_for_type(type_id, &interface_items, extra_constraints);
if allowed_traits.is_empty() {
filtered.extend(interface_items);
filtered.extend(impl_items);
continue;
}
if !impl_items.is_empty() {
let mut retained_impls = Vec::new();
for item in impl_items {
if self.trait_key_matches_allowed(&item.trait_key, &allowed_traits) {
retained_impls.push(item);
}
}
if !retained_impls.is_empty() {
filtered.extend(retained_impls);
filtered.extend(interface_items);
continue;
}
}
// No impl methods matched the bounds, so fall back to the interface placeholders.
filtered.extend(interface_items);
}
*items = filtered;
}
/// Build the list of trait paths that should remain visible for the given `type_id` when
/// resolving a method. This includes traits that supplied the interface surface entries as well
/// as any traits required by bounds on the generic parameter.
fn allowed_traits_for_type(
&self,
type_id: TypeId,
interface_items: &[CandidateTraitItem],
extra_constraints: Option<&[TraitConstraint]>,
) -> Vec<CallPath<TraitSuffix>> {
// Seed the allow-list with the traits that provided the interface items. They act as
// fallbacks whenever no concrete implementation matches the bounds.
let mut allowed: Vec<CallPath<TraitSuffix>> = interface_items
.iter()
.map(|item| item.trait_key.name.as_ref().clone())
.collect();
// Add trait bounds declared on the type parameter itself (recursively following inherited
// bounds) so they can participate in disambiguation.
let mut constraints = Vec::new();
let mut visited = HashSet::new();
self.collect_trait_constraints_recursive(type_id, &mut constraints, &mut visited);
for constraint in constraints {
let canonical = constraint
.trait_name
.to_canonical_path(self.engines(), self.namespace());
allowed.push(CallPath {
prefixes: canonical.prefixes,
suffix: TraitSuffix {
name: canonical.suffix,
args: constraint.type_arguments.clone(),
},
callpath_type: canonical.callpath_type,
});
}
// Method-specific bounds (for example from `fn foo<T: Trait>()`) are supplied separately,
// include them so only the permitted traits remain candidates after filtering.
if let Some(extra) = extra_constraints {
for constraint in extra {
let canonical = constraint
.trait_name
.to_canonical_path(self.engines(), self.namespace());
allowed.push(CallPath {
prefixes: canonical.prefixes,
suffix: TraitSuffix {
name: canonical.suffix,
args: constraint.type_arguments.clone(),
},
callpath_type: canonical.callpath_type,
});
}
}
self.dedup_allowed_traits(allowed)
}
/// Remove equivalent trait paths (up to type-argument unification) from the allow-list to
/// avoid redundant comparisons later on.
fn dedup_allowed_traits(
&self,
allowed: Vec<CallPath<TraitSuffix>>,
) -> Vec<CallPath<TraitSuffix>> {
let mut deduped = Vec::new();
let unify_check = UnifyCheck::constraint_subset(self.engines);
for entry in allowed.into_iter() {
if deduped
.iter()
.any(|existing| trait_paths_equivalent(existing, &entry, &unify_check))
{
continue;
}
deduped.push(entry);
}
deduped
}
/// Recursively collect trait constraints that apply to `type_id`, following aliases,
/// placeholders, and chains of generic parameters.
fn collect_trait_constraints_recursive(
&self,
type_id: TypeId,
acc: &mut Vec<TraitConstraint>,
visited: &mut HashSet<TypeId>,
) {
let type_engine = self.engines.te();
let type_id = type_engine.get_unaliased_type_id(type_id);
if !visited.insert(type_id) {
return;
}
match &*type_engine.get(type_id) {
TypeInfo::UnknownGeneric {
trait_constraints,
parent,
..
} => {
acc.extend(trait_constraints.iter().cloned());
if let Some(parent_id) = parent {
self.collect_trait_constraints_recursive(*parent_id, acc, visited);
}
}
TypeInfo::Placeholder(TypeParameter::Type(generic)) => {
acc.extend(generic.trait_constraints.iter().cloned());
self.collect_trait_constraints_recursive(generic.type_id, acc, visited);
}
TypeInfo::Alias { ty, .. } => {
self.collect_trait_constraints_recursive(ty.type_id, acc, visited);
}
_ => {}
}
}
/// Keep only the trait methods whose originating trait satisfies the collected constraints.
fn retain_trait_methods_matching_constraints(
&self,
trait_methods: &mut BTreeMap<GroupingKey, DeclRefFunction>,
constraints: &[TraitConstraint],
) {
if constraints.is_empty() {
return;
}
// Precompute the canonical trait paths allowed by the constraints so we can filter impls.
let allowed_traits = constraints
.iter()
.map(|constraint| {
let canonical = constraint
.trait_name
.to_canonical_path(self.engines(), self.namespace());
CallPath {
prefixes: canonical.prefixes,
suffix: TraitSuffix {
name: canonical.suffix,
args: constraint.type_arguments.clone(),
},
callpath_type: canonical.callpath_type,
}
})
.collect::<Vec<_>>();
if allowed_traits.is_empty() {
return;
}
let mut filtered = trait_methods.clone();
let unify_check = UnifyCheck::constraint_subset(self.engines);
filtered.retain(|(_impl_id, _), decl_ref| {
let method = self.engines.de().get_function(decl_ref);
let Some(ty::TyDecl::ImplSelfOrTrait(impl_ref)) = method.implementing_type.as_ref()
else {
return true;
};
let impl_decl = self.engines.de().get_impl_self_or_trait(&impl_ref.decl_id);
// Inherent impls have no trait declaration, keep them untouched.
if impl_decl.trait_decl_ref.is_none() {
return true;
}
// Build the canonical trait path and check whether it matches any of the trait bounds
// collected for this lookup. Only methods provided by traits that satisfy the bounds
// remain candidates for disambiguation.
let canonical = impl_decl
.trait_name
.to_canonical_path(self.engines(), self.namespace());
let candidate = CallPath {
prefixes: canonical.prefixes,
suffix: TraitSuffix {
name: canonical.suffix,
args: impl_decl.trait_type_arguments.clone(),
},
callpath_type: canonical.callpath_type,
};
allowed_traits
.iter()
.any(|allowed| trait_paths_equivalent(allowed, &candidate, &unify_check))
});
if !filtered.is_empty() {
*trait_methods = filtered;
}
}
fn trait_key_matches_allowed(
&self,
trait_key: &TraitKey,
allowed_traits: &[CallPath<TraitSuffix>],
) -> bool {
if allowed_traits.is_empty() {
return false;
}
let call_path = trait_key.name.as_ref();
let unify_check = UnifyCheck::constraint_subset(self.engines);
allowed_traits
.iter()
.any(|allowed| trait_paths_equivalent(allowed, call_path, &unify_check))
}
/// Convert collected items to just the method decl refs we care about.
fn items_to_method_refs(&self, items: Vec<ty::TyTraitItem>) -> Vec<DeclRefFunction> {
items
.into_iter()
.filter_map(|item| match item {
ty::TyTraitItem::Fn(decl_ref) => Some(decl_ref),
_ => None,
})
.collect()
}
fn to_method_candidate(&self, decl_ref: &DeclRefFunction) -> MethodCandidate {
let decl_engine = self.engines.de();
let fn_decl = decl_engine.get_function(decl_ref);
MethodCandidate {
decl_ref: decl_ref.clone(),
params: fn_decl
.parameters
.iter()
.map(|p| p.type_argument.type_id)
.collect(),
ret: fn_decl.return_type.type_id,
is_contract_call: fn_decl.is_contract_call,
}
}
/// Decide whether `cand` matches the given argument and annotation types.
fn score_method_candidate(
&self,
cand: &MethodCandidate,
argument_types: &[TypeId],
annotation_type: TypeId,
) -> MatchScore {
let eq_check = UnifyCheck::constraint_subset(self.engines).with_unify_ref_mut(false);
let coercion_check = UnifyCheck::coercion(self.engines).with_ignore_generic_names(true);
// Handle "self" for contract calls.
let args_len_diff = if cand.is_contract_call && !argument_types.is_empty() {
1
} else {
0
};
// Parameter count must match.
if cand.params.len() != argument_types.len().saturating_sub(args_len_diff) {
return MatchScore::Incompatible;
}
// Param-by-param check.
let mut all_exact = true;
for (p, a) in cand
.params
.iter()
.zip(argument_types.iter().skip(args_len_diff))
{
if eq_check.check(*a, *p) {
continue;
}
if coercion_check.check(*a, *p) {
all_exact = false;
continue;
}
return MatchScore::Incompatible;
}
let type_engine = self.engines.te();
let ann = &*type_engine.get(annotation_type);
let ret_ok = matches!(ann, TypeInfo::Unknown)
|| matches!(&*type_engine.get(cand.ret), TypeInfo::Never)
|| coercion_check.check(annotation_type, cand.ret);
if !ret_ok {
return MatchScore::Incompatible;
}
if all_exact {
MatchScore::Exact
} else {
MatchScore::Coercible
}
}
/// Keep only compatible candidates (coercible or exact).
fn filter_method_candidates_by_signature(
&self,
decl_refs: &Vec<DeclRefFunction>,
argument_types: &[TypeId],
annotation_type: TypeId,
) -> Vec<MethodCandidate> {
let mut out = Vec::new();
for r in decl_refs {
let cand = self.to_method_candidate(r);
match self.score_method_candidate(&cand, argument_types, annotation_type) {
MatchScore::Exact | MatchScore::Coercible => out.push(cand),
MatchScore::Incompatible => {}
}
}
out
}
/// Group signature-compatible method decl refs by their originating impl block,
/// optionally filtering by a qualified trait path.
fn group_by_trait_impl(
&self,
handler: &Handler,
method_name: &Option<&MethodName>,
method_decl_refs: &[DeclRefFunction],
) -> Result<GroupingResult, ErrorEmitted> {
let decl_engine = self.engines.de();
let type_engine = self.engines.te();
let eq_check = UnifyCheck::constraint_subset(self.engines);
// Extract `<... as Trait::<Args>>::method` info, if present.
let (qualified_call_path, trait_method_name_binding_type_args): (
Option<QualifiedCallPath>,
Option<Vec<_>>,
) = match method_name {
Some(MethodName::FromQualifiedPathRoot { as_trait, .. }) => {
match &*type_engine.get(*as_trait) {
TypeInfo::Custom {
qualified_call_path: cp,
type_arguments,
} => (Some(cp.clone()), type_arguments.clone()),
_ => (None, None),
}
}
_ => (None, None),
};
// Helper: compare two type arguments after resolution.
let types_equal = |a: (&GenericArgument, &GenericArgument)| -> Result<bool, ErrorEmitted> {
let (p1, p2) = a;
let p1_id = self.resolve_type(
handler,
p1.type_id(),
&p1.span(),
EnforceTypeArguments::Yes,
None,
)?;
let p2_id = self.resolve_type(
handler,
p2.type_id(),
&p2.span(),
EnforceTypeArguments::Yes,
None,
)?;
Ok(eq_check.check(p1_id, p2_id))
};
// Helper: check whether this impl matches the optional qualified trait filter.
let matches_trait_filter =
|trait_decl: &ty::TyImplSelfOrTrait| -> Result<bool, ErrorEmitted> {
// If there's no qualified trait filter, accept everything.
let Some(qcp) = &qualified_call_path else {
return Ok(true);
};
// Trait name must match the one from the qualified path.
if trait_decl.trait_name != qcp.clone().to_call_path(handler)? {
return Ok(false);
}
// If the qualified path provided type arguments, they must match the impl's.
if let Some(params) = &trait_method_name_binding_type_args {
if params.len() != trait_decl.trait_type_arguments.len() {
return Ok(false);
}
for pair in params.iter().zip(trait_decl.trait_type_arguments.iter()) {
if !types_equal(pair)? {
return Ok(false);
}
}
}
Ok(true)
};
let mut trait_methods: BTreeMap<GroupingKey, DeclRefFunction> = BTreeMap::new();
let mut impl_self_method: Option<DeclRefFunction> = None;
for method_ref in method_decl_refs {
let method = decl_engine.get_function(method_ref);
// Only keep methods from an impl block (trait or inherent).
let Some(ty::TyDecl::ImplSelfOrTrait(impl_trait)) = method.implementing_type.as_ref()
else {
continue;
};
let trait_decl = decl_engine.get_impl_self_or_trait(&impl_trait.decl_id);
if !matches_trait_filter(&trait_decl)? {
continue;
}
let key: GroupingKey = (impl_trait.decl_id, method.implementing_for);
// Prefer the method that is type-check finalized when conflicting.
match trait_methods.get_mut(&key) {
Some(existing_ref) => {
let existing = decl_engine.get_function(existing_ref);
if !existing.is_type_check_finalized || method.is_type_check_finalized {
*existing_ref = method_ref.clone();
}
}
None => {
trait_methods.insert(key, method_ref.clone());
}
}
// Track presence of an inherent impl so we can prefer it later.
if trait_decl.trait_decl_ref.is_none() {
impl_self_method = Some(method_ref.clone());
}
}
Ok(GroupingResult {
trait_methods,
impl_self_method,
qualified_call_path,
})
}
fn prefer_non_blanket_impls(&self, trait_methods: &mut BTreeMap<GroupingKey, DeclRefFunction>) {
let decl_engine = self.engines.de();
let non_blanket_impl_exists = {
trait_methods.values().any(|v| {
let m = decl_engine.get_function(v);
!m.is_from_blanket_impl(self.engines)
})
};
if non_blanket_impl_exists {
trait_methods.retain(|_, v| {
let m = decl_engine.get_function(v);
!m.is_from_blanket_impl(self.engines)
});
}
}
/// Format the trait name (including type arguments) for diagnostic output.
fn trait_sig_string(&self, impl_id: &TraitImplId) -> String {
let de = self.engines.de();
let trait_decl = de.get_impl_self_or_trait(impl_id);
if trait_decl.trait_type_arguments.is_empty() {
trait_decl.trait_name.suffix.to_string()
} else {
let args = trait_decl
.trait_type_arguments
.iter()
.map(|ga| self.engines.help_out(ga).to_string())
.collect::<Vec<_>>()
.join(", ");
format!("{}<{}>", trait_decl.trait_name.suffix, args)
}
}
/// Choose the final method candidate from the grouped impls, handling inherent impl
/// precedence, exact matches, and ambiguity diagnostics.
fn select_method_from_grouped(
&self,
handler: &Handler,
method_name: &Ident,
type_id: TypeId,
trait_methods: &BTreeMap<GroupingKey, DeclRefFunction>,
impl_self_method: &Option<DeclRefFunction>,
call_site_type_id: Option<TypeId>,
) -> Result<Option<DeclRefFunction>, ErrorEmitted> {
let decl_engine = self.engines.de();
let eq_check = UnifyCheck::constraint_subset(self.engines);
match trait_methods.len() {
0 => Ok(None),
1 => Ok(trait_methods.values().next().cloned()),
_ => {
// Prefer inherent impl when mixed with trait methods.
if let Some(impl_self) = impl_self_method {
return Ok(Some(impl_self.clone()));
}
// Exact implementing type wins.
let mut exact = vec![];
for r in trait_methods.values() {
let m = decl_engine.get_function(r);
if let Some(impl_for) = m.implementing_for {
if eq_check.with_unify_ref_mut(false).check(impl_for, type_id) {
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/program.rs | sway-core/src/semantic_analysis/program.rs | use std::sync::Arc;
use crate::{
language::{
parsed::ParseProgram,
ty::{self, TyModule, TyProgram},
},
metadata::MetadataManager,
semantic_analysis::{
namespace::{self, Package},
TypeCheckContext,
},
BuildConfig, Engines,
};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_features::ExperimentalFeatures;
use sway_ir::{Context, Module};
use super::{
symbol_collection_context::SymbolCollectionContext, TypeCheckAnalysis,
TypeCheckAnalysisContext, TypeCheckFinalization, TypeCheckFinalizationContext,
};
#[derive(Clone, Debug)]
pub struct TypeCheckFailed {
pub root_module: Option<Arc<TyModule>>,
pub namespace: Package,
pub error: ErrorEmitted,
}
impl TyProgram {
/// Collects the given parsed program to produce a symbol maps.
///
/// The given `initial_namespace` acts as an initial state for each module within this program.
/// It should contain a submodule for each library package dependency.
pub fn collect(
handler: &Handler,
engines: &Engines,
parsed: &ParseProgram,
namespace: namespace::Namespace,
) -> Result<SymbolCollectionContext, ErrorEmitted> {
let mut ctx = SymbolCollectionContext::new(namespace);
let ParseProgram { root, kind: _ } = parsed;
ty::TyModule::collect(handler, engines, &mut ctx, root)?;
Ok(ctx)
}
/// Type-check the given parsed program to produce a typed program.
///
/// The given `namespace` acts as an initial state for each module within this program.
/// It should contain a submodule for each library package dependency.
#[allow(clippy::result_large_err)]
#[allow(clippy::too_many_arguments)]
pub fn type_check(
handler: &Handler,
engines: &Engines,
parsed: &ParseProgram,
collection_ctx: &mut SymbolCollectionContext,
mut namespace: namespace::Namespace,
package_name: &str,
build_config: Option<&BuildConfig>,
experimental: ExperimentalFeatures,
) -> Result<Self, TypeCheckFailed> {
let mut ctx =
TypeCheckContext::from_root(&mut namespace, collection_ctx, engines, experimental)
.with_kind(parsed.kind);
let ParseProgram { root, kind } = parsed;
let root = ty::TyModule::type_check(
handler,
ctx.by_ref(),
engines,
parsed.kind,
root,
build_config,
)
.map_err(|error| TypeCheckFailed {
error,
root_module: None,
namespace: ctx.namespace.current_package_ref().clone(),
})?;
let experimental = ctx.experimental;
let (kind, declarations, configurables) =
Self::validate_root(handler, engines, &root, *kind, package_name, experimental)
.map_err(|error| TypeCheckFailed {
error,
root_module: Some(root.clone()),
namespace: ctx.namespace.current_package_ref().clone(),
})?;
let mut namespace = ctx.namespace().clone();
Self::validate_coherence(handler, engines, &root, &mut namespace).map_err(|error| {
TypeCheckFailed {
error,
root_module: Some(root.clone()),
namespace: ctx.namespace.current_package_ref().clone(),
}
})?;
let program = TyProgram {
kind,
root_module: (*root).clone(),
namespace,
declarations,
configurables,
storage_slots: vec![],
logged_types: vec![],
messages_types: vec![],
};
Ok(program)
}
pub(crate) fn get_typed_program_with_initialized_storage_slots(
&mut self,
handler: &Handler,
engines: &Engines,
context: &mut Context,
md_mgr: &mut MetadataManager,
module: Module,
) -> Result<(), ErrorEmitted> {
let decl_engine = engines.de();
match &self.kind {
ty::TyProgramKind::Contract { .. } => {
let storage_decl = self
.declarations
.iter()
.find(|decl| matches!(decl, ty::TyDecl::StorageDecl { .. }));
// Expecting at most a single storage declaration
match storage_decl {
Some(ty::TyDecl::StorageDecl(ty::StorageDecl { decl_id, .. })) => {
let decl = decl_engine.get_storage(decl_id);
let mut storage_slots = decl.get_initialized_storage_slots(
handler, engines, context, md_mgr, module,
)?;
// Sort the slots to standardize the output. Not strictly required by the
// spec.
storage_slots.sort();
self.storage_slots = storage_slots;
Ok(())
}
_ => {
self.storage_slots = vec![];
Ok(())
}
}
}
_ => {
self.storage_slots = vec![];
Ok(())
}
}
}
}
impl TypeCheckAnalysis for TyProgram {
fn type_check_analyze(
&self,
handler: &Handler,
ctx: &mut TypeCheckAnalysisContext,
) -> Result<(), ErrorEmitted> {
for node in self.root_module.all_nodes.iter() {
node.type_check_analyze(handler, ctx)?;
}
Ok(())
}
}
impl TypeCheckFinalization for TyProgram {
fn type_check_finalize(
&mut self,
handler: &Handler,
ctx: &mut TypeCheckFinalizationContext,
) -> Result<(), ErrorEmitted> {
handler.scope(|handler| {
for node in self.root_module.all_nodes.iter_mut() {
let _ = node.type_check_finalize(handler, ctx);
}
Ok(())
})
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/symbol_resolve_context.rs | sway-core/src/semantic_analysis/symbol_resolve_context.rs | use crate::{
engine_threading::*,
language::{CallPath, Visibility},
namespace::ResolvedDeclaration,
semantic_analysis::{ast_node::ConstShadowingMode, Namespace},
type_system::TypeId,
};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::{span::Span, Ident};
use super::{
symbol_collection_context::SymbolCollectionContext,
type_resolve::{resolve_call_path, VisibilityCheck},
GenericShadowingMode,
};
/// Contextual state tracked and accumulated throughout symbol resolving.
pub struct SymbolResolveContext<'a> {
/// The namespace context accumulated throughout symbol resolving.
///
/// Internally, this includes:
///
/// - The `root` module from which all other modules maybe be accessed using absolute paths.
/// - The `init` module used to initialize submodule namespaces.
/// - A `mod_path` that represents the current module being type-checked. This is automatically
/// updated upon entering/exiting submodules via the `enter_submodule` method.
pub(crate) engines: &'a Engines,
pub(crate) symbol_collection_ctx: &'a mut SymbolCollectionContext,
// The following set of fields are intentionally private. When a `SymbolResolveContext` is passed
// into a new node during symbol resolving, these fields should be updated using the `with_*`
// methods which provides a new `SymbolResolveContext`, ensuring we don't leak our changes into
// the parent nodes.
/// While symbol resolving an `impl` (whether inherent or for a `trait`/`abi`) this represents the
/// type for which we are implementing. For example in `impl Foo {}` or `impl Trait for Foo
/// {}`, this represents the type ID of `Foo`.
self_type: Option<TypeId>,
/// Whether or not a const declaration shadows previous const declarations sequentially.
///
/// This is `Sequential` while checking const declarations in functions, otherwise `ItemStyle`.
const_shadowing_mode: ConstShadowingMode,
/// Whether or not a generic type parameters shadows previous generic type parameters.
///
/// This is `Disallow` everywhere except while checking type parameters bounds in struct instantiation.
generic_shadowing_mode: GenericShadowingMode,
}
impl<'a> SymbolResolveContext<'a> {
/// Initialize a symbol resolving context with a namespace.
pub fn new(
engines: &'a Engines,
symbol_collection_ctx: &'a mut SymbolCollectionContext,
) -> Self {
Self {
engines,
symbol_collection_ctx,
self_type: None,
const_shadowing_mode: ConstShadowingMode::ItemStyle,
generic_shadowing_mode: GenericShadowingMode::Disallow,
}
}
/// Create a new context that mutably borrows the inner `namespace` with a lifetime bound by
/// `self`.
///
/// This is particularly useful when symbol resolving a node that has more than one child node
/// (very often the case). By taking the context with the namespace lifetime bound to `self`
/// rather than the original namespace reference, we instead restrict the returned context to
/// the local scope and avoid consuming the original context when providing context to the
/// first visited child node.
pub fn by_ref(&mut self) -> SymbolResolveContext<'_> {
SymbolResolveContext {
engines: self.engines,
symbol_collection_ctx: self.symbol_collection_ctx,
self_type: self.self_type,
const_shadowing_mode: self.const_shadowing_mode,
generic_shadowing_mode: self.generic_shadowing_mode,
}
}
/// Scope the `SymbolResolveContext` with a new namespace lexical scope.
pub fn enter_lexical_scope<T>(
self,
handler: &Handler,
span: Span,
with_scoped_ctx: impl FnOnce(SymbolResolveContext) -> Result<T, ErrorEmitted>,
) -> Result<T, ErrorEmitted> {
let engines = self.engines;
self.symbol_collection_ctx.enter_lexical_scope(
handler,
engines,
span,
|sub_scope_collect_ctx| {
let sub_scope_resolve_ctx =
SymbolResolveContext::new(engines, sub_scope_collect_ctx);
with_scoped_ctx(sub_scope_resolve_ctx)
},
)
}
/// Enter the submodule with the given name and a symbol resolve context ready for
/// symbol resolving its content.
///
/// Returns the result of the given `with_submod_ctx` function.
pub fn enter_submodule<T>(
self,
handler: &Handler,
mod_name: Ident,
visibility: Visibility,
module_span: Span,
with_submod_ctx: impl FnOnce(SymbolResolveContext) -> T,
) -> Result<T, ErrorEmitted> {
let engines = self.engines;
self.symbol_collection_ctx.enter_submodule(
handler,
engines,
mod_name,
visibility,
module_span,
|submod_collect_ctx| {
let submod_ctx = SymbolResolveContext::new(engines, submod_collect_ctx);
with_submod_ctx(submod_ctx)
},
)
}
/// Returns a mutable reference to the current namespace.
pub fn namespace_mut(&mut self) -> &mut Namespace {
&mut self.symbol_collection_ctx.namespace
}
/// Returns a reference to the current namespace.
pub fn namespace(&self) -> &Namespace {
&self.symbol_collection_ctx.namespace
}
/// Map this `SymbolResolveContext` instance to a new one with the given const shadowing `mode`.
#[allow(unused)]
pub(crate) fn with_const_shadowing_mode(
self,
const_shadowing_mode: ConstShadowingMode,
) -> Self {
Self {
const_shadowing_mode,
..self
}
}
/// Map this `SymbolResolveContext` instance to a new one with the given generic shadowing `mode`.
#[allow(unused)]
pub(crate) fn with_generic_shadowing_mode(
self,
generic_shadowing_mode: GenericShadowingMode,
) -> Self {
Self {
generic_shadowing_mode,
..self
}
}
// A set of accessor methods. We do this rather than making the fields `pub` in order to ensure
// that these are only updated via the `with_*` methods that produce a new `SymbolResolveContext`.
#[allow(unused)]
pub(crate) fn self_type(&self) -> Option<TypeId> {
self.self_type
}
#[allow(unused)]
pub(crate) fn const_shadowing_mode(&self) -> ConstShadowingMode {
self.const_shadowing_mode
}
#[allow(unused)]
pub(crate) fn generic_shadowing_mode(&self) -> GenericShadowingMode {
self.generic_shadowing_mode
}
/// Get the engines needed for engine threading.
pub(crate) fn engines(&self) -> &'a Engines {
self.engines
}
/// Short-hand for calling [Root::resolve_call_path_with_visibility_check] on `root` with the `mod_path`.
pub(crate) fn resolve_call_path_with_visibility_check(
&self,
handler: &Handler,
call_path: &CallPath,
) -> Result<ResolvedDeclaration, ErrorEmitted> {
resolve_call_path(
handler,
self.engines(),
self.namespace(),
&self.namespace().current_mod_path,
call_path,
self.self_type(),
VisibilityCheck::Yes,
)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/coins_analysis.rs | sway-core/src/semantic_analysis/coins_analysis.rs | use sway_error::handler::Handler;
use crate::language::ty;
use super::TypeCheckContext;
// This analysis checks if an expression is known statically to evaluate
// to a non-zero value at runtime.
// It's intended to be used in the payability analysis to check if a non-payable
// method gets called with a non-zero amount of `coins`
pub fn possibly_nonzero_u64_expression(ctx: &TypeCheckContext, expr: &ty::TyExpression) -> bool {
use ty::TyExpressionVariant::*;
match &expr.expression {
Literal(crate::language::Literal::U64(value)) => *value != 0,
Literal(crate::language::Literal::Numeric(value)) => *value != 0,
// not a u64 literal, hence we return true to be on the safe side
Literal(_) => true,
ConstantExpression { decl, .. } => match &decl.value {
Some(expr) => possibly_nonzero_u64_expression(ctx, expr),
None => false,
},
ConfigurableExpression { decl, .. } => match &decl.value {
Some(expr) => possibly_nonzero_u64_expression(ctx, expr),
None => false,
},
ConstGenericExpression { decl, .. } => match decl.value.as_ref() {
Some(expr) => possibly_nonzero_u64_expression(ctx, expr),
None => true,
},
VariableExpression { name, .. } => {
match ctx.resolve_symbol(&Handler::default(), name).ok() {
Some(ty_decl) => {
match ty_decl {
ty::TyDecl::VariableDecl(var_decl) => {
possibly_nonzero_u64_expression(ctx, &var_decl.body)
}
ty::TyDecl::ConstantDecl(ty::ConstantDecl { decl_id, .. }) => {
let const_decl = ctx.engines.de().get_constant(&decl_id);
match &const_decl.value {
Some(value) => possibly_nonzero_u64_expression(ctx, value),
None => true,
}
}
_ => true, // impossible cases, true is a safer option here
}
}
None => {
// Unknown variable, but it's not possible in a well-typed expression
// returning true here just to be on the safe side
true
}
}
}
// We do not treat complex expressions at the moment: the rational for this
// is that the `coins` contract call parameter is usually a literal, a variable,
// or a constant.
// Since we don't analyze the following types of expressions, we just assume
// those result in non-zero amount of coins
FunctionApplication { .. }
| ArrayIndex { .. }
| CodeBlock(_)
| MatchExp { .. }
| IfExp { .. }
| AsmExpression { .. }
| StructFieldAccess { .. }
| TupleElemAccess { .. }
| StorageAccess(_)
| WhileLoop { .. }
| ForLoop { .. } => true,
// The following expression variants are unreachable, because of the type system
// but we still consider these as non-zero to be on the safe side
LazyOperator { .. }
| Tuple { .. }
| ArrayExplicit { .. }
| ArrayRepeat { .. }
| StructExpression { .. }
| FunctionParameter
| EnumInstantiation { .. }
| AbiCast { .. }
| IntrinsicFunction(_)
| AbiName(_)
| UnsafeDowncast { .. }
| EnumTag { .. }
| Break
| Continue
| Reassignment(_)
| ImplicitReturn(_)
| Return(_)
| Panic(_)
| Ref(_)
| Deref(_) => true,
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/module.rs | sway-core/src/semantic_analysis/module.rs | use std::{
collections::{HashMap, HashSet},
fmt::Display,
fs,
sync::Arc,
};
use graph_cycles::Cycles;
use indexmap::IndexMap;
use itertools::Itertools;
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
warning::{CompileWarning, Warning},
};
use sway_types::{BaseIdent, Named, SourceId, Span, Spanned};
use crate::{
decl_engine::{DeclEngineGet, DeclId},
engine_threading::{DebugWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
is_ty_module_cache_up_to_date,
language::{
parsed::*,
ty::{self, TyAstNodeContent, TyDecl, TyEnumDecl},
CallPath, ModName,
},
query_engine::{ModuleCacheKey, TypedModuleInfo},
semantic_analysis::*,
BuildConfig, Engines, TypeInfo,
};
use super::{
declaration::auto_impl::{
abi_encoding::AbiEncodingAutoImplContext, debug::DebugAutoImplContext,
marker_traits::MarkerTraitsAutoImplContext,
},
symbol_collection_context::SymbolCollectionContext,
};
#[derive(Clone, Debug)]
pub struct ModuleDepGraphEdge();
impl Display for ModuleDepGraphEdge {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "")
}
}
pub type ModuleDepGraphNodeId = petgraph::graph::NodeIndex;
#[derive(Clone, Debug)]
pub enum ModuleDepGraphNode {
Module {},
Submodule { name: ModName },
}
impl DebugWithEngines for ModuleDepGraphNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>, _engines: &Engines) -> std::fmt::Result {
let text = match self {
ModuleDepGraphNode::Module { .. } => {
format!("{:?}", "Root module")
}
ModuleDepGraphNode::Submodule { name: mod_name } => {
format!("{:?}", mod_name.as_str())
}
};
f.write_str(&text)
}
}
// Represents an ordered graph between declaration id indexes.
pub type ModuleDepNodeGraph = petgraph::graph::DiGraph<ModuleDepGraphNode, ModuleDepGraphEdge>;
pub struct ModuleDepGraph {
dep_graph: ModuleDepNodeGraph,
root: ModuleDepGraphNodeId,
node_name_map: HashMap<String, ModuleDepGraphNodeId>,
}
impl ModuleDepGraph {
pub(crate) fn new() -> Self {
Self {
dep_graph: Default::default(),
root: Default::default(),
node_name_map: Default::default(),
}
}
pub fn add_node(&mut self, node: ModuleDepGraphNode) -> ModuleDepGraphNodeId {
let node_id = self.dep_graph.add_node(node.clone());
match node {
ModuleDepGraphNode::Module {} => {}
ModuleDepGraphNode::Submodule { name: mod_name } => {
self.node_name_map.insert(mod_name.to_string(), node_id);
}
};
node_id
}
pub fn add_root_node(&mut self) -> ModuleDepGraphNodeId {
self.root = self.add_node(super::module::ModuleDepGraphNode::Module {});
self.root
}
fn get_node_id_for_module(
&self,
mod_name: &sway_types::BaseIdent,
) -> Option<ModuleDepGraphNodeId> {
self.node_name_map.get(&mod_name.to_string()).copied()
}
/// Prints out GraphViz DOT format for the dependency graph.
#[allow(dead_code)]
pub(crate) fn visualize(&self, engines: &Engines, print_graph: Option<String>) {
if let Some(graph_path) = print_graph {
use petgraph::dot::{Config, Dot};
let string_graph = self.dep_graph.filter_map(
|_idx, node| Some(format!("{:?}", engines.help_out(node))),
|_idx, edge| Some(format!("{edge}")),
);
let output = format!(
"{:?}",
Dot::with_attr_getters(
&string_graph,
&[Config::NodeNoLabel, Config::EdgeNoLabel],
&|_, er| format!("label = {:?}", er.weight()),
&|_, nr| {
let _node = &self.dep_graph[nr.0];
let shape = "";
let url = "".to_string();
format!("{shape} label = {:?} {url}", nr.1)
},
)
);
if graph_path.is_empty() {
tracing::info!("{output}");
} else {
let result = fs::write(graph_path.clone(), output);
if let Some(error) = result.err() {
tracing::error!(
"There was an issue while outputting module dep analysis graph to path {graph_path:?}\n{error}"
);
}
}
}
}
/// Computes the ordered list by dependency, which will be used for evaluating the modules
/// in the correct order. We run a topological sort and cycle finding algorithm to check
/// for unsupported cyclic dependency cases.
pub(crate) fn compute_order(
&self,
handler: &Handler,
) -> Result<ModuleEvaluationOrder, ErrorEmitted> {
// Check for dependency cycles in the graph by running the Johnson's algorithm.
let cycles = self.dep_graph.cycles();
if !cycles.is_empty() {
let mut modules = Vec::new();
for cycle in cycles.first().unwrap() {
let node = self.dep_graph.node_weight(*cycle).unwrap();
match node {
ModuleDepGraphNode::Module {} => unreachable!(),
ModuleDepGraphNode::Submodule { name } => modules.push(name.clone()),
};
}
return Err(handler.emit_err(CompileError::ModuleDepGraphCyclicReference { modules }));
}
// Do a topological sort to compute an ordered list of nodes.
let sorted = match petgraph::algo::toposort(&self.dep_graph, None) {
Ok(value) => value,
// If we were not able to toposort, this means there is likely a cycle in the module dependency graph,
// which we already handled above, so lets just return an empty evaluation order instead of panic'ing.
// module dependencies, which we have already reported.
Err(_) => return Err(handler.emit_err(CompileError::ModuleDepGraphEvaluationError {})),
};
let sorted = sorted
.into_iter()
.filter_map(|node_index| {
let node = self.dep_graph.node_weight(node_index);
match node {
Some(node) => match node {
ModuleDepGraphNode::Module {} => None, // root module
ModuleDepGraphNode::Submodule { name: mod_name } => Some(mod_name.clone()),
},
None => None,
}
})
.rev()
.collect::<Vec<_>>();
Ok(sorted)
}
}
impl ty::TyModule {
/// Analyzes the given parsed module to produce a dependency graph.
pub fn build_dep_graph(
handler: &Handler,
parsed: &ParseModule,
) -> Result<ModuleDepGraph, ErrorEmitted> {
let mut dep_graph = ModuleDepGraph::new();
dep_graph.add_root_node();
let ParseModule { submodules, .. } = parsed;
// Create graph nodes for each submodule.
submodules.iter().for_each(|(name, _submodule)| {
let sub_mod_node =
dep_graph.add_node(ModuleDepGraphNode::Submodule { name: name.clone() });
dep_graph
.dep_graph
.add_edge(dep_graph.root, sub_mod_node, ModuleDepGraphEdge {});
});
// Analyze submodules first in order of declaration.
submodules.iter().for_each(|(name, submodule)| {
let _ =
ty::TySubmodule::build_dep_graph(handler, &mut dep_graph, name.clone(), submodule);
});
Ok(dep_graph)
}
/// Collects the given parsed module to produce a module symbol map.
///
/// Recursively collects submodules first.
pub fn collect(
handler: &Handler,
engines: &Engines,
ctx: &mut SymbolCollectionContext,
parsed: &ParseModule,
) -> Result<(), ErrorEmitted> {
let ParseModule {
submodules,
tree,
module_eval_order,
attributes: _,
span: _,
hash: _,
..
} = parsed;
// Analyze submodules first in order of evaluation previously computed by the dependency graph.
module_eval_order.iter().for_each(|eval_mod_name| {
let (name, submodule) = submodules
.iter()
.find(|(submod_name, _submodule)| eval_mod_name == submod_name)
.unwrap();
let _ = ty::TySubmodule::collect(handler, engines, ctx, name.clone(), submodule);
});
let _ = tree
.root_nodes
.iter()
.map(|node| ty::TyAstNode::collect(handler, engines, ctx, node))
.filter_map(|res| res.ok())
.collect::<Vec<_>>();
Ok(())
}
/// Retrieves a cached typed module if it's up to date.
///
/// This function checks the cache for a typed module corresponding to the given source ID.
/// If found and up to date, it returns the cached module. Otherwise, it returns None.
fn get_cached_ty_module_if_up_to_date(
source_id: Option<&SourceId>,
engines: &Engines,
build_config: Option<&BuildConfig>,
) -> Option<(Arc<ty::TyModule>, Arc<namespace::Module>)> {
let source_id = source_id?;
// Create a cache key and get the module cache
let path = engines.se().get_path(source_id);
let include_tests = build_config.is_some_and(|x| x.include_tests);
let key = ModuleCacheKey::new(path.clone().into(), include_tests);
let cache = engines.qe().module_cache.read();
cache.get(&key).and_then(|entry| {
entry.typed.as_ref().and_then(|typed| {
// Check if the cached module is up to date
let is_up_to_date = is_ty_module_cache_up_to_date(
engines,
&path.into(),
include_tests,
build_config,
);
// Return the cached module if it's up to date, otherwise None
if is_up_to_date {
Some((typed.module.clone(), typed.namespace_module.clone()))
} else {
None
}
})
})
}
/// Type-check the given parsed module to produce a typed module.
///
/// Recursively type-checks submodules first.
pub fn type_check(
handler: &Handler,
mut ctx: TypeCheckContext,
engines: &Engines,
kind: TreeType,
parsed: &ParseModule,
build_config: Option<&BuildConfig>,
) -> Result<Arc<Self>, ErrorEmitted> {
let ParseModule {
submodules,
tree,
attributes,
span,
module_eval_order,
..
} = parsed;
// Try to get the cached root module if it's up to date
if let Some((ty_module, _namespace_module)) =
ty::TyModule::get_cached_ty_module_if_up_to_date(
parsed.span.source_id(),
engines,
build_config,
)
{
return Ok(ty_module);
}
// Type-check submodules first in order of evaluation previously computed by the dependency graph.
let submodules_res = module_eval_order
.iter()
.map(|eval_mod_name| {
let (name, submodule) = submodules
.iter()
.find(|(submod_name, _)| eval_mod_name == submod_name)
.unwrap();
// Try to get the cached submodule
if let Some(cached_module) = ty::TyModule::get_cached_ty_module_if_up_to_date(
submodule.module.span.source_id(),
engines,
build_config,
) {
// If cached, restore namespace module and return cached TySubmodule
let (ty_module, namespace_module) = cached_module;
ctx.namespace_mut()
.current_module_mut()
.import_cached_submodule(name, (*namespace_module).clone());
let ty_submod = ty::TySubmodule {
module: ty_module,
mod_name_span: submodule.mod_name_span.clone(),
};
Ok::<(BaseIdent, ty::TySubmodule), ErrorEmitted>((name.clone(), ty_submod))
} else {
// If not cached, type-check the submodule
let type_checked_submodule = ty::TySubmodule::type_check(
handler,
ctx.by_ref(),
engines,
name.clone(),
kind,
submodule,
build_config,
)?;
Ok((name.clone(), type_checked_submodule))
}
})
.collect::<Result<Vec<_>, _>>();
// TODO: Ordering should be solved across all modules prior to the beginning of type-check.
let ordered_nodes = node_dependencies::order_ast_nodes_by_dependency(
handler,
ctx.engines(),
tree.root_nodes.clone(),
)?;
let mut all_nodes = Self::type_check_nodes(handler, ctx.by_ref(), &ordered_nodes)?;
let submodules = submodules_res?;
let fallback_fn = collect_fallback_fn(&all_nodes, engines, handler)?;
match (&kind, &fallback_fn) {
(TreeType::Contract, _) | (_, None) => {}
(_, Some(fallback_fn)) => {
let fallback_fn = engines.de().get(fallback_fn);
return Err(handler.emit_err(CompileError::FallbackFnsAreContractOnly {
span: fallback_fn.span.clone(),
}));
}
}
if ctx.experimental.new_encoding {
let main_decl = all_nodes.iter_mut().find_map(|x| match &mut x.content {
ty::TyAstNodeContent::Declaration(ty::TyDecl::FunctionDecl(decl)) => {
let fn_decl = engines.de().get_function(&decl.decl_id);
(fn_decl.name.as_str() == "main").then_some(fn_decl)
}
_ => None,
});
match (&kind, main_decl.is_some()) {
(TreeType::Predicate, true) => {
let mut fn_generator = AbiEncodingAutoImplContext::new(&mut ctx);
if let Ok(node) = fn_generator.generate_predicate_entry(
engines,
main_decl.as_ref().unwrap(),
handler,
) {
all_nodes.push(node)
}
}
(TreeType::Script, true) => {
let mut fn_generator = AbiEncodingAutoImplContext::new(&mut ctx);
if let Ok(node) = fn_generator.generate_script_entry(
engines,
main_decl.as_ref().unwrap(),
handler,
) {
all_nodes.push(node)
}
}
(TreeType::Contract, _) => {
// collect all supertrait methods
let contract_supertrait_fns = submodules
.iter()
.flat_map(|x| x.1.module.submodules_recursive())
.flat_map(|x| x.1.module.contract_supertrait_fns(engines))
.chain(
all_nodes
.iter()
.flat_map(|x| x.contract_supertrait_fns(engines)),
)
.collect::<Vec<_>>();
// collect all contract methods
let mut contract_fns = submodules
.iter()
.flat_map(|x| x.1.module.submodules_recursive())
.flat_map(|x| x.1.module.contract_fns(engines))
.chain(all_nodes.iter().flat_map(|x| x.contract_fns(engines)))
.collect::<Vec<_>>();
// exclude all contract methods that are supertrait methods
let partialeq_ctx = PartialEqWithEnginesContext::new(engines);
contract_fns.retain(|method| {
contract_supertrait_fns
.iter()
.all(|si| !PartialEqWithEngines::eq(method, si, &partialeq_ctx))
});
let mut fn_generator = AbiEncodingAutoImplContext::new(&mut ctx);
if let Ok(node) = fn_generator.generate_contract_entry(
engines,
parsed.span.source_id(),
&contract_fns,
fallback_fn,
handler,
) {
all_nodes.push(node)
}
}
_ => {}
}
}
#[allow(clippy::arc_with_non_send_sync)]
let ty_module = Arc::new(Self {
span: span.clone(),
submodules,
all_nodes,
attributes: attributes.clone(),
});
// Cache the ty module
if let Some(source_id) = span.source_id() {
let path = engines.se().get_path(source_id);
let version = build_config
.and_then(|config| config.lsp_mode.as_ref())
.and_then(|lsp| lsp.file_versions.get(&path).copied())
.flatten();
let include_tests = build_config.is_some_and(|x| x.include_tests);
let key = ModuleCacheKey::new(path.clone().into(), include_tests);
engines.qe().update_typed_module_cache_entry(
&key,
TypedModuleInfo {
module: ty_module.clone(),
namespace_module: Arc::new(ctx.namespace().current_module().clone()),
version,
},
);
}
Ok(ty_module)
}
// Filter and gather impl items
fn get_all_impls(
ctx: TypeCheckContext<'_>,
nodes: &[AstNode],
predicate: fn(&ImplSelfOrTrait) -> bool,
) -> HashMap<BaseIdent, HashSet<CallPath>> {
let engines = ctx.engines();
let mut impls = HashMap::<BaseIdent, HashSet<CallPath>>::new();
for node in nodes.iter() {
if let AstNodeContent::Declaration(Declaration::ImplSelfOrTrait(decl_id)) =
&node.content
{
let decl = &*engines.pe().get_impl_self_or_trait(decl_id);
let implementing_for = ctx.engines.te().get(decl.implementing_for.type_id);
let implementing_for = match &*implementing_for {
TypeInfo::Struct(decl_id) => {
Some(ctx.engines().de().get(decl_id).name().clone())
}
TypeInfo::Enum(decl) => Some(ctx.engines().de().get(decl).name().clone()),
TypeInfo::Custom {
qualified_call_path,
..
} => Some(qualified_call_path.call_path.suffix.clone()),
_ => None,
};
if let Some(implementing_for) = implementing_for {
if predicate(decl) {
impls
.entry(implementing_for)
.or_default()
.insert(decl.trait_name.clone());
}
}
}
}
impls
}
fn type_check_nodes(
handler: &Handler,
mut ctx: TypeCheckContext,
nodes: &[AstNode],
) -> Result<Vec<ty::TyAstNode>, ErrorEmitted> {
let engines = ctx.engines();
// Check which structs and enums needs to have auto impl for `AbiEncode` and `AbiDecode`.
// We need to do this before type checking, because the impls must be right after
// the declarations.
let all_abi_encode_impls = Self::get_all_impls(ctx.by_ref(), nodes, |decl| {
decl.trait_name.suffix.as_str() == "AbiEncode"
});
let all_debug_impls = Self::get_all_impls(ctx.by_ref(), nodes, |decl| {
decl.trait_name.suffix.as_str() == "Debug"
});
let mut typed_nodes = vec![];
for node in nodes {
// Check if the encoding and debug traits are explicitly implemented.
let (auto_impl_encoding_traits, auto_impl_debug_traits) = match &node.content {
AstNodeContent::Declaration(Declaration::StructDeclaration(decl_id)) => {
let decl = ctx.engines().pe().get_struct(decl_id);
(
!all_abi_encode_impls.contains_key(&decl.name),
!all_debug_impls.contains_key(&decl.name),
)
}
AstNodeContent::Declaration(Declaration::EnumDeclaration(decl_id)) => {
let decl = ctx.engines().pe().get_enum(decl_id);
(
!all_abi_encode_impls.contains_key(&decl.name),
!all_debug_impls.contains_key(&decl.name),
)
}
_ => (false, false),
};
let Ok(node) = ty::TyAstNode::type_check(handler, ctx.by_ref(), node) else {
continue;
};
// Auto impl encoding traits only if they are not explicitly implemented.
let mut generated = vec![];
if ctx.experimental.new_encoding {
if let (true, mut ctx) = (
auto_impl_encoding_traits,
AbiEncodingAutoImplContext::new(&mut ctx),
) {
match &node.content {
TyAstNodeContent::Declaration(decl @ TyDecl::StructDecl(_))
| TyAstNodeContent::Declaration(decl @ TyDecl::EnumDecl(_)) => {
let (abi_encode_impl, abi_decode_impl) =
ctx.generate_abi_encode_and_decode_impls(engines, decl);
generated.extend(abi_encode_impl);
generated.extend(abi_decode_impl);
}
_ => {}
}
};
}
// Auto impl debug traits only if they are not explicitly implemented
if auto_impl_debug_traits {
match &node.content {
TyAstNodeContent::Declaration(decl @ TyDecl::StructDecl(_))
| TyAstNodeContent::Declaration(decl @ TyDecl::EnumDecl(_)) => {
let mut ctx = DebugAutoImplContext::new(&mut ctx);
let a = ctx.generate_debug_impl(engines, decl);
generated.extend(a);
}
_ => {}
}
}
// Always auto impl marker traits. If an explicit implementation exists, that will be
// reported as an error when type-checking trait impls.
let mut ctx = MarkerTraitsAutoImplContext::new(&mut ctx);
if let TyAstNodeContent::Declaration(TyDecl::EnumDecl(enum_decl)) = &node.content {
let enum_decl = &*ctx.engines().de().get(&enum_decl.decl_id);
let enum_marker_trait_impl =
ctx.generate_enum_marker_trait_impl(engines, enum_decl);
generated.extend(enum_marker_trait_impl);
if check_is_valid_error_type_enum(handler, enum_decl).is_ok_and(|res| res) {
let error_type_marker_trait_impl =
ctx.generate_error_type_marker_trait_impl_for_enum(engines, enum_decl);
generated.extend(error_type_marker_trait_impl);
}
}
typed_nodes.push(node);
typed_nodes.extend(generated);
}
Ok(typed_nodes)
}
}
/// Performs all semantic checks for `error_type` and `error` attributes, and returns true if the
/// `enum_decl` is a valid error type declaration.
fn check_is_valid_error_type_enum(
handler: &Handler,
enum_decl: &TyEnumDecl,
) -> Result<bool, ErrorEmitted> {
let has_error_type_attribute = enum_decl.attributes.has_error_type();
if has_error_type_attribute && enum_decl.variants.is_empty() {
handler.emit_warn(CompileWarning {
span: enum_decl.name().span(),
warning_content: Warning::ErrorTypeEmptyEnum {
enum_name: enum_decl.name().into(),
},
});
}
// We show warnings for error messages even if the error type enum
// is not well formed, e.g., if it doesn't have the `error_type` attribute.
let mut duplicated_error_messages = IndexMap::<&str, Vec<Span>>::new();
for (enum_variant_name, error_attr) in enum_decl.variants.iter().flat_map(|variant| {
variant
.attributes
.error()
.map(|error_attr| (&variant.name, error_attr))
}) {
error_attr.check_args_multiplicity(handler)?;
assert_eq!(
(1usize, 1usize),
(&error_attr.args_multiplicity()).into(),
"`#[error]` attribute must have argument multiplicity of exactly one"
);
let m_arg = &error_attr.args[0];
let error_msg = m_arg.get_string(handler, error_attr)?;
if error_msg.is_empty() {
handler.emit_warn(CompileWarning {
span: m_arg
.value
.as_ref()
.expect("`m` argument has a valid empty string value")
.span(),
warning_content: Warning::ErrorEmptyErrorMessage {
enum_name: enum_decl.name().clone(),
enum_variant_name: enum_variant_name.clone(),
},
});
} else {
// We ignore duplicated empty messages and for those show
// only the warning that the message is empty.
duplicated_error_messages
.entry(error_msg)
.or_default()
.push(
m_arg
.value
.as_ref()
.expect("`m` argument has a valid empty string value")
.span(),
);
}
}
// Emit duplicated messages warnings, if we actually have duplicates.
for duplicated_error_messages in duplicated_error_messages
.into_values()
.filter(|spans| spans.len() > 1)
{
let (last_occurrence, previous_occurrences) = duplicated_error_messages
.split_last()
.expect("`duplicated_error_messages` has more than one element");
handler.emit_warn(CompileWarning {
span: last_occurrence.clone(),
warning_content: Warning::ErrorDuplicatedErrorMessage {
last_occurrence: last_occurrence.clone(),
previous_occurrences: previous_occurrences.into(),
},
});
}
handler.scope(|handler| {
if has_error_type_attribute {
let non_error_variants = enum_decl
.variants
.iter()
.filter(|variant| !variant.attributes.has_error())
.collect_vec();
if !non_error_variants.is_empty() {
handler.emit_err(CompileError::ErrorTypeEnumHasNonErrorVariants {
enum_name: enum_decl.name().into(),
non_error_variants: non_error_variants
.iter()
.map(|variant| (&variant.name).into())
.collect(),
});
}
} else {
for variant in enum_decl
.variants
.iter()
.filter(|variant| variant.attributes.has_error())
{
handler.emit_err(CompileError::ErrorAttributeInNonErrorEnum {
enum_name: enum_decl.name().into(),
enum_variant_name: (&variant.name).into(),
});
}
}
Ok(())
})?;
Ok(has_error_type_attribute)
}
fn collect_fallback_fn(
all_nodes: &[ty::TyAstNode],
engines: &Engines,
handler: &Handler,
) -> Result<Option<DeclId<ty::TyFunctionDecl>>, ErrorEmitted> {
let mut fallback_fns = all_nodes
.iter()
.filter_map(|x| match &x.content {
ty::TyAstNodeContent::Declaration(ty::TyDecl::FunctionDecl(decl)) => {
let d = engines.de().get(&decl.decl_id);
d.is_fallback().then_some(decl.decl_id)
}
_ => None,
})
.collect::<Vec<_>>();
let mut last_error = None;
for f in fallback_fns.iter().skip(1) {
let decl = engines.de().get(f);
last_error = Some(
handler.emit_err(CompileError::MultipleDefinitionsOfFallbackFunction {
name: decl.name.clone(),
span: decl.span.clone(),
}),
);
}
if let Some(last_error) = last_error {
return Err(last_error);
}
if let Some(fallback_fn) = fallback_fns.pop() {
let f = engines.de().get(&fallback_fn);
if !f.parameters.is_empty() {
Err(
handler.emit_err(CompileError::FallbackFnsCannotHaveParameters {
span: f.span.clone(),
}),
)
} else {
Ok(Some(fallback_fn))
}
} else {
Ok(None)
}
}
impl ty::TySubmodule {
pub fn build_dep_graph(
_handler: &Handler,
module_dep_graph: &mut ModuleDepGraph,
mod_name: ModName,
submodule: &ParseSubmodule,
) -> Result<(), ErrorEmitted> {
let ParseSubmodule { module, .. } = submodule;
let sub_mod_node = module_dep_graph.get_node_id_for_module(&mod_name).unwrap();
for node in module.tree.root_nodes.iter() {
match &node.content {
AstNodeContent::UseStatement(use_stmt) => {
if let Some(use_mod_ident) = use_stmt.call_path.first() {
if let Some(mod_name_node) =
module_dep_graph.get_node_id_for_module(use_mod_ident)
{
// Prevent adding edge loops between the same node as that will throw off
// the cyclic dependency analysis.
if sub_mod_node != mod_name_node {
module_dep_graph.dep_graph.add_edge(
sub_mod_node,
mod_name_node,
ModuleDepGraphEdge {},
);
}
}
}
}
AstNodeContent::Declaration(_) => {}
AstNodeContent::Expression(_) => {}
AstNodeContent::IncludeStatement(_) => {}
AstNodeContent::Error(_, _) => {}
}
}
Ok(())
}
pub fn collect(
handler: &Handler,
engines: &Engines,
parent_ctx: &mut SymbolCollectionContext,
mod_name: ModName,
submodule: &ParseSubmodule,
) -> Result<(), ErrorEmitted> {
let ParseSubmodule {
module,
mod_name_span: _,
visibility,
} = submodule;
parent_ctx.enter_submodule(
handler,
engines,
mod_name,
*visibility,
module.span.clone(),
|submod_ctx| ty::TyModule::collect(handler, engines, submod_ctx, module),
)?
}
pub fn type_check(
handler: &Handler,
mut parent_ctx: TypeCheckContext,
engines: &Engines,
mod_name: ModName,
kind: TreeType,
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/symbol_collection_context.rs | sway-core/src/semantic_analysis/symbol_collection_context.rs | use crate::{
language::{parsed::Declaration, Visibility},
namespace::{LexicalScopeId, ModulePath, ResolvedDeclaration},
semantic_analysis::Namespace,
Engines,
};
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::{span::Span, Ident};
use super::{namespace::Items, ConstShadowingMode, GenericShadowingMode};
#[derive(Clone)]
/// Contextual state tracked and accumulated throughout symbol collecting.
pub struct SymbolCollectionContext {
/// The namespace context accumulated throughout symbol collecting.
pub(crate) namespace: Namespace,
/// Whether or not a const declaration shadows previous const declarations sequentially.
///
/// This is `Sequential` while checking const declarations in functions, otherwise `ItemStyle`.
const_shadowing_mode: ConstShadowingMode,
/// Whether or not a generic type parameters shadows previous generic type parameters.
///
/// This is `Disallow` everywhere except while checking type parameters bounds in struct instantiation.
generic_shadowing_mode: GenericShadowingMode,
}
impl SymbolCollectionContext {
/// Initialize a context at the top-level of a module with its namespace.
pub fn new(namespace: Namespace) -> Self {
Self {
namespace,
const_shadowing_mode: ConstShadowingMode::ItemStyle,
generic_shadowing_mode: GenericShadowingMode::Disallow,
}
}
/// Scope the `CollectionContext` with a new lexical scope.
pub fn scoped<T>(
&mut self,
engines: &Engines,
span: Span,
decl: Option<Declaration>,
with_scoped_ctx: impl FnOnce(&mut SymbolCollectionContext) -> Result<T, ErrorEmitted>,
) -> (Result<T, ErrorEmitted>, LexicalScopeId) {
let decl = decl.map(ResolvedDeclaration::Parsed);
let lexical_scope_id: LexicalScopeId =
self.namespace.current_module_mut().write(engines, |m| {
m.push_new_lexical_scope(span.clone(), decl.clone())
});
let ret = with_scoped_ctx(self);
self.namespace
.current_module_mut()
.write(engines, |m| m.pop_lexical_scope());
(ret, lexical_scope_id)
}
/// Enter the lexical scope corresponding to the given span and produce a
/// collection context ready for collecting its content.
///
/// Returns the result of the given `with_ctx` function.
pub fn enter_lexical_scope<T>(
&mut self,
handler: &Handler,
engines: &Engines,
span: Span,
with_ctx: impl FnOnce(&mut SymbolCollectionContext) -> Result<T, ErrorEmitted>,
) -> Result<T, ErrorEmitted> {
self.namespace
.current_module_mut()
.write(engines, |m| m.enter_lexical_scope(handler, span.clone()))?;
let ret = with_ctx(self);
self.namespace
.current_module_mut()
.write(engines, |m| m.pop_lexical_scope());
ret
}
/// Enter the submodule with the given name and produce a collection context ready for
/// collecting its content.
///
/// Returns the result of the given `with_submod_ctx` function.
pub fn enter_submodule<T>(
&mut self,
handler: &Handler,
engines: &Engines,
mod_name: Ident,
visibility: Visibility,
module_span: Span,
with_submod_ctx: impl FnOnce(&mut SymbolCollectionContext) -> T,
) -> Result<T, ErrorEmitted> {
self.namespace
.push_submodule(handler, engines, mod_name, visibility, module_span, true)?;
//let Self { namespace, .. } = self;
//let mut submod_ns = namespace.enter_submodule(mod_name, visibility, module_span);
let ret = with_submod_ctx(self);
self.namespace.pop_submodule();
Ok(ret)
}
/// Short-hand for calling [Items::insert_parsed_symbol].
pub(crate) fn insert_parsed_symbol(
&mut self,
handler: &Handler,
engines: &Engines,
name: Ident,
item: Declaration,
) -> Result<(), ErrorEmitted> {
self.namespace.current_module_mut().write(engines, |m| {
Items::insert_parsed_symbol(
handler,
engines,
m,
name.clone(),
item.clone(),
self.const_shadowing_mode,
self.generic_shadowing_mode,
)
})
}
/// Returns a mutable reference to the current namespace.
pub fn namespace_mut(&mut self) -> &mut Namespace {
&mut self.namespace
}
/// Returns a reference to the current namespace.
pub fn namespace(&self) -> &Namespace {
&self.namespace
}
/// Short-hand for performing a [Module::star_import] with `mod_path` as the destination.
pub(crate) fn star_import(
&mut self,
handler: &Handler,
engines: &Engines,
src: &ModulePath,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
self.namespace_mut()
.star_import_to_current_module(handler, engines, src, visibility)
}
/// Short-hand for performing a [Module::variant_star_import] with `mod_path` as the destination.
pub(crate) fn variant_star_import(
&mut self,
handler: &Handler,
engines: &Engines,
src: &ModulePath,
enum_name: &Ident,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
self.namespace_mut()
.variant_star_import_to_current_module(handler, engines, src, enum_name, visibility)
}
/// Short-hand for performing a [Module::self_import] with `mod_path` as the destination.
pub(crate) fn self_import(
&mut self,
handler: &Handler,
engines: &Engines,
src: &ModulePath,
alias: Option<Ident>,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
self.namespace_mut()
.self_import_to_current_module(handler, engines, src, alias, visibility)
}
/// Short-hand for performing a [Module::item_import] with `mod_path` as the destination.
pub(crate) fn item_import(
&mut self,
handler: &Handler,
engines: &Engines,
src: &ModulePath,
item: &Ident,
alias: Option<Ident>,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
self.namespace_mut()
.item_import_to_current_module(handler, engines, src, item, alias, visibility)
}
/// Short-hand for performing a [Module::variant_import] with `mod_path` as the destination.
#[allow(clippy::too_many_arguments)]
pub(crate) fn variant_import(
&mut self,
handler: &Handler,
engines: &Engines,
src: &ModulePath,
enum_name: &Ident,
variant_name: &Ident,
alias: Option<Ident>,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
self.namespace_mut().variant_import_to_current_module(
handler,
engines,
src,
enum_name,
variant_name,
alias,
visibility,
)
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/type_check_analysis.rs | sway-core/src/semantic_analysis/type_check_analysis.rs | //! This module handles the process of iterating through the typed AST and doing an analysis.
//! At the moment, we compute a dependency graph between typed nodes.
use std::collections::{HashMap, HashSet};
use std::fmt::Display;
use std::fs;
use petgraph::stable_graph::NodeIndex;
use petgraph::Graph;
use sway_error::error::CompileError;
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::Named;
use crate::decl_engine::{AssociatedItemDeclId, DeclId, DeclUniqueId};
use crate::engine_threading::DebugWithEngines;
use crate::language::ty::{self, TyFunctionDecl, TyTraitItem};
use crate::Engines;
use graph_cycles::Cycles;
pub type TyNodeDepGraphNodeId = petgraph::graph::NodeIndex;
#[derive(Clone, Debug)]
pub enum TyNodeDepGraphEdgeInfo {
FnApp,
}
#[derive(Clone, Debug)]
pub struct TyNodeDepGraphEdge(pub TyNodeDepGraphEdgeInfo);
impl Display for TyNodeDepGraphEdge {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
TyNodeDepGraphEdgeInfo::FnApp => write!(f, "fn app"),
}
}
}
#[derive(Clone, Debug)]
pub enum TyNodeDepGraphNode {
ImplTrait { node: ty::ImplSelfOrTrait },
ImplTraitItem { node: ty::TyTraitItem },
Fn { node: DeclId<TyFunctionDecl> },
}
// Represents an ordered graph between declaration id indexes.
pub type TyNodeDepGraph = petgraph::graph::DiGraph<TyNodeDepGraphNode, TyNodeDepGraphEdge>;
// A simple context that is used to pass context necessary for typed AST analysis.
pub struct TypeCheckAnalysisContext<'cx> {
pub(crate) engines: &'cx Engines,
pub(crate) dep_graph: TyNodeDepGraph,
pub(crate) nodes: HashMap<DeclUniqueId, TyNodeDepGraphNodeId>,
pub(crate) items_node_stack: Vec<TyNodeDepGraphNodeId>,
pub(crate) node_stack: Vec<TyNodeDepGraphNodeId>,
}
impl TypeCheckAnalysisContext<'_> {
pub fn add_node(&mut self, node: TyNodeDepGraphNode) -> TyNodeDepGraphNodeId {
self.dep_graph.add_node(node)
}
pub fn add_edge_from_current(&mut self, to: TyNodeDepGraphNodeId, edge: TyNodeDepGraphEdge) {
let from = *self.node_stack.last().unwrap();
if !self.dep_graph.contains_edge(from, to) {
self.dep_graph.add_edge(from, to, edge);
}
}
#[allow(clippy::map_entry)]
pub fn get_or_create_node_for_impl_item(&mut self, item: &TyTraitItem) -> TyNodeDepGraphNodeId {
let id = match item {
TyTraitItem::Fn(decl_ref) => decl_ref.id().unique_id(),
TyTraitItem::Constant(decl_ref) => decl_ref.id().unique_id(),
TyTraitItem::Type(decl_ref) => decl_ref.id().unique_id(),
};
if self.nodes.contains_key(&id) {
*self.nodes.get(&id).unwrap()
} else {
let item_node = self.add_node(TyNodeDepGraphNode::ImplTraitItem { node: item.clone() });
self.nodes.insert(id, item_node);
item_node
}
}
/// This functions either gets an existing node in the graph, or creates a new
/// node corresponding to the passed function declaration node.
/// The function will try to find a non-monomorphized declaration node id so that
/// future accesses always normalize to the same node id.
#[allow(clippy::map_entry)]
pub fn get_or_create_node_for_fn_decl(
&mut self,
fn_decl_id: &DeclId<TyFunctionDecl>,
) -> TyNodeDepGraphNodeId {
let parents = self
.engines
.de()
.find_all_parents(self.engines, fn_decl_id)
.into_iter()
.filter_map(|f| match f {
AssociatedItemDeclId::TraitFn(_) => None,
AssociatedItemDeclId::Function(fn_id) => Some(fn_id),
AssociatedItemDeclId::Constant(_) => None,
AssociatedItemDeclId::Type(_) => None,
})
.collect::<Vec<_>>();
let id = if !parents.is_empty() {
parents.first().unwrap().unique_id()
} else {
fn_decl_id.unique_id()
};
if self.nodes.contains_key(&id) {
*self.nodes.get(&id).unwrap()
} else {
let item_node = self.add_node(TyNodeDepGraphNode::Fn { node: *fn_decl_id });
self.nodes.insert(id, item_node);
item_node
}
}
/// This function will process an impl trait declaration, pushing graph nodes
/// corresponding to each item in the trait impl.
#[allow(clippy::map_entry)]
pub(crate) fn push_nodes_for_impl_trait(
&mut self,
impl_trait: &ty::ImplSelfOrTrait,
) -> TyNodeDepGraphNodeId {
if self.nodes.contains_key(&impl_trait.decl_id.unique_id()) {
*self.nodes.get(&impl_trait.decl_id.unique_id()).unwrap()
} else {
let node = self.add_node(TyNodeDepGraphNode::ImplTrait {
node: impl_trait.clone(),
});
self.nodes.insert(impl_trait.decl_id.unique_id(), node);
let decl_engine = self.engines.de();
let impl_trait = decl_engine.get_impl_self_or_trait(&impl_trait.decl_id);
for item in impl_trait.items.iter() {
let item_node = self.get_or_create_node_for_impl_item(item);
// Connect the item node to the impl trait node.
self.dep_graph.add_edge(
node,
item_node,
TyNodeDepGraphEdge(TyNodeDepGraphEdgeInfo::FnApp),
);
self.items_node_stack.push(item_node);
}
node
}
}
/// This function will return an option to the node that represents the
/// function being referenced by a function application.
/// It will look through all the parent nodes in the engine to deal with
/// monomorphized function references.
pub(crate) fn get_node_for_fn_decl(
&mut self,
fn_decl_id: &DeclId<TyFunctionDecl>,
) -> Option<TyNodeDepGraphNodeId> {
let parents = self
.engines
.de()
.find_all_parents(self.engines, fn_decl_id)
.into_iter()
.filter_map(|f| match f {
AssociatedItemDeclId::TraitFn(_) => None,
AssociatedItemDeclId::Function(fn_id) => Some(fn_id),
AssociatedItemDeclId::Constant(_) => None,
AssociatedItemDeclId::Type(_) => None,
})
.collect::<Vec<_>>();
let mut possible_nodes = vec![*fn_decl_id];
possible_nodes.append(&mut parents.clone());
for possible_node in possible_nodes.iter().rev() {
if let Some(found) = self.nodes.get(&possible_node.unique_id()) {
return Some(*found);
}
}
for index in self.items_node_stack.iter().rev() {
let node = self
.dep_graph
.node_weight(*index)
.expect("expecting valid node id");
let fn_decl_id = match node {
TyNodeDepGraphNode::ImplTrait { node: _ } => unreachable!(),
TyNodeDepGraphNode::ImplTraitItem {
node: TyTraitItem::Fn(item_fn_ref),
} => item_fn_ref.id(),
TyNodeDepGraphNode::Fn { node: fn_decl_id } => fn_decl_id,
_ => continue,
};
for possible_node in possible_nodes.iter() {
if possible_node.inner() == fn_decl_id.inner() {
return Some(*index);
}
}
}
// If no node has been found yet, create it.
let base_id = if !parents.is_empty() {
parents.first().unwrap()
} else {
fn_decl_id
};
let node = self.get_or_create_node_for_fn_decl(base_id);
Some(node)
}
/// Prints out GraphViz DOT format for the dependency graph.
#[allow(dead_code)]
pub(crate) fn visualize(&self, engines: &Engines, print_graph: Option<String>) {
if let Some(graph_path) = print_graph {
use petgraph::dot::{Config, Dot};
let string_graph = self.dep_graph.filter_map(
|_idx, node| Some(format!("{:?}", engines.help_out(node))),
|_idx, edge| Some(format!("{edge}")),
);
let output = format!(
"{:?}",
Dot::with_attr_getters(
&string_graph,
&[Config::NodeNoLabel, Config::EdgeNoLabel],
&|_, er| format!("label = {:?}", er.weight()),
&|_, nr| {
let _node = &self.dep_graph[nr.0];
let shape = "";
let url = "".to_string();
format!("{shape} label = {:?} {url}", nr.1)
},
)
);
if graph_path.is_empty() {
tracing::info!("{output}");
} else {
let result = fs::write(graph_path.clone(), output);
if let Some(error) = result.err() {
tracing::error!(
"There was an issue while outputting type check analysis graph to path {graph_path:?}\n{error}"
);
}
}
}
}
/// Performs recursive analysis by running the Johnson's algorithm to find all cycles
/// in the previously constructed dependency graph.
pub(crate) fn check_recursive_calls(&self, handler: &Handler) -> Result<(), ErrorEmitted> {
handler.scope(|handler| {
let cycles = self.dep_graph.cycles();
if cycles.is_empty() {
return Ok(());
}
for mut sub_cycles in cycles {
// Manipulate the cycles order to get the same ordering as the source code's lexical order.
sub_cycles.rotate_left(1);
if sub_cycles.len() == 1 {
let node = self.dep_graph.node_weight(sub_cycles[0]).unwrap();
let fn_decl_id = self.get_fn_decl_id_from_node(node);
let fn_decl = self.engines.de().get_function(&fn_decl_id);
handler.emit_err(CompileError::RecursiveCall {
fn_name: fn_decl.name.clone(),
span: fn_decl.span.clone(),
});
} else {
let node = self.dep_graph.node_weight(sub_cycles[0]).unwrap();
let mut call_chain = vec![];
for i in sub_cycles.into_iter().skip(1) {
let node = self.dep_graph.node_weight(i).unwrap();
let fn_decl_id = self.get_fn_decl_id_from_node(node);
let fn_decl = self.engines.de().get_function(&fn_decl_id);
call_chain.push(fn_decl.name.to_string());
}
let fn_decl_id = self.get_fn_decl_id_from_node(node);
let fn_decl = self.engines.de().get_function(&fn_decl_id);
handler.emit_err(CompileError::RecursiveCallChain {
fn_name: fn_decl.name.clone(),
call_chain: call_chain.join(" -> "),
span: fn_decl.span.clone(),
});
}
}
Ok(())
})
}
pub(crate) fn get_normalized_fn_node_id(
&self,
fn_decl_id: &DeclId<TyFunctionDecl>,
) -> DeclId<TyFunctionDecl> {
let parents = self
.engines
.de()
.find_all_parents(self.engines, fn_decl_id)
.into_iter()
.filter_map(|f| match f {
AssociatedItemDeclId::TraitFn(_) => None,
AssociatedItemDeclId::Function(fn_id) => Some(fn_id),
AssociatedItemDeclId::Constant(_) => None,
AssociatedItemDeclId::Type(_) => None,
})
.collect::<Vec<_>>();
if !parents.is_empty() {
self.get_normalized_fn_node_id(parents.first().unwrap())
} else {
*fn_decl_id
}
}
pub(crate) fn get_fn_decl_id_from_node(
&self,
node: &TyNodeDepGraphNode,
) -> DeclId<TyFunctionDecl> {
match node {
TyNodeDepGraphNode::ImplTrait { .. } => unreachable!(),
TyNodeDepGraphNode::ImplTraitItem { node } => match node {
TyTraitItem::Fn(node) => *node.id(),
TyTraitItem::Constant(_) => unreachable!(),
TyTraitItem::Type(_) => unreachable!(),
},
TyNodeDepGraphNode::Fn { node } => *node,
}
}
pub(crate) fn get_sub_graph(
&self,
node_index: NodeIndex,
) -> Graph<&TyNodeDepGraphNode, &TyNodeDepGraphEdge> {
let neighbors: Vec<_> = self
.dep_graph
.neighbors_directed(node_index, petgraph::Direction::Outgoing)
.collect();
let neighbors_set: HashSet<&NodeIndex> = HashSet::from_iter(neighbors.iter());
self.dep_graph.filter_map(
|node_index, node| {
if neighbors_set.contains(&node_index) {
Some(node)
} else {
None
}
},
|_edge_index, edge| Some(edge),
)
}
}
impl DebugWithEngines for TyNodeDepGraphNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>, engines: &Engines) -> std::fmt::Result {
let text = match self {
TyNodeDepGraphNode::ImplTraitItem { node } => {
let str = match node {
ty::TyTraitItem::Fn(node) => node.name().as_str(),
ty::TyTraitItem::Constant(node) => node.name().as_str(),
ty::TyTraitItem::Type(node) => node.name().as_str(),
};
format!("{str:?}")
}
TyNodeDepGraphNode::ImplTrait { node } => {
let decl = engines.de().get_impl_self_or_trait(&node.decl_id);
format!("{:?}", decl.name().as_str())
}
TyNodeDepGraphNode::Fn { node } => {
let fn_decl = engines.de().get_function(node);
format!("{:?}", fn_decl.name.as_str())
}
};
f.write_str(&text)
}
}
impl<'cx> TypeCheckAnalysisContext<'cx> {
pub fn new(engines: &'cx Engines) -> Self {
Self {
engines,
dep_graph: Default::default(),
nodes: Default::default(),
items_node_stack: Default::default(),
node_stack: Default::default(),
}
}
}
pub(crate) trait TypeCheckAnalysis {
fn type_check_analyze(
&self,
handler: &Handler,
ctx: &mut TypeCheckAnalysisContext,
) -> Result<(), ErrorEmitted>;
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/node_dependencies.rs | sway-core/src/semantic_analysis/node_dependencies.rs | use crate::{
ast_elements::type_argument::GenericTypeArgument,
decl_engine::ParsedDeclEngineGet,
language::{parsed::*, CallPath},
type_system::*,
Engines,
};
use hashbrown::{HashMap, HashSet};
use std::{
hash::{DefaultHasher, Hash, Hasher},
iter::FromIterator,
};
use sway_error::error::CompileError;
use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::integer_bits::IntegerBits;
use sway_types::Spanned;
use sway_types::{ident::Ident, span::Span};
// -------------------------------------------------------------------------------------------------
/// Take a list of nodes and reorder them so that they may be semantically analysed without any
/// dependencies breaking.
pub(crate) fn order_ast_nodes_by_dependency(
handler: &Handler,
engines: &Engines,
nodes: Vec<AstNode>,
) -> Result<Vec<AstNode>, ErrorEmitted> {
let decl_dependencies = DependencyMap::from_iter(
nodes
.iter()
.filter_map(|node| Dependencies::gather_from_decl_node(handler, engines, node)),
);
// Check here for recursive calls now that we have a nice map of the dependencies to help us.
let mut errors = find_recursive_decls(&decl_dependencies);
handler.scope(|handler| {
// Because we're pulling these errors out of a HashMap they'll probably be in a funny
// order. Here we'll sort them by span start.
errors.sort_by_key(|err| err.span().start());
for err in errors {
handler.emit_err(err);
}
Ok(())
})?;
// Reorder the parsed AstNodes based on dependency. Includes first, then uses, then
// reordered declarations, then anything else. To keep the list stable and simple we can
// use a basic insertion sort.
Ok(nodes
.into_iter()
.fold(Vec::<AstNode>::new(), |ordered, node| {
insert_into_ordered_nodes(handler, engines, &decl_dependencies, ordered, node)
}))
}
// -------------------------------------------------------------------------------------------------
// Recursion detection.
fn find_recursive_decls(decl_dependencies: &DependencyMap) -> Vec<CompileError> {
decl_dependencies
.iter()
.filter_map(|(dep_sym, _)| find_recursive_decl(decl_dependencies, dep_sym))
.collect()
}
fn find_recursive_decl(
decl_dependencies: &DependencyMap,
dep_sym: &DependentSymbol,
) -> Option<CompileError> {
match dep_sym {
DependentSymbol::Fn(_, _, Some(fn_span)) => {
let mut chain = Vec::new();
find_recursive_call_chain(decl_dependencies, dep_sym, fn_span, &mut chain)
}
DependentSymbol::Symbol(_, _) => {
let mut chain = Vec::new();
find_recursive_type_chain(decl_dependencies, dep_sym, &mut chain)
}
_otherwise => None,
}
}
fn find_recursive_call_chain(
decl_dependencies: &DependencyMap,
fn_sym: &DependentSymbol,
fn_span: &Span,
chain: &mut Vec<Ident>,
) -> Option<CompileError> {
if let DependentSymbol::Fn(_, fn_sym_ident, _) = fn_sym {
if chain.contains(fn_sym_ident) {
// We've found a recursive loop, but it's possible this function is not actually in the
// loop, but is instead just calling into the loop. Only if this function is at the
// start of the chain do we need to report it.
return if &chain[0] != fn_sym_ident {
None
} else {
Some(build_recursion_error(
fn_sym_ident.clone(),
fn_span.clone(),
&chain[1..],
))
};
}
decl_dependencies.get(fn_sym).and_then(|deps_set| {
chain.push(fn_sym_ident.clone());
let result = deps_set.deps.iter().find_map(|dep_sym| {
find_recursive_call_chain(decl_dependencies, dep_sym, fn_span, chain)
});
chain.pop();
result
})
} else {
None
}
}
fn find_recursive_type_chain(
decl_dependencies: &DependencyMap,
dep_sym: &DependentSymbol,
chain: &mut Vec<Ident>,
) -> Option<CompileError> {
if let DependentSymbol::Symbol(_, sym_ident) = dep_sym {
if chain.contains(sym_ident) {
// See above about it only being an error if we're referring back to the start.
return if &chain[0] != sym_ident {
None
} else {
Some(build_recursive_type_error(sym_ident.clone(), &chain[1..]))
};
}
decl_dependencies.get(dep_sym).and_then(|deps_set| {
chain.push(sym_ident.clone());
let result = deps_set
.deps
.iter()
.find_map(|dep_sym| find_recursive_type_chain(decl_dependencies, dep_sym, chain));
chain.pop();
result
})
} else {
None
}
}
fn build_recursion_error(fn_sym: Ident, span: Span, chain: &[Ident]) -> CompileError {
match chain.len() {
// An empty chain indicates immediate recursion.
0 => CompileError::RecursiveCall {
fn_name: fn_sym,
span,
},
// Chain entries indicate mutual recursion.
1 => CompileError::RecursiveCallChain {
fn_name: fn_sym,
call_chain: chain[0].as_str().to_string(),
span,
},
n => {
let mut msg = chain[0].as_str().to_string();
for ident in &chain[1..(n - 1)] {
msg.push_str(", ");
msg.push_str(ident.as_str());
}
msg.push_str(" and ");
msg.push_str(chain[n - 1].as_str());
CompileError::RecursiveCallChain {
fn_name: fn_sym,
call_chain: msg,
span,
}
}
}
}
fn build_recursive_type_error(name: Ident, chain: &[Ident]) -> CompileError {
let span = name.span();
match chain.len() {
// An empty chain indicates immediate recursion.
0 => CompileError::RecursiveType { name, span },
// Chain entries indicate mutual recursion.
1 => CompileError::RecursiveTypeChain {
name,
type_chain: chain[0].as_str().to_string(),
span,
},
n => {
let mut msg = chain[0].as_str().to_string();
for ident in &chain[1..(n - 1)] {
msg.push_str(", ");
msg.push_str(ident.as_str());
}
msg.push_str(" and ");
msg.push_str(chain[n - 1].as_str());
CompileError::RecursiveTypeChain {
name,
type_chain: msg,
span,
}
}
}
}
// -------------------------------------------------------------------------------------------------
// Dependency gathering.
#[derive(Default)]
struct MemoizedBuildHasher {}
impl std::hash::BuildHasher for MemoizedBuildHasher {
type Hasher = MemoizedHasher;
fn build_hasher(&self) -> Self::Hasher {
MemoizedHasher { last_u64: None }
}
}
// Only works with `write_u64`, because it returns the last "hashed" u64, as is.
struct MemoizedHasher {
last_u64: Option<u64>,
}
impl std::hash::Hasher for MemoizedHasher {
fn finish(&self) -> u64 {
*self.last_u64.as_ref().unwrap()
}
fn write(&mut self, _bytes: &[u8]) {
unimplemented!("Only works with write_u64");
}
fn write_u64(&mut self, i: u64) {
self.last_u64 = Some(i);
}
}
type DependencyMap = HashMap<DependentSymbol, Dependencies, MemoizedBuildHasher>;
type DependencySet = HashSet<DependentSymbol, MemoizedBuildHasher>;
fn insert_into_ordered_nodes(
handler: &Handler,
engines: &Engines,
decl_dependencies: &DependencyMap,
mut ordered_nodes: Vec<AstNode>,
node: AstNode,
) -> Vec<AstNode> {
for idx in 0..ordered_nodes.len() {
// If we find a node which depends on the new node, insert it in front.
if depends_on(
handler,
engines,
decl_dependencies,
&ordered_nodes[idx],
&node,
) {
ordered_nodes.insert(idx, node);
return ordered_nodes;
}
}
// Node wasn't inserted into list, append it now.
ordered_nodes.push(node);
ordered_nodes
}
// dependant: noun; thing depending on another thing.
// dependee: noun; thing which is depended upon by another thing.
//
// Does the dependant depend on the dependee?
fn depends_on(
handler: &Handler,
engines: &Engines,
decl_dependencies: &DependencyMap,
dependant_node: &AstNode,
dependee_node: &AstNode,
) -> bool {
match (&dependant_node.content, &dependee_node.content) {
// Include statements first.
(AstNodeContent::IncludeStatement(_), AstNodeContent::IncludeStatement(_)) => false,
(_, AstNodeContent::IncludeStatement(_)) => true,
// Use statements next.
(AstNodeContent::IncludeStatement(_), AstNodeContent::UseStatement(_)) => false,
(AstNodeContent::UseStatement(_), AstNodeContent::UseStatement(_)) => false,
(_, AstNodeContent::UseStatement(_)) => true,
// Then declarations, ordered using the dependencies list.
(AstNodeContent::IncludeStatement(_), AstNodeContent::Declaration(_)) => false,
(AstNodeContent::UseStatement(_), AstNodeContent::Declaration(_)) => false,
(AstNodeContent::Declaration(dependant), AstNodeContent::Declaration(dependee)) => {
match (
decl_name(handler, engines, dependant),
decl_name(handler, engines, dependee),
) {
(Some(dependant_name), Some(dependee_name)) => decl_dependencies
.get(&dependant_name)
.map(|deps_set| {
recursively_depends_on(&deps_set.deps, &dependee_name, decl_dependencies)
})
.unwrap_or(false),
_ => false,
}
}
(_, AstNodeContent::Declaration(_)) => true,
// Everything else we don't care.
_ => false,
}
}
// -------------------------------------------------------------------------------------------------
// Dependencies are just a collection of dependee symbols.
#[derive(Debug, Default)]
struct Dependencies {
deps: DependencySet,
}
impl Dependencies {
fn gather_from_decl_node(
handler: &Handler,
engines: &Engines,
node: &AstNode,
) -> Option<(DependentSymbol, Dependencies)> {
match &node.content {
AstNodeContent::Declaration(decl) => decl_name(handler, engines, decl).map(|name| {
(
name,
Dependencies {
deps: DependencySet::default(),
}
.gather_from_decl(engines, decl),
)
}),
_ => None,
}
}
fn gather_from_decl(self, engines: &Engines, decl: &Declaration) -> Self {
match decl {
Declaration::VariableDeclaration(decl_id) => {
let VariableDeclaration {
type_ascription,
body,
..
} = &*engines.pe().get_variable(decl_id);
self.gather_from_generic_type_argument(engines, type_ascription)
.gather_from_expr(engines, body)
}
Declaration::ConstantDeclaration(decl_id) => {
let decl = engines.pe().get_constant(decl_id);
self.gather_from_constant_decl(engines, &decl)
}
Declaration::ConfigurableDeclaration(decl_id) => {
let decl = engines.pe().get_configurable(decl_id);
self.gather_from_configurable_decl(engines, &decl)
}
Declaration::TraitTypeDeclaration(decl_id) => {
let decl = engines.pe().get_trait_type(decl_id);
self.gather_from_type_decl(engines, &decl)
}
Declaration::TraitFnDeclaration(decl_id) => {
let decl = engines.pe().get_trait_fn(decl_id);
self.gather_from_trait_fn_decl(engines, &decl)
}
Declaration::FunctionDeclaration(decl_id) => {
let fn_decl = engines.pe().get_function(decl_id);
self.gather_from_fn_decl(engines, &fn_decl)
}
Declaration::StructDeclaration(decl_id) => {
let StructDeclaration {
fields,
type_parameters,
..
} = &*engines.pe().get_struct(decl_id);
self.gather_from_iter(fields.iter(), |deps, field| {
deps.gather_from_generic_type_argument(engines, &field.type_argument)
})
.gather_from_type_parameters(type_parameters)
}
Declaration::EnumDeclaration(decl_id) => {
let EnumDeclaration {
variants,
type_parameters,
..
} = &*engines.pe().get_enum(decl_id);
self.gather_from_iter(variants.iter(), |deps, variant| {
deps.gather_from_generic_type_argument(engines, &variant.type_argument)
})
.gather_from_type_parameters(type_parameters)
}
Declaration::EnumVariantDeclaration(_decl) => unreachable!(),
Declaration::TraitDeclaration(decl_id) => {
let trait_decl = engines.pe().get_trait(decl_id);
self.gather_from_iter(trait_decl.supertraits.iter(), |deps, sup| {
deps.gather_from_call_path(&sup.name, false, false)
})
.gather_from_iter(
trait_decl.interface_surface.iter(),
|deps, item| match item {
TraitItem::TraitFn(decl_id) => {
let sig = engines.pe().get_trait_fn(decl_id);
deps.gather_from_iter(sig.parameters.iter(), |deps, param| {
deps.gather_from_generic_type_argument(
engines,
¶m.type_argument,
)
})
.gather_from_generic_type_argument(engines, &sig.return_type)
}
TraitItem::Constant(decl_id) => {
let const_decl = engines.pe().get_constant(decl_id);
deps.gather_from_constant_decl(engines, &const_decl)
}
TraitItem::Type(decl_id) => {
let type_decl = engines.pe().get_trait_type(decl_id);
deps.gather_from_type_decl(engines, &type_decl)
}
TraitItem::Error(_, _) => deps,
},
)
.gather_from_iter(
trait_decl.methods.iter(),
|deps, fn_decl_id| {
let fn_decl = engines.pe().get_function(fn_decl_id);
deps.gather_from_fn_decl(engines, &fn_decl)
},
)
}
Declaration::ImplSelfOrTrait(decl_id) => {
let ImplSelfOrTrait {
impl_type_parameters,
trait_name,
implementing_for,
items,
..
} = &*engines.pe().get_impl_self_or_trait(decl_id);
self.gather_from_call_path(trait_name, false, false)
.gather_from_generic_type_argument(engines, implementing_for)
.gather_from_type_parameters(impl_type_parameters)
.gather_from_iter(items.iter(), |deps, item| match item {
ImplItem::Fn(fn_decl_id) => {
let fn_decl = engines.pe().get_function(fn_decl_id);
deps.gather_from_fn_decl(engines, &fn_decl)
}
ImplItem::Constant(decl_id) => {
let const_decl = engines.pe().get_constant(decl_id);
deps.gather_from_constant_decl(engines, &const_decl)
}
ImplItem::Type(decl_id) => {
let type_decl = engines.pe().get_trait_type(decl_id);
deps.gather_from_type_decl(engines, &type_decl)
}
})
}
Declaration::AbiDeclaration(decl_id) => {
let AbiDeclaration {
interface_surface,
methods,
supertraits,
..
} = &*engines.pe().get_abi(decl_id);
self.gather_from_iter(supertraits.iter(), |deps, sup| {
deps.gather_from_call_path(&sup.name, false, false)
})
.gather_from_iter(interface_surface.iter(), |deps, item| match item {
TraitItem::TraitFn(decl_id) => {
let sig = engines.pe().get_trait_fn(decl_id);
deps.gather_from_iter(sig.parameters.iter(), |deps, param| {
deps.gather_from_generic_type_argument(engines, ¶m.type_argument)
})
.gather_from_generic_type_argument(engines, &sig.return_type)
}
TraitItem::Constant(decl_id) => {
let const_decl = engines.pe().get_constant(decl_id);
deps.gather_from_constant_decl(engines, &const_decl)
}
TraitItem::Type(decl_id) => {
let type_decl = engines.pe().get_trait_type(decl_id);
deps.gather_from_type_decl(engines, &type_decl)
}
TraitItem::Error(_, _) => deps,
})
.gather_from_iter(methods.iter(), |deps, fn_decl_id| {
let fn_decl = engines.pe().get_function(fn_decl_id);
deps.gather_from_fn_decl(engines, &fn_decl)
})
}
Declaration::StorageDeclaration(decl_id) => {
let StorageDeclaration { entries, .. } = &*engines.pe().get_storage(decl_id);
self.gather_from_iter(entries.iter(), |deps, entry| {
deps.gather_from_storage_entry(engines, entry)
})
}
Declaration::TypeAliasDeclaration(decl_id) => {
let TypeAliasDeclaration { ty, .. } = &*engines.pe().get_type_alias(decl_id);
self.gather_from_generic_type_argument(engines, ty)
}
Declaration::ConstGenericDeclaration(_) => Dependencies::default(),
}
}
fn gather_from_storage_entry(self, engines: &Engines, entry: &StorageEntry) -> Self {
match entry {
StorageEntry::Namespace(namespace) => self
.gather_from_iter(namespace.entries.iter(), |deps, entry| {
deps.gather_from_storage_entry(engines, entry)
}),
StorageEntry::Field(field) => {
self.gather_from_generic_type_argument(engines, &field.type_argument)
}
}
}
fn gather_from_constant_decl(
self,
engines: &Engines,
const_decl: &ConstantDeclaration,
) -> Self {
let ConstantDeclaration {
type_ascription,
value,
..
} = const_decl;
match value {
Some(value) => self
.gather_from_generic_type_argument(engines, type_ascription)
.gather_from_expr(engines, value),
None => self,
}
}
fn gather_from_configurable_decl(
self,
engines: &Engines,
const_decl: &ConfigurableDeclaration,
) -> Self {
let ConfigurableDeclaration {
type_ascription,
value,
..
} = const_decl;
match value {
Some(value) => self
.gather_from_generic_type_argument(engines, type_ascription)
.gather_from_expr(engines, value),
None => self,
}
}
fn gather_from_type_decl(self, engines: &Engines, type_decl: &TraitTypeDeclaration) -> Self {
let TraitTypeDeclaration { ty_opt, .. } = type_decl;
match ty_opt {
Some(value) => self.gather_from_generic_argument(engines, value),
None => self,
}
}
fn gather_from_trait_fn_decl(self, engines: &Engines, fn_decl: &TraitFn) -> Self {
let TraitFn {
parameters,
return_type,
..
} = fn_decl;
self.gather_from_iter(parameters.iter(), |deps, param| {
deps.gather_from_generic_type_argument(engines, ¶m.type_argument)
})
.gather_from_generic_type_argument(engines, return_type)
}
fn gather_from_fn_decl(self, engines: &Engines, fn_decl: &FunctionDeclaration) -> Self {
let FunctionDeclaration {
parameters,
return_type,
body,
type_parameters,
..
} = fn_decl;
self.gather_from_iter(parameters.iter(), |deps, param| {
deps.gather_from_generic_type_argument(engines, ¶m.type_argument)
})
.gather_from_generic_type_argument(engines, return_type)
.gather_from_block(engines, body)
.gather_from_type_parameters(type_parameters)
}
fn gather_from_expr(self, engines: &Engines, expr: &Expression) -> Self {
match &expr.kind {
ExpressionKind::Variable(name) => {
// in the case of ABI variables, we actually want to check if the ABI needs to be
// ordered
self.gather_from_call_path(&(name.clone()).into(), false, false)
}
ExpressionKind::AmbiguousVariableExpression(name) => {
self.gather_from_call_path(&(name.clone()).into(), false, false)
}
ExpressionKind::FunctionApplication(function_application_expression) => {
let FunctionApplicationExpression {
call_path_binding,
resolved_call_path_binding: _,
arguments,
} = &**function_application_expression;
self.gather_from_call_path(&call_path_binding.inner, false, true)
.gather_from_type_arguments(engines, &call_path_binding.type_arguments.to_vec())
.gather_from_iter(arguments.iter(), |deps, arg| {
deps.gather_from_expr(engines, arg)
})
}
ExpressionKind::LazyOperator(LazyOperatorExpression { lhs, rhs, .. }) => self
.gather_from_expr(engines, lhs)
.gather_from_expr(engines, rhs),
ExpressionKind::If(IfExpression {
condition,
then,
r#else,
..
}) => if let Some(else_expr) = r#else {
self.gather_from_expr(engines, else_expr)
} else {
self
}
.gather_from_expr(engines, condition)
.gather_from_expr(engines, then),
ExpressionKind::Match(MatchExpression {
value, branches, ..
}) => self
.gather_from_expr(engines, value)
.gather_from_iter(branches.iter(), |deps, branch| {
deps.gather_from_match_branch(engines, branch)
}),
ExpressionKind::CodeBlock(contents) => self.gather_from_block(engines, contents),
ExpressionKind::Array(ArrayExpression::Explicit { contents, .. }) => self
.gather_from_iter(contents.iter(), |deps, expr| {
deps.gather_from_expr(engines, expr)
}),
ExpressionKind::Array(ArrayExpression::Repeat { value, length }) => self
.gather_from_expr(engines, value)
.gather_from_expr(engines, length),
ExpressionKind::ArrayIndex(ArrayIndexExpression { prefix, index, .. }) => self
.gather_from_expr(engines, prefix)
.gather_from_expr(engines, index),
ExpressionKind::Struct(struct_expression) => {
let StructExpression {
call_path_binding,
resolved_call_path_binding: _,
fields,
} = &**struct_expression;
self.gather_from_call_path(&call_path_binding.inner, false, false)
.gather_from_type_arguments(engines, &call_path_binding.type_arguments.to_vec())
.gather_from_iter(fields.iter(), |deps, field| {
deps.gather_from_expr(engines, &field.value)
})
}
ExpressionKind::Subfield(SubfieldExpression { prefix, .. }) => {
self.gather_from_expr(engines, prefix)
}
ExpressionKind::AmbiguousPathExpression(e) => {
let AmbiguousPathExpression {
call_path_binding,
args,
qualified_path_root: _,
} = &**e;
let mut this = self;
if call_path_binding.inner.prefixes.is_empty() {
if let Some(before) = &call_path_binding.inner.suffix.before {
// We have just `Foo::Bar`, and nothing before `Foo`,
// so this could be referring to `Enum::Variant`,
// so we want to depend on `Enum` but not `Variant`.
this.deps
.insert(DependentSymbol::new_symbol(before.inner.clone()));
} else {
// We have just `Foo`, and nothing before `Foo`,
// so this is could either an enum variant or a function application
// so we want to depend on it as a function
this.deps.insert(DependentSymbol::new_fn(
call_path_binding.inner.suffix.suffix.clone(),
None,
));
}
}
this.gather_from_type_arguments(engines, &call_path_binding.type_arguments.to_vec())
.gather_from_iter(args.iter(), |deps, arg| deps.gather_from_expr(engines, arg))
}
ExpressionKind::DelineatedPath(delineated_path_expression) => {
let DelineatedPathExpression {
call_path_binding,
args,
} = &**delineated_path_expression;
// It's either a module path which we can ignore, or an enum variant path, in which
// case we're interested in the enum name and initialiser args, ignoring the
// variant name.
let args_vec = args.clone().unwrap_or_default();
self.gather_from_call_path(&call_path_binding.inner.call_path, true, false)
.gather_from_type_arguments(engines, &call_path_binding.type_arguments.to_vec())
.gather_from_iter(args_vec.iter(), |deps, arg| {
deps.gather_from_expr(engines, arg)
})
}
ExpressionKind::MethodApplication(method_application_expression) => self
.gather_from_iter(
method_application_expression.arguments.iter(),
|deps, arg| deps.gather_from_expr(engines, arg),
),
ExpressionKind::Asm(asm) => self
.gather_from_iter(asm.registers.iter(), |deps, register| {
deps.gather_from_opt_expr(engines, register.initializer.as_ref())
})
.gather_from_typeinfo(engines, &asm.return_type),
// we should do address someday, but due to the whole `re_parse_expression` thing
// it isn't possible right now
ExpressionKind::AbiCast(abi_cast_expression) => {
self.gather_from_call_path(&abi_cast_expression.abi_name, false, false)
}
ExpressionKind::Literal(_)
| ExpressionKind::Break
| ExpressionKind::Continue
| ExpressionKind::StorageAccess(_)
| ExpressionKind::Error(_, _) => self,
ExpressionKind::Tuple(fields) => self.gather_from_iter(fields.iter(), |deps, field| {
deps.gather_from_expr(engines, field)
}),
ExpressionKind::TupleIndex(TupleIndexExpression { prefix, .. }) => {
self.gather_from_expr(engines, prefix)
}
ExpressionKind::IntrinsicFunction(IntrinsicFunctionExpression {
arguments, ..
}) => self.gather_from_iter(arguments.iter(), |deps, arg| {
deps.gather_from_expr(engines, arg)
}),
ExpressionKind::WhileLoop(WhileLoopExpression {
condition, body, ..
}) => self
.gather_from_expr(engines, condition)
.gather_from_block(engines, body),
ExpressionKind::ForLoop(ForLoopExpression { desugared, .. }) => {
self.gather_from_expr(engines, desugared)
}
ExpressionKind::Reassignment(reassignment) => {
self.gather_from_expr(engines, &reassignment.rhs)
}
ExpressionKind::ImplicitReturn(expr) | ExpressionKind::Return(expr) => {
self.gather_from_expr(engines, expr)
}
ExpressionKind::Panic(expr) => self.gather_from_expr(engines, expr),
ExpressionKind::Ref(RefExpression { value: expr, .. })
| ExpressionKind::Deref(expr) => self.gather_from_expr(engines, expr),
}
}
fn gather_from_match_branch(self, engines: &Engines, branch: &MatchBranch) -> Self {
let MatchBranch {
scrutinee, result, ..
} = branch;
self.gather_from_iter(
scrutinee.gather_approximate_typeinfo_dependencies().iter(),
|deps, type_info| deps.gather_from_typeinfo(engines, type_info),
)
.gather_from_expr(engines, result)
}
fn gather_from_opt_expr(self, engines: &Engines, opt_expr: Option<&Expression>) -> Self {
match opt_expr {
None => self,
Some(expr) => self.gather_from_expr(engines, expr),
}
}
fn gather_from_block(self, engines: &Engines, block: &CodeBlock) -> Self {
self.gather_from_iter(block.contents.iter(), |deps, node| {
deps.gather_from_node(engines, node)
})
}
fn gather_from_node(self, engines: &Engines, node: &AstNode) -> Self {
match &node.content {
AstNodeContent::Expression(expr) => self.gather_from_expr(engines, expr),
AstNodeContent::Declaration(decl) => self.gather_from_decl(engines, decl),
// No deps from these guys.
AstNodeContent::UseStatement(_)
| AstNodeContent::IncludeStatement(_)
| AstNodeContent::Error(_, _) => self,
}
}
fn gather_from_call_path(
mut self,
call_path: &CallPath,
use_prefix: bool,
is_fn_app: bool,
) -> Self {
if call_path.prefixes.is_empty() {
// We can just use the suffix.
self.deps.insert(if is_fn_app {
DependentSymbol::new_fn(call_path.suffix.clone(), None)
} else {
DependentSymbol::new_symbol(call_path.suffix.clone())
});
} else if use_prefix && call_path.prefixes.len() == 1 {
// Here we can use the prefix (e.g., for 'Enum::Variant' -> 'Enum') as long is it's
// only a single element.
self.deps
.insert(DependentSymbol::new_symbol(call_path.prefixes[0].clone()));
}
self
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/type_resolve.rs | sway-core/src/semantic_analysis/type_resolve.rs | use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::{Ident, Span, Spanned};
use crate::{
ast_elements::type_parameter::{ConstGenericExpr, ConstGenericExprTyDecl},
language::{
ty::{self, TyDecl, TyTraitItem},
CallPath, CallPathType, QualifiedCallPath,
},
monomorphization::type_decl_opt_to_type_id,
namespace::{Module, ModulePath, ResolvedDeclaration, ResolvedTraitImplItem},
type_system::SubstTypes,
EnforceTypeArguments, Engines, Length, Namespace, SubstTypesContext, TypeId, TypeInfo,
};
use super::namespace::TraitMap;
/// Specifies if visibility checks should be performed as part of name resolution.
#[derive(Clone, Copy, PartialEq)]
pub enum VisibilityCheck {
Yes,
No,
}
fn resolve_length(
length: &Length,
handler: &Handler,
engines: &Engines,
namespace: &Namespace,
mod_path: &ModulePath,
self_type: Option<TypeId>,
) -> Result<Length, ErrorEmitted> {
match length.expr() {
ConstGenericExpr::Literal { val, span } => Ok(Length(ConstGenericExpr::Literal {
val: *val,
span: span.clone(),
})),
ConstGenericExpr::AmbiguousVariableExpression { ident, decl } => {
if decl.is_some() {
return Ok(length.clone());
}
let resolved_decl = resolve_call_path(
handler,
engines,
namespace,
mod_path,
&CallPath {
prefixes: vec![],
suffix: ident.clone(),
callpath_type: CallPathType::Ambiguous,
},
self_type,
VisibilityCheck::No,
)
.map(|d| d.expect_typed())?;
let decl = match resolved_decl {
TyDecl::ConstGenericDecl(decl) => ConstGenericExprTyDecl::ConstGenericDecl(decl),
TyDecl::ConstantDecl(decl) => ConstGenericExprTyDecl::ConstantDecl(decl),
_ => unreachable!(),
};
Ok(Length(ConstGenericExpr::AmbiguousVariableExpression {
ident: ident.clone(),
decl: Some(decl),
}))
}
}
}
/// Resolve the type of the given [TypeId], replacing any instances of
/// [TypeInfo::Custom] with either a monomorphized struct, monomorphized
/// enum, or a reference to a type parameter.
#[allow(clippy::too_many_arguments)]
pub fn resolve_type(
handler: &Handler,
engines: &Engines,
namespace: &Namespace,
mod_path: &ModulePath,
type_id: TypeId,
span: &Span,
enforce_type_arguments: EnforceTypeArguments,
type_info_prefix: Option<&ModulePath>,
self_type: Option<TypeId>,
subst_ctx: &SubstTypesContext,
check_visibility: VisibilityCheck,
) -> Result<TypeId, ErrorEmitted> {
let type_engine = engines.te();
let module_path = type_info_prefix.unwrap_or(mod_path);
let type_id = match type_engine.get(type_id).as_ref() {
TypeInfo::Custom {
qualified_call_path,
type_arguments,
} => {
let type_decl_opt = resolve_qualified_call_path(
handler,
engines,
namespace,
module_path,
qualified_call_path,
self_type,
subst_ctx,
check_visibility,
)
.ok();
type_decl_opt_to_type_id(
handler,
engines,
namespace,
type_decl_opt,
&qualified_call_path.call_path,
span,
enforce_type_arguments,
mod_path,
type_arguments.clone(),
self_type,
subst_ctx,
)?
}
TypeInfo::Array(elem_ty, length) => {
let mut elem_ty = elem_ty.clone();
elem_ty.type_id = resolve_type(
handler,
engines,
namespace,
mod_path,
elem_ty.type_id,
span,
enforce_type_arguments,
None,
self_type,
subst_ctx,
check_visibility,
)
.unwrap_or_else(|err| engines.te().id_of_error_recovery(err));
let length = resolve_length(length, handler, engines, namespace, mod_path, self_type)?;
engines.te().insert_array(engines, elem_ty, length.clone())
}
TypeInfo::Slice(elem_ty) => {
let mut elem_ty = elem_ty.clone();
elem_ty.type_id = resolve_type(
handler,
engines,
namespace,
mod_path,
elem_ty.type_id,
span,
enforce_type_arguments,
None,
self_type,
subst_ctx,
check_visibility,
)
.unwrap_or_else(|err| engines.te().id_of_error_recovery(err));
engines.te().insert_slice(engines, elem_ty)
}
TypeInfo::Tuple(type_arguments) => {
let mut type_arguments = type_arguments.clone();
for type_argument in type_arguments.iter_mut() {
type_argument.type_id = resolve_type(
handler,
engines,
namespace,
mod_path,
type_argument.type_id,
span,
enforce_type_arguments,
None,
self_type,
subst_ctx,
check_visibility,
)
.unwrap_or_else(|err| engines.te().id_of_error_recovery(err));
}
engines.te().insert_tuple(engines, type_arguments)
}
TypeInfo::TraitType {
name,
implemented_in,
} => {
let trait_item_ref = TraitMap::get_trait_item_for_type(
namespace.current_package_root_module(),
handler,
engines,
name,
*implemented_in,
None,
)?;
if let ResolvedTraitImplItem::Typed(TyTraitItem::Type(type_ref)) = trait_item_ref {
let type_decl = engines.de().get_type(type_ref.id());
if let Some(ty) = &type_decl.ty {
ty.type_id()
} else {
type_id
}
} else {
return Err(handler.emit_err(CompileError::Internal(
"Expecting associated type",
trait_item_ref.span(engines),
)));
}
}
TypeInfo::Ref {
referenced_type,
to_mutable_value,
} => {
let mut ty = referenced_type.clone();
ty.type_id = resolve_type(
handler,
engines,
namespace,
mod_path,
ty.type_id,
span,
enforce_type_arguments,
None,
self_type,
subst_ctx,
check_visibility,
)
.unwrap_or_else(|err| engines.te().id_of_error_recovery(err));
engines.te().insert_ref(engines, *to_mutable_value, ty)
}
TypeInfo::StringArray(length) => {
let length = resolve_length(length, handler, engines, namespace, mod_path, self_type)?;
engines.te().insert_string_array(engines, length)
}
_ => type_id,
};
let mut type_id = type_id;
type_id.subst(subst_ctx);
Ok(type_id)
}
#[allow(clippy::too_many_arguments)]
pub fn resolve_qualified_call_path(
handler: &Handler,
engines: &Engines,
namespace: &Namespace,
mod_path: &ModulePath,
qualified_call_path: &QualifiedCallPath,
self_type: Option<TypeId>,
subst_ctx: &SubstTypesContext,
check_visibility: VisibilityCheck,
) -> Result<ResolvedDeclaration, ErrorEmitted> {
let type_engine = engines.te();
if let Some(qualified_path_root) = qualified_call_path.clone().qualified_path_root {
let root_type_id = match &&*type_engine.get(qualified_path_root.ty.type_id()) {
TypeInfo::Custom {
qualified_call_path,
type_arguments,
..
} => {
let type_decl = resolve_call_path(
handler,
engines,
namespace,
mod_path,
&qualified_call_path.clone().to_call_path(handler)?,
self_type,
check_visibility,
)?;
type_decl_opt_to_type_id(
handler,
engines,
namespace,
Some(type_decl),
&qualified_call_path.call_path,
&qualified_path_root.ty.span(),
EnforceTypeArguments::No,
mod_path,
type_arguments.clone(),
self_type,
subst_ctx,
)?
}
_ => qualified_path_root.ty.type_id(),
};
let as_trait_opt = match &&*type_engine.get(qualified_path_root.as_trait) {
TypeInfo::Custom {
qualified_call_path: call_path,
..
} => Some(
call_path
.clone()
.to_call_path(handler)?
.to_canonical_path(engines, namespace),
),
_ => None,
};
resolve_call_path_and_root_type_id(
handler,
engines,
namespace.current_package_root_module(),
root_type_id,
as_trait_opt,
&qualified_call_path.call_path,
self_type,
)
.map(|(d, _)| d)
} else {
resolve_call_path(
handler,
engines,
namespace,
mod_path,
&qualified_call_path.call_path,
self_type,
check_visibility,
)
}
}
/// Resolve a symbol that is potentially prefixed with some path, e.g. `foo::bar::symbol`.
///
/// This will concatenate the `mod_path` with the `call_path`'s prefixes and
/// then calling `resolve_symbol` with the resulting path and call_path's suffix.
///
/// The `mod_path` is significant here as we assume the resolution is done within the
/// context of the module pointed to by `mod_path` and will only check the call path prefixes
/// and the symbol's own visibility.
pub fn resolve_call_path(
handler: &Handler,
engines: &Engines,
namespace: &Namespace,
mod_path: &ModulePath,
call_path: &CallPath,
self_type: Option<TypeId>,
check_visibility: VisibilityCheck,
) -> Result<ResolvedDeclaration, ErrorEmitted> {
let full_path = call_path.to_fullpath_from_mod_path(engines, namespace, &mod_path.to_vec());
let (decl, is_self_type, decl_mod_path) = resolve_symbol_and_mod_path(
handler,
engines,
namespace,
&full_path.prefixes,
&full_path.suffix,
self_type,
)?;
if check_visibility == VisibilityCheck::No {
return Ok(decl);
}
// Check that the modules in full_path are visible from the current module.
let _ = namespace.check_module_visibility(handler, &full_path.prefixes);
// If the full path is different from the declaration path, then we are accessing a reexport,
// which is by definition public.
if decl_mod_path != full_path.prefixes {
return Ok(decl);
}
// All declarations in the current module are visible, regardless of their visibility modifier.
if decl_mod_path == *namespace.current_mod_path() {
return Ok(decl);
}
// Otherwise, check the visibility modifier
if !decl.visibility(engines).is_public() && is_self_type == IsSelfType::No {
handler.emit_err(CompileError::ImportPrivateSymbol {
name: call_path.suffix.clone(),
span: call_path.suffix.span(),
});
}
Ok(decl)
}
// Resolve a path. The first identifier in the path is the package name, which may be the
// current package or an external one.
pub(super) fn resolve_symbol_and_mod_path(
handler: &Handler,
engines: &Engines,
namespace: &Namespace,
mod_path: &ModulePath,
symbol: &Ident,
self_type: Option<TypeId>,
) -> Result<(ResolvedDeclaration, IsSelfType, Vec<Ident>), ErrorEmitted> {
assert!(!mod_path.is_empty());
if mod_path[0] == *namespace.current_package_name() {
resolve_symbol_and_mod_path_inner(
handler,
engines,
namespace.current_package_root_module(),
mod_path,
symbol,
self_type,
)
} else {
match namespace.get_external_package(mod_path[0].as_str()) {
Some(ext_package) => {
// The path must be resolved in an external package.
// The root module in that package may have a different name than the name we
// use to refer to the package, so replace it.
let mut new_mod_path = vec![ext_package.name().clone()];
for id in mod_path.iter().skip(1) {
new_mod_path.push(id.clone());
}
resolve_symbol_and_mod_path_inner(
handler,
engines,
ext_package.root_module(),
&new_mod_path,
symbol,
self_type,
)
}
None => Err(handler.emit_err(crate::namespace::module_not_found(
mod_path,
mod_path[0] == *namespace.current_package_name(),
))),
}
}
}
fn resolve_symbol_and_mod_path_inner(
handler: &Handler,
engines: &Engines,
root_module: &Module,
mod_path: &ModulePath,
symbol: &Ident,
self_type: Option<TypeId>,
) -> Result<(ResolvedDeclaration, IsSelfType, Vec<Ident>), ErrorEmitted> {
assert!(!mod_path.is_empty());
assert!(root_module.mod_path().len() == 1);
assert!(mod_path[0] == root_module.mod_path()[0]);
// This block tries to resolve associated types
let mut current_module = root_module;
let mut current_mod_path = vec![mod_path[0].clone()];
let mut decl_opt = None;
let mut is_self_type = IsSelfType::No;
for ident in mod_path.iter().skip(1) {
if let Some(decl) = decl_opt {
let (decl, ret_is_self_type) = resolve_associated_type_or_item(
handler,
engines,
current_module,
ident,
decl,
None,
self_type,
)?;
decl_opt = Some(decl);
if ret_is_self_type == IsSelfType::Yes {
is_self_type = IsSelfType::Yes;
}
} else {
match current_module.submodule(std::slice::from_ref(ident)) {
Some(ns) => {
current_module = ns;
current_mod_path.push(ident.clone());
}
None => {
if ident.as_str() == "Self" {
is_self_type = IsSelfType::Yes;
}
let (decl, _) = current_module.resolve_symbol(handler, engines, ident)?;
decl_opt = Some(decl);
}
}
}
}
if let Some(decl) = decl_opt {
let (decl, ret_is_self_type) = resolve_associated_type_or_item(
handler,
engines,
current_module,
symbol,
decl,
None,
self_type,
)?;
if ret_is_self_type == IsSelfType::Yes {
is_self_type = IsSelfType::Yes;
}
return Ok((decl, is_self_type, current_mod_path));
}
if mod_path.len() == 1 {
let (decl, decl_path) = root_module.resolve_symbol(handler, engines, symbol)?;
Ok((decl, is_self_type, decl_path))
} else {
root_module
.lookup_submodule(handler, &mod_path[1..])
.and_then(|module| {
let (decl, decl_path) = module.resolve_symbol(handler, engines, symbol)?;
Ok((decl, is_self_type, decl_path))
})
}
}
fn decl_to_type_info(
handler: &Handler,
engines: &Engines,
symbol: &Ident,
decl: ResolvedDeclaration,
) -> Result<TypeInfo, ErrorEmitted> {
match decl {
ResolvedDeclaration::Parsed(_decl) => todo!(),
ResolvedDeclaration::Typed(decl) => Ok(match decl.clone() {
ty::TyDecl::StructDecl(struct_ty_decl) => TypeInfo::Struct(struct_ty_decl.decl_id),
ty::TyDecl::EnumDecl(enum_ty_decl) => TypeInfo::Enum(enum_ty_decl.decl_id),
ty::TyDecl::TraitTypeDecl(type_decl) => {
let type_decl = engines.de().get_type(&type_decl.decl_id);
if type_decl.ty.is_none() {
return Err(handler.emit_err(CompileError::Internal(
"Trait type declaration has no type",
symbol.span(),
)));
}
(*engines.te().get(type_decl.ty.clone().unwrap().type_id())).clone()
}
ty::TyDecl::GenericTypeForFunctionScope(decl) => {
(*engines.te().get(decl.type_id)).clone()
}
_ => {
return Err(handler.emit_err(CompileError::SymbolNotFound {
name: symbol.clone(),
span: symbol.span(),
}))
}
}),
}
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum IsSelfType {
Yes,
No,
}
#[allow(clippy::too_many_arguments)]
fn resolve_associated_item_from_type_id(
handler: &Handler,
engines: &Engines,
module: &Module,
symbol: &Ident,
type_id: TypeId,
as_trait: Option<CallPath>,
self_type: Option<TypeId>,
) -> Result<(ResolvedDeclaration, IsSelfType), ErrorEmitted> {
let mut is_self_type = IsSelfType::No;
let type_id = if engines.te().get(type_id).is_self_type() {
if let Some(self_type) = self_type {
is_self_type = IsSelfType::Yes;
self_type
} else {
return Err(handler.emit_err(CompileError::Internal(
"Self type not provided.",
symbol.span(),
)));
}
} else {
type_id
};
let item_ref =
TraitMap::get_trait_item_for_type(module, handler, engines, symbol, type_id, as_trait)?;
let resolved = match item_ref {
ResolvedTraitImplItem::Parsed(_item) => todo!(),
ResolvedTraitImplItem::Typed(item) => match item {
TyTraitItem::Fn(fn_ref) => ResolvedDeclaration::Typed(fn_ref.into()),
TyTraitItem::Constant(const_ref) => ResolvedDeclaration::Typed(const_ref.into()),
TyTraitItem::Type(type_ref) => ResolvedDeclaration::Typed(type_ref.into()),
},
};
Ok((resolved, is_self_type))
}
#[allow(clippy::too_many_arguments)]
fn resolve_associated_type_or_item(
handler: &Handler,
engines: &Engines,
module: &Module,
symbol: &Ident,
decl: ResolvedDeclaration,
as_trait: Option<CallPath>,
self_type: Option<TypeId>,
) -> Result<(ResolvedDeclaration, IsSelfType), ErrorEmitted> {
let type_info = decl_to_type_info(handler, engines, symbol, decl)?;
let type_id = engines
.te()
.insert(engines, type_info, symbol.span().source_id());
resolve_associated_item_from_type_id(
handler, engines, module, symbol, type_id, as_trait, self_type,
)
}
#[allow(clippy::too_many_arguments)]
fn resolve_call_path_and_root_type_id(
handler: &Handler,
engines: &Engines,
module: &Module,
root_type_id: TypeId,
mut as_trait: Option<CallPath>,
call_path: &CallPath,
self_type: Option<TypeId>,
) -> Result<(ResolvedDeclaration, IsSelfType), ErrorEmitted> {
// This block tries to resolve associated types
let mut decl_opt = None;
let mut type_id_opt = Some(root_type_id);
let mut is_self_type = IsSelfType::No;
for ident in call_path.prefixes.iter() {
if let Some(type_id) = type_id_opt {
type_id_opt = None;
decl_opt = Some(resolve_associated_item_from_type_id(
handler,
engines,
module,
ident,
type_id,
as_trait.clone(),
self_type,
)?);
as_trait = None;
} else if let Some((decl, ret_is_self_type)) = decl_opt {
if ret_is_self_type == IsSelfType::Yes {
is_self_type = IsSelfType::Yes;
}
decl_opt = Some(resolve_associated_type_or_item(
handler,
engines,
module,
ident,
decl,
as_trait.clone(),
self_type,
)?);
as_trait = None;
}
}
if let Some(type_id) = type_id_opt {
let (decl, ret_is_self_type) = resolve_associated_item_from_type_id(
handler,
engines,
module,
&call_path.suffix,
type_id,
as_trait,
self_type,
)?;
if ret_is_self_type == IsSelfType::Yes {
is_self_type = IsSelfType::Yes;
}
return Ok((decl, is_self_type));
}
if let Some((decl, ret_is_self_type)) = decl_opt {
if ret_is_self_type == IsSelfType::Yes {
is_self_type = IsSelfType::Yes;
}
let (decl, ret_is_self_type) = resolve_associated_type_or_item(
handler,
engines,
module,
&call_path.suffix,
decl,
as_trait,
self_type,
)?;
if ret_is_self_type == IsSelfType::Yes {
is_self_type = IsSelfType::Yes;
}
Ok((decl, is_self_type))
} else {
Err(handler.emit_err(CompileError::Internal("Unexpected error", call_path.span())))
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/namespace/module.rs | sway-core/src/semantic_analysis/namespace/module.rs | use crate::{
engine_threading::Engines,
language::{
ty::{self},
Visibility,
},
Ident, TypeId,
};
use super::{
lexical_scope::{Items, LexicalScope, ResolvedFunctionDecl},
LexicalScopeId, ModuleName, ModulePath, ModulePathBuf, ResolvedDeclaration,
ResolvedTraitImplItem, TraitMap,
};
use rustc_hash::FxHasher;
use std::{collections::HashMap, hash::BuildHasherDefault};
use sway_error::handler::Handler;
use sway_error::{error::CompileError, handler::ErrorEmitted};
use sway_types::{span::Span, Spanned};
/// A single `Module` within a Sway project.
///
/// A `Module` is most commonly associated with an individual file of Sway code, e.g. a top-level
/// script/predicate/contract file or some library dependency whether introduced via `mod` or the
/// `[dependencies]` table of a `forc` manifest.
///
/// A `Module` contains a set of all items that exist within the lexical scope via declaration or
/// importing, along with a map of each of its submodules.
#[derive(Clone, Debug)]
pub struct Module {
/// Submodules of the current module represented as an ordered map from each submodule's name
/// to the associated `Module`.
///
/// Submodules are normally introduced in Sway code with the `mod foo;` syntax where `foo` is
/// some library dependency that we include as a submodule.
///
/// Note that we *require* this map to produce deterministic codegen results which is why [`FxHasher`] is used.
submodules: im::HashMap<ModuleName, Module, BuildHasherDefault<FxHasher>>,
/// Keeps all lexical scopes associated with this module.
pub lexical_scopes: Vec<LexicalScope>,
/// Current lexical scope id in the lexical scope hierarchy stack.
pub current_lexical_scope_id: LexicalScopeId,
/// Maps between a span and the corresponding lexical scope id.
pub lexical_scopes_spans: HashMap<Span, LexicalScopeId>,
/// Name of the module, package name for root module, module name for other modules.
/// Module name used is the same as declared in `mod name;`.
name: Ident,
/// Whether or not this is a `pub` module
visibility: Visibility,
/// Empty span at the beginning of the file implementing the module
span: Option<Span>,
/// An absolute path from the `root` that represents the module location.
///
/// The path of the root module in a package is `[package_name]`. If a module `X` is a submodule
/// of module `Y` which is a submodule of the root module in the package `P`, then the path is
/// `[P, Y, X]`.
mod_path: ModulePathBuf,
}
impl Module {
pub(super) fn new(
name: Ident,
visibility: Visibility,
span: Option<Span>,
parent_mod_path: &ModulePathBuf,
) -> Self {
let mut mod_path = parent_mod_path.clone();
mod_path.push(name.clone());
Self {
visibility,
submodules: Default::default(),
lexical_scopes: vec![LexicalScope::default()],
lexical_scopes_spans: Default::default(),
current_lexical_scope_id: 0,
name,
span,
mod_path,
}
}
pub fn name(&self) -> &Ident {
&self.name
}
pub fn visibility(&self) -> &Visibility {
&self.visibility
}
pub fn span(&self) -> &Option<Span> {
&self.span
}
pub fn set_span(&mut self, span: Span) {
self.span = Some(span);
}
pub(super) fn add_new_submodule(
&mut self,
name: &Ident,
visibility: Visibility,
span: Option<Span>,
) {
let module = Self::new(name.clone(), visibility, span, &self.mod_path);
self.submodules.insert(name.to_string(), module);
}
pub(crate) fn import_cached_submodule(&mut self, name: &Ident, module: Module) {
self.submodules.insert(name.to_string(), module);
}
pub fn read<R>(&self, _engines: &crate::Engines, mut f: impl FnMut(&Module) -> R) -> R {
f(self)
}
pub fn write<R>(
&mut self,
_engines: &crate::Engines,
mut f: impl FnMut(&mut Module) -> R,
) -> R {
f(self)
}
pub fn mod_path(&self) -> &ModulePath {
self.mod_path.as_slice()
}
pub fn mod_path_buf(&self) -> ModulePathBuf {
self.mod_path.clone()
}
/// Immutable access to this module's submodules.
pub fn submodules(&self) -> &im::HashMap<ModuleName, Module, BuildHasherDefault<FxHasher>> {
&self.submodules
}
pub fn has_submodule(&self, name: &Ident) -> bool {
self.submodule(std::slice::from_ref(name)).is_some()
}
/// Mutable access to this module's submodules.
pub fn submodules_mut(
&mut self,
) -> &mut im::HashMap<ModuleName, Module, BuildHasherDefault<FxHasher>> {
&mut self.submodules
}
/// Lookup the submodule at the given path.
pub fn submodule(&self, path: &ModulePath) -> Option<&Module> {
let mut module = self;
for ident in path.iter() {
match module.submodules.get(ident.as_str()) {
Some(ns) => module = ns,
None => return None,
}
}
Some(module)
}
/// Unique access to the submodule at the given path.
pub fn submodule_mut(&mut self, path: &ModulePath) -> Option<&mut Module> {
let mut module = self;
for ident in path.iter() {
match module.submodules.get_mut(ident.as_str()) {
Some(ns) => module = ns,
None => return None,
}
}
Some(module)
}
/// Lookup the submodule at the given path.
///
/// This should be used rather than `Index` when we don't yet know whether the module exists.
pub(crate) fn lookup_submodule(
&self,
handler: &Handler,
path: &[Ident],
) -> Result<&Module, ErrorEmitted> {
match self.submodule(path) {
None => Err(handler.emit_err(module_not_found(path, true))),
Some(module) => Ok(module),
}
}
/// Returns the root lexical scope id associated with this module.
pub fn root_lexical_scope_id(&self) -> LexicalScopeId {
0
}
/// Returns the root lexical scope associated with this module.
pub fn root_lexical_scope(&self) -> &LexicalScope {
self.lexical_scopes
.get(self.root_lexical_scope_id())
.unwrap()
}
pub fn get_lexical_scope(&self, id: LexicalScopeId) -> Option<&LexicalScope> {
self.lexical_scopes.get(id)
}
pub fn get_lexical_scope_mut(&mut self, id: LexicalScopeId) -> Option<&mut LexicalScope> {
self.lexical_scopes.get_mut(id)
}
/// Returns the current lexical scope associated with this module.
pub fn current_lexical_scope(&self) -> &LexicalScope {
self.lexical_scopes
.get(self.current_lexical_scope_id)
.unwrap()
}
/// Returns the mutable current lexical scope associated with this module.
pub fn current_lexical_scope_mut(&mut self) -> &mut LexicalScope {
self.lexical_scopes
.get_mut(self.current_lexical_scope_id)
.unwrap()
}
/// The collection of items declared by this module's current lexical scope.
pub fn current_items(&self) -> &Items {
&self.current_lexical_scope().items
}
/// The collection of items declared by this module's root lexical scope.
pub fn root_items(&self) -> &Items {
&self.root_lexical_scope().items
}
/// The mutable collection of items declared by this module's current lexical scope.
pub fn current_items_mut(&mut self) -> &mut Items {
&mut self.current_lexical_scope_mut().items
}
pub fn current_lexical_scope_id(&self) -> LexicalScopeId {
self.current_lexical_scope_id
}
/// Enters the scope with the given span in the module's lexical scope hierarchy.
pub fn enter_lexical_scope(
&mut self,
handler: &Handler,
span: Span,
) -> Result<LexicalScopeId, ErrorEmitted> {
let id_opt = self.lexical_scopes_spans.get(&span);
match id_opt {
Some(id) => {
let visitor_parent = self.current_lexical_scope_id;
self.current_lexical_scope_id = *id;
self.current_lexical_scope_mut().visitor_parent = Some(visitor_parent);
Ok(self.current_lexical_scope_id)
}
None => Err(handler.emit_err(CompileError::Internal(
"Could not find a valid lexical scope for this source location.",
span.clone(),
))),
}
}
/// Pushes a new scope to the module's lexical scope hierarchy.
pub fn push_new_lexical_scope(
&mut self,
span: Span,
declaration: Option<ResolvedDeclaration>,
) -> LexicalScopeId {
let previous_scope_id = self.current_lexical_scope_id();
let previous_scope = self.lexical_scopes.get(previous_scope_id).unwrap();
let new_scoped_id = {
self.lexical_scopes.push(LexicalScope {
parent: Some(previous_scope_id),
visitor_parent: Some(previous_scope_id),
items: Items {
symbols_unique_while_collecting_unifications: previous_scope
.items
.symbols_unique_while_collecting_unifications
.clone(),
..Default::default()
},
declaration,
..Default::default()
});
self.lexical_scopes.len() - 1
};
let previous_scope = self.lexical_scopes.get_mut(previous_scope_id).unwrap();
previous_scope.children.push(new_scoped_id);
self.current_lexical_scope_id = new_scoped_id;
self.lexical_scopes_spans.insert(span, new_scoped_id);
new_scoped_id
}
/// Pops the current scope from the module's lexical scope hierarchy.
pub fn pop_lexical_scope(&mut self) {
let parent_scope_id = self.current_lexical_scope().visitor_parent;
self.current_lexical_scope_id = parent_scope_id.unwrap(); // panics if pops do not match pushes
}
pub fn walk_scope_chain_early_return<T>(
&self,
mut f: impl FnMut(&LexicalScope) -> Result<Option<T>, ErrorEmitted>,
) -> Result<Option<T>, ErrorEmitted> {
let mut lexical_scope_opt = Some(self.current_lexical_scope());
while let Some(lexical_scope) = lexical_scope_opt {
let result = f(lexical_scope)?;
if let Some(result) = result {
return Ok(Some(result));
}
if let Some(parent_scope_id) = lexical_scope.parent {
lexical_scope_opt = self.get_lexical_scope(parent_scope_id);
} else {
lexical_scope_opt = None;
}
}
Ok(None)
}
pub fn walk_scope_chain(&self, mut f: impl FnMut(&LexicalScope)) {
let mut lexical_scope_opt = Some(self.current_lexical_scope());
while let Some(lexical_scope) = lexical_scope_opt {
f(lexical_scope);
if let Some(parent_scope_id) = lexical_scope.parent {
lexical_scope_opt = self.get_lexical_scope(parent_scope_id);
} else {
lexical_scope_opt = None;
}
}
}
pub fn append_items_for_type(
&self,
engines: &Engines,
type_id: TypeId,
items: &mut Vec<ResolvedTraitImplItem>,
) {
TraitMap::append_items_for_type(self, engines, type_id, items)
}
pub fn resolve_symbol(
&self,
handler: &Handler,
engines: &Engines,
symbol: &Ident,
) -> Result<(ResolvedDeclaration, ModulePathBuf), ErrorEmitted> {
let mut last_handler = Handler::default();
let ret = self.walk_scope_chain_early_return(|lexical_scope| {
last_handler = Handler::default();
Ok(lexical_scope
.items
.resolve_symbol(&last_handler, engines, symbol, &self.mod_path)
.ok()
.flatten())
})?;
handler.append(last_handler);
if let Some(ret) = ret {
Ok(ret)
} else {
// Symbol not found
Err(handler.emit_err(CompileError::SymbolNotFound {
name: symbol.clone(),
span: symbol.span(),
}))
}
}
pub fn get_methods_for_type(
&self,
engines: &Engines,
type_id: TypeId,
) -> Vec<ResolvedFunctionDecl> {
let mut items = vec![];
self.append_items_for_type(engines, type_id, &mut items);
items
.into_iter()
.filter_map(|item| match item {
ResolvedTraitImplItem::Parsed(_) => unreachable!(),
ResolvedTraitImplItem::Typed(item) => match item {
ty::TyTraitItem::Fn(decl_ref) => Some(ResolvedFunctionDecl::Typed(decl_ref)),
ty::TyTraitItem::Constant(_decl_ref) => None,
ty::TyTraitItem::Type(_decl_ref) => None,
},
})
.collect::<Vec<_>>()
}
}
/// Create a ModuleNotFound error.
/// If skip_package_name is true, then the package name is not emitted as part of the error
/// message. This is used when the module was supposed to be found in the current package rather
/// than in an external one.
pub fn module_not_found(path: &[Ident], skip_package_name: bool) -> CompileError {
CompileError::ModuleNotFound {
span: path
.iter()
.skip(if skip_package_name { 1 } else { 0 })
.fold(path.last().unwrap().span(), |acc, this_one| {
if acc.source_id() == this_one.span().source_id() {
Span::join(acc, &this_one.span())
} else {
acc
}
}),
name: path
.iter()
.skip(if skip_package_name { 1 } else { 0 })
.map(|x| x.as_str())
.collect::<Vec<_>>()
.join("::"),
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/namespace/contract_helpers.rs | sway-core/src/semantic_analysis/namespace/contract_helpers.rs | use sway_ast::ItemConst;
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_parse::{lex, Parser};
use sway_types::{constants::CONTRACT_ID, ProgramId, Spanned};
use crate::{
build_config::DbgGeneration,
language::{
parsed::{AstNode, AstNodeContent, Declaration, ExpressionKind},
ty::{TyAstNode, TyAstNodeContent},
Visibility,
},
semantic_analysis::{
namespace::Package, symbol_collection_context::SymbolCollectionContext, TypeCheckContext,
},
transform::to_parsed_lang,
Engines, Ident, Namespace,
};
/// Factory function for contracts
pub fn package_with_contract_id(
engines: &Engines,
package_name: Ident,
program_id: ProgramId,
contract_id_value: String,
experimental: crate::ExperimentalFeatures,
dbg_generation: DbgGeneration,
) -> Result<Package, vec1::Vec1<CompileError>> {
let package = Package::new(package_name, None, program_id, true);
let handler = <_>::default();
bind_contract_id_in_root_module(
&handler,
engines,
contract_id_value,
package,
experimental,
dbg_generation,
)
.map_err(|_| {
let (errors, warnings, infos) = handler.consume();
assert!(warnings.is_empty());
assert!(infos.is_empty());
// Invariant: `.value == None` => `!errors.is_empty()`.
vec1::Vec1::try_from_vec(errors).unwrap()
})
}
fn bind_contract_id_in_root_module(
handler: &Handler,
engines: &Engines,
contract_id_value: String,
package: Package,
experimental: crate::ExperimentalFeatures,
dbg_generation: DbgGeneration,
) -> Result<Package, ErrorEmitted> {
// this for loop performs a miniature compilation of each const item in the config
// FIXME(Centril): Stop parsing. Construct AST directly instead!
// parser config
let const_item = format!("pub const {CONTRACT_ID}: b256 = {contract_id_value};");
let const_item_len = const_item.len();
let src = const_item.as_str().into();
let token_stream = lex(handler, src, 0, const_item_len, None).unwrap();
let mut parser = Parser::new(handler, &token_stream, experimental);
// perform the parse
let const_item: ItemConst = parser.parse()?;
let const_item_span = const_item.span();
// perform the conversions from parser code to parse tree types
let attributes = Default::default();
// convert to const decl
let const_decl_id = to_parsed_lang::item_const_to_constant_declaration(
&mut to_parsed_lang::Context::new(
crate::BuildTarget::EVM,
dbg_generation,
experimental,
package.name().as_str(),
),
handler,
engines,
const_item,
Visibility::Private,
attributes,
true,
)?;
// Temporarily disallow non-literals. See https://github.com/FuelLabs/sway/issues/2647.
let const_decl = engines.pe().get_constant(&const_decl_id);
let has_literal = match &const_decl.value {
Some(value) => {
matches!(value.kind, ExpressionKind::Literal(_))
}
None => false,
};
if !has_literal {
return Err(handler.emit_err(CompileError::ContractIdValueNotALiteral {
span: const_item_span,
}));
}
let ast_node = AstNode {
content: AstNodeContent::Declaration(Declaration::ConstantDeclaration(const_decl_id)),
span: const_item_span.clone(),
};
// This is pretty hacky but that's okay because of this code is being removed pretty soon
let mut namespace = Namespace::new(handler, engines, package, false)?;
let mut symbol_ctx = SymbolCollectionContext::new(namespace.clone());
let type_check_ctx =
TypeCheckContext::from_namespace(&mut namespace, &mut symbol_ctx, engines, experimental);
// Typecheck the const declaration. This will add the binding in the supplied namespace
let type_checked = TyAstNode::type_check(handler, type_check_ctx, &ast_node).unwrap();
if let TyAstNodeContent::Declaration(_) = type_checked.content {
Ok(namespace.current_package())
} else {
Err(handler.emit_err(CompileError::Internal(
"Contract ID declaration did not typecheck to a declaration, which should be impossible",
const_item_span,
)))
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/namespace/trait_coherence.rs | sway-core/src/semantic_analysis/namespace/trait_coherence.rs | use std::{
cell::Cell,
collections::{HashMap, HashSet},
};
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::Spanned;
use crate::{
engine_threading::{GetCallPathWithEngines, PartialEqWithEngines, PartialEqWithEnginesContext},
language::CallPath,
Engines, IncludeSelf, SubstTypes, SubstTypesContext, TypeId, TypeInfo, TypeParameter,
TypeSubstMap, UnifyCheck,
};
use super::{Package, TraitMap};
// Given an impl of the form `impl<P1..=Pn> Trait<T1..=Tn>` for `T0`, the impl is allowed if:
// 1. Trait is a local trait
// or
// 2. All of
// a) At least one of the types `T0..=Tn` must be a local type. Let Ti be the first such type.
// b) No uncovered type parameters `P1..=Pn` may appear in `T0..Ti` (excluding `Ti`)
// This is already checked elsewhere in the compiler so no need to check here.
pub(crate) fn check_orphan_rules_for_impls(
handler: &Handler,
engines: &Engines,
current_package: &Package,
) -> Result<(), ErrorEmitted> {
let mut error: Option<ErrorEmitted> = None;
let module = ¤t_package.root_module();
module.walk_scope_chain(|lexical_scope| {
let trait_map = &lexical_scope.items.implemented_traits;
if let Err(err) =
check_orphan_rules_for_impls_in_scope(handler, engines, current_package, trait_map)
{
error = Some(err);
}
});
match error {
Some(err) => Err(err),
None => Ok(()),
}
}
fn check_orphan_rules_for_impls_in_scope(
handler: &Handler,
engines: &Engines,
current_package: &Package,
trait_map: &TraitMap,
) -> Result<(), ErrorEmitted> {
for key in trait_map.trait_impls.keys() {
for trait_entry in trait_map.trait_impls[key].iter() {
// 0. If it's a contract then skip it as it's not relevant to coherence.
if engines
.te()
.get(trait_entry.inner.key.type_id)
.is_contract()
{
continue;
}
// 1. Check if trait is local to the current package
let package_name = trait_entry.inner.key.name.prefixes.first().unwrap();
let package_program_id = current_package.program_id();
let trait_impl_program_id = match trait_entry.inner.value.impl_span.source_id() {
Some(source_id) => source_id.program_id(),
None => {
return Err(handler.emit_err(CompileError::Internal(
"Expected a valid source id",
trait_entry.inner.value.impl_span.clone(),
)))
}
};
if package_program_id != trait_impl_program_id {
continue;
}
if package_name == current_package.name() {
continue;
}
fn references_local_type(
engines: &Engines,
current_package: &Package,
type_id: TypeId,
) -> bool {
// Create a flag to track if a local type was foundt.
let found_local = Cell::new(false);
type_id.walk_inner_types(
engines,
IncludeSelf::Yes,
&|inner_type_id| {
// If we've already flagged a local type, no need to do further work.
if found_local.get() {
return;
}
let inner_type = engines.te().get(*inner_type_id);
let is_local = match *inner_type {
TypeInfo::Enum(decl_id) => {
let enum_decl = engines.de().get_enum(&decl_id);
is_from_local_package(current_package, &enum_decl.call_path)
}
TypeInfo::Struct(decl_id) => {
let struct_decl = engines.de().get_struct(&decl_id);
is_from_local_package(current_package, &struct_decl.call_path)
}
// FIXME: We treat arrays as a special case for now due to lack of const generics.
TypeInfo::Array(_, _) => true,
TypeInfo::StringArray(_) => true,
_ => false,
};
// Mark the flag if a local type is found.
if is_local {
found_local.set(true);
}
},
&|trait_constraint| {
// If we've already flagged a local type, no need to do further work.
if found_local.get() {
return;
}
let is_local =
is_from_local_package(current_package, &trait_constraint.trait_name);
// Mark the flag if a local type is found.
if is_local {
found_local.set(true);
}
},
);
found_local.get()
}
// 2. Now the trait is necessarily upstream to the current package
let mut has_local_type = false;
for arg in &trait_entry.inner.key.name.suffix.args {
has_local_type |= references_local_type(engines, current_package, arg.type_id());
if has_local_type {
break;
}
}
'tp: for type_id in &trait_entry.inner.key.impl_type_parameters {
let tp = engines.te().get(*type_id);
match tp.as_ref() {
TypeInfo::TypeParam(tp) => match tp {
TypeParameter::Type(tp) => {
for tc in &tp.trait_constraints {
has_local_type |=
is_from_local_package(current_package, &tc.trait_name);
if has_local_type {
break 'tp;
}
}
}
TypeParameter::Const(_tp) => {}
},
_ => unreachable!(),
}
}
has_local_type |=
references_local_type(engines, current_package, trait_entry.inner.key.type_id);
if !has_local_type {
let trait_name = trait_entry.inner.key.name.suffix.name.to_string();
let type_name = {
let ty = engines.te().get(trait_entry.inner.key.type_id);
ty.get_type_str(engines)
};
handler.emit_err(CompileError::IncoherentImplDueToOrphanRule {
trait_name,
type_name,
span: trait_entry.inner.value.impl_span.clone(),
});
}
}
}
Ok(())
}
fn is_from_local_package(current_package: &Package, call_path: &CallPath) -> bool {
let package_name = call_path.prefixes.first().unwrap();
let is_external =
current_package
.external_packages
.iter()
.any(|(external_package_name, _root)| {
external_package_name.as_str() == package_name.as_str()
});
if is_external {
return false;
}
assert_eq!(current_package.name().as_str(), package_name.as_str());
true
}
/// Given [TraitMap]s `self` and `other`, checks for overlaps between `self` and `other`.
/// If no overlaps are found extends `self` with `other`.
pub(crate) fn check_impls_for_overlap(
trait_map: &mut TraitMap,
handler: &Handler,
other: TraitMap,
engines: &Engines,
) -> Result<(), ErrorEmitted> {
let mut overlap_err = None;
let unify_check = UnifyCheck::constraint_subset(engines);
let mut traits_types = HashMap::<CallPath, HashSet<TypeId>>::new();
trait_map.get_traits_types(&mut traits_types)?;
other.get_traits_types(&mut traits_types)?;
for key in trait_map.trait_impls.keys() {
for self_entry in trait_map.trait_impls[key].iter() {
let self_tcs: Vec<(CallPath, TypeId)> = self_entry
.inner
.key
.impl_type_parameters
.iter()
.flat_map(|type_id| {
let ti = engines.te().get(*type_id);
match ti.as_ref() {
TypeInfo::TypeParam(tp) => match tp {
TypeParameter::Type(tp) => tp
.trait_constraints
.iter()
.map(|tc| (tc.trait_name.clone(), tp.type_id))
.collect::<Vec<_>>(),
TypeParameter::Const(_tp) => vec![],
},
_ => unreachable!(),
}
})
.collect::<Vec<_>>();
let self_call_path = engines
.te()
.get(self_entry.inner.key.type_id)
.call_path(engines);
other.for_each_impls(engines, self_entry.inner.key.type_id, true, |other_entry| {
let other_call_path = engines
.te()
.get(other_entry.inner.key.type_id)
.call_path(engines);
// This prevents us from checking duplicated types as might happen when
// compiling different versions of the same library.
let is_duplicated_type = matches!(
(&self_call_path, &other_call_path),
(Some(v1), Some(v2))
if v1.prefixes == v2.prefixes
&& v1.span().source_id() != v2.span().source_id()
);
if self_entry.inner.key.name.eq(
&*other_entry.inner.key.name,
&PartialEqWithEnginesContext::new(engines),
) && self_entry.inner.value.impl_span != other_entry.inner.value.impl_span
&& !is_duplicated_type
&& (unify_check
.check(self_entry.inner.key.type_id, other_entry.inner.key.type_id)
|| unify_check
.check(other_entry.inner.key.type_id, self_entry.inner.key.type_id))
{
let other_tcs: Vec<(CallPath, TypeId)> = other_entry
.inner
.key
.impl_type_parameters
.iter()
.flat_map(|type_id| {
let ti = engines.te().get(*type_id);
match ti.as_ref() {
TypeInfo::TypeParam(tp) => match tp {
TypeParameter::Type(tp) => tp
.trait_constraints
.iter()
.map(|tc| (tc.trait_name.clone(), tp.type_id))
.collect::<Vec<_>>(),
TypeParameter::Const(_tp) => vec![],
},
_ => unreachable!(),
}
})
.collect::<Vec<_>>();
let other_tcs_satisfied = other_tcs.iter().all(|(trait_name, tp_type_id)| {
if let Some(tc_type_ids) = traits_types.get(trait_name) {
tc_type_ids.iter().any(|tc_type_id| {
let mut type_mapping = TypeSubstMap::new();
type_mapping.insert(*tp_type_id, *tc_type_id);
let mut type_id = other_entry.inner.key.type_id;
type_id.subst(&SubstTypesContext::new(
handler,
engines,
&type_mapping,
false,
));
unify_check.check(self_entry.inner.key.type_id, type_id)
})
} else {
false
}
});
let self_tcs_satisfied = self_tcs.iter().all(|(trait_name, tp_type_id)| {
if let Some(tc_type_ids) = traits_types.get(trait_name) {
tc_type_ids.iter().any(|tc_type_id| {
let mut type_mapping = TypeSubstMap::new();
type_mapping.insert(*tp_type_id, *tc_type_id);
let mut type_id = self_entry.inner.key.type_id;
type_id.subst(&SubstTypesContext::new(
handler,
engines,
&type_mapping,
false,
));
unify_check.check(other_entry.inner.key.type_id, type_id)
})
} else {
false
}
});
if other_tcs_satisfied && self_tcs_satisfied {
for trait_item_name1 in self_entry.inner.value.trait_items.keys() {
for trait_item_name2 in other_entry.inner.value.trait_items.keys() {
if trait_item_name1 == trait_item_name2 {
overlap_err = Some(
handler.emit_err(
CompileError::ConflictingImplsForTraitAndType {
trait_name: engines
.help_out(self_entry.inner.key.name.as_ref())
.to_string(),
type_implementing_for: engines
.help_out(self_entry.inner.key.type_id)
.to_string(),
type_implementing_for_unaliased: engines
.help_out(self_entry.inner.key.type_id)
.to_string(),
existing_impl_span: self_entry
.inner
.value
.impl_span
.clone(),
second_impl_span: other_entry
.inner
.value
.impl_span
.clone(),
},
),
);
}
}
}
}
}
});
}
}
if let Some(overlap_err) = overlap_err {
return Err(overlap_err);
}
trait_map.extend(other, engines);
Ok(())
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/namespace/mod.rs | sway-core/src/semantic_analysis/namespace/mod.rs | mod contract_helpers;
mod lexical_scope;
mod module;
#[allow(clippy::module_inception)]
mod namespace;
mod package;
mod resolved_declaration;
mod trait_coherence;
mod trait_map;
pub use contract_helpers::*;
pub use lexical_scope::{Items, LexicalScope, LexicalScopeId, LexicalScopePath};
pub use module::module_not_found;
pub use module::Module;
pub use namespace::Namespace;
pub use package::Package;
pub use resolved_declaration::ResolvedDeclaration;
pub(crate) use trait_coherence::check_impls_for_overlap;
pub(crate) use trait_coherence::check_orphan_rules_for_impls;
pub(crate) use trait_map::IsExtendingExistingImpl;
pub(crate) use trait_map::IsImplInterfaceSurface;
pub(crate) use trait_map::IsImplSelf;
pub(super) use trait_map::ResolvedTraitImplItem;
pub(crate) use trait_map::TraitEntry;
pub(crate) use trait_map::TraitKey;
pub use trait_map::TraitMap;
pub(crate) use trait_map::TraitSuffix;
pub use trait_map::TryInsertingTraitImplOnFailure;
use sway_types::Ident;
type ModuleName = String;
pub type ModulePath = [Ident];
pub type ModulePathBuf = Vec<Ident>;
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/namespace/trait_map.rs | sway-core/src/semantic_analysis/namespace/trait_map.rs | use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
fmt,
hash::{DefaultHasher, Hash, Hasher},
sync::Arc,
};
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::{integer_bits::IntegerBits, BaseIdent, Ident, Span, Spanned};
use crate::{
decl_engine::{
parsed_id::ParsedDeclId, DeclEngineGet, DeclEngineGetParsedDeclId, DeclEngineInsert,
},
engine_threading::*,
language::{
parsed::{EnumDeclaration, ImplItem, StructDeclaration},
ty::{self, TyDecl, TyImplItem, TyTraitItem},
CallPath,
},
type_system::{SubstTypes, TypeId},
GenericArgument, IncludeSelf, SubstTypesContext, TraitConstraint, TypeEngine, TypeInfo,
TypeSubstMap, UnifyCheck,
};
use super::Module;
/// Enum used to pass a value asking for insertion of type into trait map when an implementation
/// of the trait cannot be found.
#[derive(Debug, Clone)]
pub enum TryInsertingTraitImplOnFailure {
Yes,
No,
}
#[derive(Clone)]
pub enum CodeBlockFirstPass {
Yes,
No,
}
impl From<bool> for CodeBlockFirstPass {
fn from(value: bool) -> Self {
if value {
CodeBlockFirstPass::Yes
} else {
CodeBlockFirstPass::No
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct TraitSuffix {
pub(crate) name: Ident,
pub(crate) args: Vec<GenericArgument>,
}
impl PartialEqWithEngines for TraitSuffix {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name && self.args.eq(&other.args, ctx)
}
}
impl OrdWithEngines for TraitSuffix {
fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> std::cmp::Ordering {
self.name
.cmp(&other.name)
.then_with(|| self.args.cmp(&other.args, ctx))
}
}
impl DisplayWithEngines for TraitSuffix {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
let res = write!(f, "{}", self.name.as_str());
if !self.args.is_empty() {
write!(
f,
"<{}>",
self.args
.iter()
.map(|i| engines.help_out(i.type_id()).to_string())
.collect::<Vec<_>>()
.join(", ")
)
} else {
res
}
}
}
impl DebugWithEngines for TraitSuffix {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
write!(f, "{}", engines.help_out(self))
}
}
type TraitName = Arc<CallPath<TraitSuffix>>;
#[derive(Clone, Debug)]
pub(crate) struct TraitKey {
pub(crate) name: TraitName,
pub(crate) type_id: TypeId,
pub(crate) impl_type_parameters: Vec<TypeId>,
pub(crate) trait_decl_span: Option<Span>,
pub(crate) is_impl_interface_surface: IsImplInterfaceSurface,
}
impl OrdWithEngines for TraitKey {
fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> std::cmp::Ordering {
self.name.cmp(&other.name, ctx).then_with(|| {
self.type_id
.cmp(&other.type_id)
.then_with(|| self.impl_type_parameters.cmp(&other.impl_type_parameters))
})
}
}
#[derive(Clone, Debug)]
pub enum ResolvedTraitImplItem {
Parsed(ImplItem),
Typed(TyImplItem),
}
impl DebugWithEngines for ResolvedTraitImplItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
match self {
ResolvedTraitImplItem::Parsed(_) => panic!(),
ResolvedTraitImplItem::Typed(ty) => write!(f, "{:?}", engines.help_out(ty)),
}
}
}
impl ResolvedTraitImplItem {
fn expect_typed(self) -> TyImplItem {
match self {
ResolvedTraitImplItem::Parsed(_) => panic!(),
ResolvedTraitImplItem::Typed(ty) => ty,
}
}
pub fn span(&self, engines: &Engines) -> Span {
match self {
ResolvedTraitImplItem::Parsed(item) => item.span(engines),
ResolvedTraitImplItem::Typed(item) => item.span(),
}
}
}
/// Map of name to [ResolvedTraitImplItem](ResolvedTraitImplItem)
type TraitItems = BTreeMap<String, ResolvedTraitImplItem>;
#[derive(Clone, Debug)]
pub(crate) struct TraitValue {
pub(crate) trait_items: TraitItems,
/// The span of the entire impl block.
pub(crate) impl_span: Span,
}
#[derive(Clone, Debug)]
pub(crate) struct TraitEntry {
pub(crate) key: TraitKey,
pub(crate) value: TraitValue,
}
#[derive(Clone, Debug)]
pub(crate) struct SharedTraitEntry {
pub(crate) inner: Arc<TraitEntry>,
}
impl SharedTraitEntry {
pub fn fork_if_non_unique(&mut self) -> &mut Self {
match Arc::get_mut(&mut self.inner) {
Some(_) => {}
None => {
let data = TraitEntry::clone(&self.inner);
self.inner = Arc::new(data);
}
}
self
}
pub fn get_mut(&mut self) -> &mut TraitEntry {
Arc::get_mut(&mut self.inner).unwrap()
}
}
/// Map of string of type entry id and vec of [TraitEntry].
/// We are using the HashMap as a wrapper to the vec so the TraitMap algorithms
/// don't need to traverse every TraitEntry.
pub(crate) type TraitImpls = BTreeMap<TypeRootFilter, Vec<SharedTraitEntry>>;
#[derive(Clone, Hash, Eq, PartialOrd, Ord, PartialEq, Debug)]
pub(crate) enum TypeRootFilter {
Unknown,
Never,
Placeholder,
StringSlice,
StringArray,
U8,
U16,
U32,
U64,
U256,
Bool,
Custom(String),
B256,
Contract,
ErrorRecovery,
Tuple(usize),
Enum(ParsedDeclId<EnumDeclaration>),
Struct(ParsedDeclId<StructDeclaration>),
ContractCaller(String),
Array,
RawUntypedPtr,
RawUntypedSlice,
Ptr,
Slice,
TraitType(String),
}
impl DebugWithEngines for TypeRootFilter {
fn fmt(&self, f: &mut fmt::Formatter<'_>, _engines: &Engines) -> fmt::Result {
use TypeRootFilter::*;
match self {
Unknown => write!(f, "Unknown"),
Never => write!(f, "Never"),
Placeholder => write!(f, "Placeholder"),
StringSlice => write!(f, "StringSlice"),
StringArray => write!(f, "StringArray"),
U8 => write!(f, "u8"),
U16 => write!(f, "u16"),
U32 => write!(f, "u32"),
U64 => write!(f, "u64"),
U256 => write!(f, "u256"),
Bool => write!(f, "bool"),
Custom(name) => write!(f, "Custom({name})"),
B256 => write!(f, "b256"),
Contract => write!(f, "Contract"),
ErrorRecovery => write!(f, "ErrorRecovery"),
Tuple(n) => write!(f, "Tuple(len={n})"),
Enum(parsed_id) => {
write!(f, "Enum({parsed_id:?})")
}
Struct(parsed_id) => {
write!(f, "Struct({parsed_id:?})")
}
ContractCaller(abi_name) => write!(f, "ContractCaller({abi_name})"),
Array => write!(f, "Array"),
RawUntypedPtr => write!(f, "RawUntypedPtr"),
RawUntypedSlice => write!(f, "RawUntypedSlice"),
Ptr => write!(f, "Ptr"),
Slice => write!(f, "Slice"),
TraitType(name) => write!(f, "TraitType({name})"),
}
}
}
/// Map holding trait implementations for types.
///
/// Note: "impl self" blocks are considered traits and are stored in the
/// [TraitMap].
#[derive(Clone, Debug, Default)]
pub struct TraitMap {
pub(crate) trait_impls: TraitImpls,
satisfied_cache: HashSet<u64>,
}
pub(crate) enum IsImplSelf {
Yes,
No,
}
pub(crate) enum IsExtendingExistingImpl {
Yes,
No,
}
#[derive(Clone, Debug)]
pub(crate) enum IsImplInterfaceSurface {
Yes,
No,
}
impl DebugWithEngines for TraitMap {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
if self.trait_impls.is_empty() {
return write!(f, "TraitMap {{ <empty> }}");
}
writeln!(f, "TraitMap {{")?;
for (root, entries) in &self.trait_impls {
writeln!(f, " [root={:?}]", engines.help_out(root))?;
for se in entries {
let entry = &se.inner;
let key = &entry.key;
let value = &entry.value;
let trait_name_str = engines.help_out(&*key.name).to_string();
let ty_str = engines.help_out(key.type_id).to_string();
let iface_flag = match key.is_impl_interface_surface {
IsImplInterfaceSurface::Yes => "interface_surface",
IsImplInterfaceSurface::No => "impl",
};
let mut impl_tparams = String::new();
if !key.impl_type_parameters.is_empty() {
impl_tparams.push_str(" where [");
let mut first = true;
for t in &key.impl_type_parameters {
if !first {
impl_tparams.push_str(", ");
}
first = false;
impl_tparams.push_str(&engines.help_out(*t).to_string());
}
impl_tparams.push(']');
}
writeln!(
f,
" impl {trait_name_str} for {ty_str} [{iface_flag}]{impl_tparams} {{"
)?;
for (name, item) in &value.trait_items {
match item {
ResolvedTraitImplItem::Parsed(_p) => {
writeln!(f, " - {name}: <parsed>")?;
}
ResolvedTraitImplItem::Typed(ty_item) => {
writeln!(f, " - {}: {:?}", name, engines.help_out(ty_item))?;
}
}
}
writeln!(f, " [impl span: {:?}]", value.impl_span)?;
writeln!(f, " }}")?;
}
}
write!(f, "}}")
}
}
impl TraitMap {
/// Given a [TraitName] `trait_name`, [TypeId] `type_id`, and list of
/// [TyImplItem](ty::TyImplItem) `items`, inserts
/// `items` into the [TraitMap] with the key `(trait_name, type_id)`.
///
/// This method is as conscious as possible of existing entries in the
/// [TraitMap], and tries to append `items` to an existing list of
/// declarations for the key `(trait_name, type_id)` whenever possible.
#[allow(clippy::too_many_arguments)]
pub(crate) fn insert(
&mut self,
handler: &Handler,
trait_name: CallPath,
trait_type_args: Vec<GenericArgument>,
type_id: TypeId,
impl_type_parameters: Vec<TypeId>,
items: &[ResolvedTraitImplItem],
impl_span: &Span,
trait_decl_span: Option<Span>,
is_impl_self: IsImplSelf,
is_extending_existing_impl: IsExtendingExistingImpl,
is_impl_interface_surface: IsImplInterfaceSurface,
engines: &Engines,
) -> Result<(), ErrorEmitted> {
let unaliased_type_id = engines.te().get_unaliased_type_id(type_id);
handler.scope(|handler| {
let mut trait_items: TraitItems = BTreeMap::new();
for item in items.iter() {
match item {
ResolvedTraitImplItem::Parsed(_) => todo!(),
ResolvedTraitImplItem::Typed(ty_item) => match ty_item {
TyImplItem::Fn(decl_ref) => {
if trait_items
.insert(decl_ref.name().clone().to_string(), item.clone())
.is_some()
{
// duplicate method name
handler.emit_err(CompileError::MultipleDefinitionsOfName {
name: decl_ref.name().clone(),
span: decl_ref.span(),
});
}
}
TyImplItem::Constant(decl_ref) => {
trait_items.insert(decl_ref.name().to_string(), item.clone());
}
TyImplItem::Type(decl_ref) => {
trait_items.insert(decl_ref.name().to_string(), item.clone());
}
},
}
}
let trait_impls = self.get_impls_mut(engines, unaliased_type_id);
// check to see if adding this trait will produce a conflicting definition
for entry in trait_impls.iter() {
let TraitEntry {
key:
TraitKey {
name: map_trait_name,
type_id: map_type_id,
trait_decl_span: _,
impl_type_parameters: _,
is_impl_interface_surface: map_is_impl_interface_surface,
},
value:
TraitValue {
trait_items: map_trait_items,
impl_span: existing_impl_span,
},
} = entry.inner.as_ref();
let CallPath {
suffix:
TraitSuffix {
name: map_trait_name_suffix,
args: map_trait_type_args,
},
..
} = &*map_trait_name.clone();
let unify_checker = UnifyCheck::non_generic_constraint_subset(engines);
// Types are subset if the `unaliased_type_id` that we want to insert can unify with the
// existing `map_type_id`. In addition we need to additionally check for the case of
// `&mut <type>` and `&<type>`.
let types_are_subset = unify_checker.check(unaliased_type_id, *map_type_id)
&& is_unified_type_subset(engines.te(), unaliased_type_id, *map_type_id);
/// `left` can unify into `right`. Additionally we need to check subset condition in case of
/// [TypeInfo::Ref] types. Although `&mut <type>` can unify with `&<type>`
/// when it comes to trait and self impls, we considered them to be different types.
/// E.g., we can have `impl Foo for &T` and at the same time `impl Foo for &mut T`.
/// Or in general, `impl Foo for & &mut .. &T` is different type then, e.g., `impl Foo for &mut & .. &mut T`.
fn is_unified_type_subset(
type_engine: &TypeEngine,
mut left: TypeId,
mut right: TypeId,
) -> bool {
// The loop cannot be endless, because at the end we must hit a referenced type which is not
// a reference.
loop {
let left_ty_info = &*type_engine.get_unaliased(left);
let right_ty_info = &*type_engine.get_unaliased(right);
match (left_ty_info, right_ty_info) {
(
TypeInfo::Ref {
to_mutable_value: l_to_mut,
..
},
TypeInfo::Ref {
to_mutable_value: r_to_mut,
..
},
) if *l_to_mut != *r_to_mut => return false, // Different mutability means not subset.
(
TypeInfo::Ref {
referenced_type: l_ty,
..
},
TypeInfo::Ref {
referenced_type: r_ty,
..
},
) => {
left = l_ty.type_id;
right = r_ty.type_id;
}
_ => return true,
}
}
}
let mut traits_are_subset = true;
if *map_trait_name_suffix != trait_name.suffix
|| map_trait_type_args.len() != trait_type_args.len()
{
traits_are_subset = false;
} else {
for (map_arg_type, arg_type) in
map_trait_type_args.iter().zip(trait_type_args.iter())
{
if !unify_checker.check(arg_type.type_id(), map_arg_type.type_id()) {
traits_are_subset = false;
}
}
}
let should_check = matches!(is_impl_interface_surface, IsImplInterfaceSurface::No);
if should_check {
if matches!(is_extending_existing_impl, IsExtendingExistingImpl::No)
&& types_are_subset
&& traits_are_subset
&& matches!(is_impl_self, IsImplSelf::No)
&& matches!(map_is_impl_interface_surface, IsImplInterfaceSurface::No)
{
handler.emit_err(CompileError::ConflictingImplsForTraitAndType {
trait_name: trait_name.to_string_with_args(engines, &trait_type_args),
type_implementing_for: engines.help_out(type_id).to_string(),
type_implementing_for_unaliased: engines
.help_out(unaliased_type_id)
.to_string(),
existing_impl_span: existing_impl_span.clone(),
second_impl_span: impl_span.clone(),
});
} else if types_are_subset
&& (traits_are_subset || matches!(is_impl_self, IsImplSelf::Yes))
&& matches!(map_is_impl_interface_surface, IsImplInterfaceSurface::No)
{
for name in trait_items.keys() {
let item = &trait_items[name];
match item {
ResolvedTraitImplItem::Parsed(_item) => todo!(),
ResolvedTraitImplItem::Typed(item) => match item {
ty::TyTraitItem::Fn(decl_ref) => {
if let Some(existing_item) = map_trait_items.get(name) {
handler.emit_err(
CompileError::DuplicateDeclDefinedForType {
decl_kind: "method".into(),
decl_name: decl_ref.name().to_string(),
type_implementing_for: engines
.help_out(type_id)
.to_string(),
type_implementing_for_unaliased: engines
.help_out(unaliased_type_id)
.to_string(),
existing_impl_span: existing_item
.span(engines)
.clone(),
second_impl_span: decl_ref.name().span(),
},
);
}
}
ty::TyTraitItem::Constant(decl_ref) => {
if let Some(existing_item) = map_trait_items.get(name) {
handler.emit_err(
CompileError::DuplicateDeclDefinedForType {
decl_kind: "constant".into(),
decl_name: decl_ref.name().to_string(),
type_implementing_for: engines
.help_out(type_id)
.to_string(),
type_implementing_for_unaliased: engines
.help_out(unaliased_type_id)
.to_string(),
existing_impl_span: existing_item
.span(engines)
.clone(),
second_impl_span: decl_ref.name().span(),
},
);
}
}
ty::TyTraitItem::Type(decl_ref) => {
if let Some(existing_item) = map_trait_items.get(name) {
handler.emit_err(
CompileError::DuplicateDeclDefinedForType {
decl_kind: "type".into(),
decl_name: decl_ref.name().to_string(),
type_implementing_for: engines
.help_out(type_id)
.to_string(),
type_implementing_for_unaliased: engines
.help_out(unaliased_type_id)
.to_string(),
existing_impl_span: existing_item
.span(engines)
.clone(),
second_impl_span: decl_ref.name().span(),
},
);
}
}
},
}
}
}
}
}
let trait_name: TraitName = Arc::new(CallPath {
prefixes: trait_name.prefixes,
suffix: TraitSuffix {
name: trait_name.suffix,
args: trait_type_args,
},
callpath_type: trait_name.callpath_type,
});
// even if there is a conflicting definition, add the trait anyway
self.insert_inner(
trait_name,
impl_span.clone(),
trait_decl_span,
unaliased_type_id,
impl_type_parameters,
trait_items,
is_impl_interface_surface,
engines,
);
Ok(())
})
}
#[allow(clippy::too_many_arguments)]
fn insert_inner(
&mut self,
trait_name: TraitName,
impl_span: Span,
trait_decl_span: Option<Span>,
type_id: TypeId,
impl_type_parameters: Vec<TypeId>,
trait_methods: TraitItems,
is_impl_interface_surface: IsImplInterfaceSurface,
engines: &Engines,
) {
let key = TraitKey {
name: trait_name,
type_id,
trait_decl_span,
impl_type_parameters,
is_impl_interface_surface,
};
let value = TraitValue {
trait_items: trait_methods,
impl_span,
};
let mut trait_impls: TraitImpls = BTreeMap::new();
let type_root_filter = Self::get_type_root_filter(engines, type_id);
let entry = TraitEntry { key, value };
let impls_vector = vec![SharedTraitEntry {
inner: Arc::new(entry),
}];
trait_impls.insert(type_root_filter, impls_vector);
let trait_map = TraitMap {
trait_impls,
satisfied_cache: HashSet::default(),
};
self.extend(trait_map, engines);
}
/// Given [TraitMap]s `self` and `other`, extend `self` with `other`,
/// extending existing entries when possible.
pub(crate) fn extend(&mut self, other: TraitMap, engines: &Engines) {
for impls_key in other.trait_impls.keys() {
let oe_vec = &other.trait_impls[impls_key];
let self_vec = if let Some(self_vec) = self.trait_impls.get_mut(impls_key) {
self_vec
} else {
self.trait_impls.insert(impls_key.clone(), Vec::<_>::new());
self.trait_impls.get_mut(impls_key).unwrap()
};
for oe in oe_vec.iter() {
let pos = self_vec.binary_search_by(|se| {
se.inner
.key
.cmp(&oe.inner.key, &OrdWithEnginesContext::new(engines))
});
match pos {
Ok(pos) => self_vec[pos]
.fork_if_non_unique()
.get_mut()
.value
.trait_items
.extend(oe.inner.value.trait_items.clone()),
Err(pos) => self_vec.insert(pos, oe.clone()),
}
}
}
}
pub(crate) fn get_traits_types(
&self,
traits_types: &mut HashMap<CallPath, HashSet<TypeId>>,
) -> Result<(), ErrorEmitted> {
for key in self.trait_impls.keys() {
for self_entry in self.trait_impls[key].iter() {
let callpath = CallPath {
prefixes: self_entry.inner.key.name.prefixes.clone(),
suffix: self_entry.inner.key.name.suffix.name.clone(),
callpath_type: self_entry.inner.key.name.callpath_type,
};
if let Some(set) = traits_types.get_mut(&callpath) {
set.insert(self_entry.inner.key.type_id);
} else {
traits_types.insert(
callpath,
vec![self_entry.inner.key.type_id].into_iter().collect(),
);
}
}
}
Ok(())
}
/// Filters the entries in `self` and return a new [TraitMap] with all of
/// the entries from `self` that implement a trait from the declaration with that span.
pub(crate) fn filter_by_trait_decl_span(&self, trait_decl_span: Span) -> TraitMap {
let mut trait_map = TraitMap::default();
for key in self.trait_impls.keys() {
let vec = &self.trait_impls[key];
for entry in vec {
if entry.inner.key.trait_decl_span.as_ref() == Some(&trait_decl_span) {
let trait_map_vec =
if let Some(trait_map_vec) = trait_map.trait_impls.get_mut(key) {
trait_map_vec
} else {
trait_map.trait_impls.insert(key.clone(), Vec::<_>::new());
trait_map.trait_impls.get_mut(key).unwrap()
};
trait_map_vec.push(entry.clone());
}
}
}
trait_map
}
/// Filters the entries in `self` with the given [TypeId] `type_id` and
/// return a new [TraitMap] with all of the entries from `self` for which
/// `type_id` is a subtype or a supertype. Additionally, the new [TraitMap]
/// contains the entries for the inner types of `self`.
///
/// This is used for handling the case in which we need to import an impl
/// block from another module, and the type that that impl block is defined
/// for is of the type that we are importing, but in a more concrete form.
///
/// Here is some example Sway code that we should expect to compile:
///
/// `my_double.sw`:
/// ```ignore
/// library;
///
/// pub trait MyDouble<T> {
/// fn my_double(self, input: T) -> T;
/// }
/// ```
///
/// `my_point.sw`:
/// ```ignore
/// library;
///
/// use ::my_double::MyDouble;
///
/// pub struct MyPoint<T> {
/// x: T,
/// y: T,
/// }
///
/// impl MyDouble<u64> for MyPoint<u64> {
/// fn my_double(self, value: u64) -> u64 {
/// (self.x*2) + (self.y*2) + (value*2)
/// }
/// }
/// ```
///
/// `main.sw`:
/// ```ignore
/// script;
///
/// mod my_double;
/// mod my_point;
///
/// use my_point::MyPoint;
///
/// fn main() -> u64 {
/// let foo = MyPoint {
/// x: 10u64,
/// y: 10u64,
/// };
/// foo.my_double(100)
/// }
/// ```
///
/// We need to be able to import the trait defined upon `MyPoint<u64>` just
/// from seeing `use ::my_double::MyDouble;`.
pub(crate) fn filter_by_type_item_import(
&self,
type_id: TypeId,
engines: &Engines,
) -> TraitMap {
let unify_checker = UnifyCheck::constraint_subset(engines);
let unify_checker_for_item_import = UnifyCheck::non_generic_constraint_subset(engines);
// a curried version of the decider protocol to use in the helper functions
let decider = |left: TypeId, right: TypeId| {
unify_checker.check(left, right) || unify_checker_for_item_import.check(right, left)
};
let mut trait_map = self.filter_by_type_inner(engines, vec![type_id], decider);
let all_types = type_id
.extract_inner_types(engines, IncludeSelf::No)
.into_iter()
.collect::<Vec<_>>();
// a curried version of the decider protocol to use in the helper functions
let decider2 = |left: TypeId, right: TypeId| unify_checker.check(left, right);
trait_map.extend(
self.filter_by_type_inner(engines, all_types, decider2),
engines,
);
// include indirect trait impls for cases like StorageKey<T>
for key in self.trait_impls.keys() {
for entry in self.trait_impls[key].iter() {
let TraitEntry {
key:
TraitKey {
name: trait_name,
type_id: trait_type_id,
trait_decl_span,
impl_type_parameters,
is_impl_interface_surface,
},
value:
TraitValue {
trait_items,
impl_span,
},
} = entry.inner.as_ref();
let decider3 =
|left: TypeId, right: TypeId| unify_checker_for_item_import.check(right, left);
let matches_generic_params = match *engines.te().get(*trait_type_id) {
TypeInfo::Enum(decl_id) => engines
.de()
.get(&decl_id)
.generic_parameters
.iter()
.any(|gp| gp.unifies(type_id, decider3)),
TypeInfo::Struct(decl_id) => engines
.de()
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/namespace/package.rs | sway-core/src/semantic_analysis/namespace/package.rs | use super::{module::Module, Ident, ModuleName};
use crate::language::Visibility;
use rustc_hash::FxHasher;
use std::hash::BuildHasherDefault;
use sway_types::{span::Span, ProgramId};
/// A representation of the bindings in a package. The package's module structure can be accessed
/// via the root module.
///
/// This is equivalent to a Rust crate. The root module is equivalent to Rust's "crate root".
#[derive(Clone, Debug)]
pub struct Package {
// The contents of the package being compiled.
root_module: Module,
// Program id for the package.
pub program_id: ProgramId,
// True if the current package is a contract, false otherwise.
is_contract_package: bool,
// The external dependencies of the current package. Note that an external package is
// represented as a `Package` object. This is because external packages may have their own external
// dependencies which are needed for lookups, but which are not directly accessible to the
// current package.
pub external_packages: im::HashMap<ModuleName, Package, BuildHasherDefault<FxHasher>>,
}
impl Package {
// Create a new `Package` object with a root module.
//
// To ensure the correct initialization the factory function `package_with_contract_id` is
// supplied in `contract_helpers`.
//
// External packages must be added afterwards by calling `add_external`.
pub fn new(
package_name: Ident,
span: Option<Span>,
program_id: ProgramId,
is_contract_package: bool,
) -> Self {
// The root module must be public
let root_module = Module::new(package_name, Visibility::Public, span, &vec![]);
Self {
root_module,
program_id,
is_contract_package,
external_packages: Default::default(),
}
}
// Add an external package to this package. The package name must be supplied, since the package
// may be referred to by a different name in the Forc.toml file than the actual name of the
// package.
pub fn add_external(&mut self, package_name: String, external_package: Package) {
// This should be ensured by the package manager
assert!(!self.external_packages.contains_key(&package_name));
self.external_packages
.insert(package_name, external_package);
}
pub fn root_module(&self) -> &Module {
&self.root_module
}
pub fn root_module_mut(&mut self) -> &mut Module {
&mut self.root_module
}
pub fn name(&self) -> &Ident {
self.root_module.name()
}
pub fn program_id(&self) -> ProgramId {
self.program_id
}
pub(crate) fn check_path_is_in_package(&self, mod_path: &[Ident]) -> bool {
!mod_path.is_empty() && mod_path[0] == *self.root_module.name()
}
pub(crate) fn package_relative_path(mod_path: &[Ident]) -> &[Ident] {
&mod_path[1..]
}
pub(super) fn is_contract_package(&self) -> bool {
self.is_contract_package
}
// Find module in the current environment. `mod_path` must be a fully qualified path
pub fn module_from_absolute_path(&self, mod_path: &[Ident]) -> Option<&Module> {
assert!(!mod_path.is_empty());
let package_relative_path = Self::package_relative_path(mod_path);
if mod_path[0] == *self.root_module.name() {
self.root_module.submodule(package_relative_path)
} else if let Some(external_package) = self.external_packages.get(mod_path[0].as_str()) {
external_package
.root_module()
.submodule(package_relative_path)
} else {
None
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/namespace/namespace.rs | sway-core/src/semantic_analysis/namespace/namespace.rs | use crate::{
decl_engine::DeclRef,
language::{parsed::*, Visibility},
ty::{self, TyDecl},
Engines, Ident,
};
use super::{
module::Module, package::Package, trait_map::TraitMap, ModuleName, ModulePath, ModulePathBuf,
ResolvedDeclaration,
};
use rustc_hash::FxHasher;
use std::hash::BuildHasherDefault;
use sway_error::{
error::CompileError,
handler::{ErrorEmitted, Handler},
};
use sway_types::{
constants::{CONTRACT_ID, PRELUDE, STD},
span::Span,
Spanned,
};
use sway_utils::iter_prefixes;
/// The set of items that represent the namespace context passed throughout type checking.
#[derive(Clone, Debug)]
pub struct Namespace {
/// The current package, containing all the bindings found so far during compilation.
///
/// The `Package` object should be supplied to `new` in order to be properly initialized. Note
/// also the existence of `contract_helpers::package_with_contract_id`.
pub(crate) current_package: Package,
/// An absolute path to the current module within the current package.
///
/// The path of the root module in a package is `[package_name]`. If a module `X` is a submodule
/// of module `Y` which is a submodule of the root module in the package `P`, then the path is
/// `[P, Y, X]`.
pub(crate) current_mod_path: ModulePathBuf,
}
impl Namespace {
/// Initialize the namespace
/// See also `contract_helpers::package_with_contract_id`.
///
/// If `import_std_prelude_into_root` is true then std::prelude::* will be imported into the
/// root module, provided std is available in the external modules.
pub fn new(
handler: &Handler,
engines: &Engines,
package: Package,
import_std_prelude_into_root: bool,
) -> Result<Self, ErrorEmitted> {
let name = package.name().clone();
let mut res = Self {
current_package: package,
current_mod_path: vec![name],
};
if import_std_prelude_into_root {
res.import_implicits(handler, engines)?;
}
Ok(res)
}
pub fn current_package(self) -> Package {
self.current_package
}
pub fn current_package_ref(&self) -> &Package {
&self.current_package
}
fn module_in_current_package(&self, mod_path: &ModulePathBuf) -> Option<&Module> {
assert!(self.current_package.check_path_is_in_package(mod_path));
self.current_package.module_from_absolute_path(mod_path)
}
pub fn current_module(&self) -> &Module {
self.module_in_current_package(&self.current_mod_path)
.unwrap_or_else(|| {
panic!(
"Could not retrieve submodule for mod_path: {:?}",
self.current_mod_path
);
})
}
pub fn current_module_mut(&mut self) -> &mut Module {
let package_relative_path = Package::package_relative_path(&self.current_mod_path);
self.current_package
.root_module_mut()
.submodule_mut(package_relative_path)
.unwrap_or_else(|| {
panic!("Could not retrieve submodule for mod_path: {package_relative_path:?}");
})
}
pub(crate) fn current_module_has_submodule(&self, submod_name: &Ident) -> bool {
self.current_module()
.submodule(std::slice::from_ref(submod_name))
.is_some()
}
pub fn current_package_name(&self) -> &Ident {
self.current_package.name()
}
/// A reference to the path of the module currently being processed.
pub fn current_mod_path(&self) -> &ModulePathBuf {
&self.current_mod_path
}
/// Prepends the module path into the prefixes.
pub fn prepend_module_path<'a>(
&'a self,
prefixes: impl IntoIterator<Item = &'a Ident>,
) -> ModulePathBuf {
self.current_mod_path
.iter()
.chain(prefixes)
.cloned()
.collect()
}
/// Convert a parsed path to a full path.
pub fn parsed_path_to_full_path(
&self,
_engines: &Engines,
parsed_path: &ModulePathBuf,
is_relative_to_package_root: bool,
) -> ModulePathBuf {
if is_relative_to_package_root {
// Path is relative to the root module in the current package. Prepend the package name
let mut path = vec![self.current_package_name().clone()];
for ident in parsed_path.iter() {
path.push(ident.clone())
}
path
} else if self.current_module_has_submodule(&parsed_path[0]) {
// The first identifier is a submodule of the current module
// The path is therefore assumed to be relative to the current module, so prepend the current module path.
self.prepend_module_path(parsed_path)
} else if self.module_is_external(parsed_path) {
// The path refers to an external module, so the path is already a full path.
parsed_path.to_vec()
} else {
// The first identifier is neither a submodule nor an external package. It must
// therefore refer to a binding in the local environment
self.prepend_module_path(parsed_path)
}
}
pub fn current_package_root_module(&self) -> &Module {
self.current_package.root_module()
}
pub fn external_packages(
&self,
) -> &im::HashMap<ModuleName, Package, BuildHasherDefault<FxHasher>> {
&self.current_package.external_packages
}
pub(crate) fn get_external_package(&self, package_name: &str) -> Option<&Package> {
self.current_package.external_packages.get(package_name)
}
pub(super) fn exists_as_external(&self, package_name: &str) -> bool {
self.get_external_package(package_name).is_some()
}
pub fn module_from_absolute_path(&self, path: &[Ident]) -> Option<&Module> {
if path.is_empty() {
None
} else {
self.current_package.module_from_absolute_path(path)
}
}
// Like module_from_absolute_path, but throws an error if the module is not found
pub fn require_module_from_absolute_path(
&self,
handler: &Handler,
path: &[Ident],
) -> Result<&Module, ErrorEmitted> {
if path.is_empty() {
return Err(handler.emit_err(CompileError::Internal(
"Found empty absolute mod path",
Span::dummy(),
)));
}
let is_in_current_package = self.current_package.check_path_is_in_package(path);
match self.module_from_absolute_path(path) {
Some(module) => Ok(module),
None => Err(handler.emit_err(crate::namespace::module::module_not_found(
path,
is_in_current_package,
))),
}
}
/// Returns true if the current module being checked is a direct or indirect submodule of
/// the module given by the `absolute_module_path`.
///
/// The current module being checked is determined by `current_mod_path`.
///
/// E.g., the mod_path `[fist, second, third]` of the root `foo` is a submodule of the module
/// `[foo, first]`.
///
/// If the current module being checked is the same as the module given by the
/// `absolute_module_path`, the `true_if_same` is returned.
pub(crate) fn module_is_submodule_of(
&self,
absolute_module_path: &ModulePath,
true_if_same: bool,
) -> bool {
if self.current_mod_path.len() < absolute_module_path.len() {
return false;
}
let is_submodule = absolute_module_path
.iter()
.zip(self.current_mod_path.iter())
.all(|(left, right)| left == right);
if is_submodule {
if self.current_mod_path.len() == absolute_module_path.len() {
true_if_same
} else {
true
}
} else {
false
}
}
/// Returns true if the module given by the `absolute_module_path` is external
/// to the current package. External modules are imported in the `Forc.toml` file.
pub(crate) fn module_is_external(&self, absolute_module_path: &ModulePath) -> bool {
assert!(!absolute_module_path.is_empty(), "Absolute module path must have at least one element, because it always contains the package name.");
self.current_package_name() != &absolute_module_path[0]
}
pub fn package_exists(&self, name: &Ident) -> bool {
self.module_from_absolute_path(std::slice::from_ref(name))
.is_some()
}
pub(crate) fn module_has_binding(
&self,
engines: &Engines,
mod_path: &ModulePathBuf,
symbol: &Ident,
) -> bool {
let dummy_handler = Handler::default();
if let Some(module) = self.module_from_absolute_path(mod_path) {
module
.resolve_symbol(&dummy_handler, engines, symbol)
.is_ok()
} else {
false
}
}
// Import std::prelude::* and ::CONTRACT_ID as appropriate into the current module
fn import_implicits(
&mut self,
handler: &Handler,
engines: &Engines,
) -> Result<(), ErrorEmitted> {
// Import preludes
let package_name = self.current_package_name().to_string();
let prelude_ident = Ident::new_no_span(PRELUDE.to_string());
if package_name == STD {
// Do nothing
} else {
// Import std::prelude::*
let std_string = STD.to_string();
// Only import std::prelude::* if std exists as a dependency
if self.exists_as_external(&std_string) {
self.prelude_import(
handler,
engines,
&[Ident::new_no_span(std_string), prelude_ident],
)?
}
}
// Import contract id. CONTRACT_ID is declared in the root module, so only import it into
// non-root modules
if self.current_package.is_contract_package() && self.current_mod_path.len() > 1 {
// import ::CONTRACT_ID
self.item_import_to_current_module(
handler,
engines,
&[Ident::new_no_span(package_name)],
&Ident::new_no_span(CONTRACT_ID.to_string()),
None,
Visibility::Private,
)?
}
Ok(())
}
pub(crate) fn enter_submodule(
&mut self,
handler: &Handler,
engines: &Engines,
mod_name: Ident,
visibility: Visibility,
module_span: Span,
check_implicits: bool,
) -> Result<(), ErrorEmitted> {
let mut import_implicits = false;
// Ensure the new module exists and is initialized properly
if !self
.current_module()
.submodules()
.contains_key(&mod_name.to_string())
&& check_implicits
{
// Entering a new module. Add a new one.
self.current_module_mut()
.add_new_submodule(&mod_name, visibility, Some(module_span));
import_implicits = true;
}
// Update self to point to the new module
self.current_mod_path.push(mod_name.clone());
// Import implicits into the newly created module.
if import_implicits {
self.import_implicits(handler, engines)?;
}
Ok(())
}
/// Pushes a new submodule to the namespace's module hierarchy.
pub fn push_submodule(
&mut self,
handler: &Handler,
engines: &Engines,
mod_name: Ident,
visibility: Visibility,
module_span: Span,
check_implicits: bool,
) -> Result<(), ErrorEmitted> {
match self.enter_submodule(
handler,
engines,
mod_name,
visibility,
module_span,
check_implicits,
) {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
/// Pops the current submodule from the namespace's module hierarchy.
pub fn pop_submodule(&mut self) {
self.current_mod_path.pop();
}
////// IMPORT //////
/// Given a path to a prelude in the standard library, create synonyms to every symbol in that
/// prelude to the current module.
///
/// This is used when a new module is created in order to populate the module with implicit
/// imports from the standard library preludes.
///
/// `src` is assumed to be absolute.
fn prelude_import(
&mut self,
handler: &Handler,
engines: &Engines,
src: &ModulePath,
) -> Result<(), ErrorEmitted> {
let src_mod = self.require_module_from_absolute_path(handler, src)?;
let mut imports = vec![];
// A prelude should not declare its own items
assert!(src_mod.root_items().symbols.is_empty());
// Collect those item-imported items that the source module reexports
let mut symbols = src_mod
.root_items()
.use_item_synonyms
.keys()
.clone()
.collect::<Vec<_>>();
symbols.sort();
for symbol in symbols {
let (_, path, decl, src_visibility) = &src_mod.root_items().use_item_synonyms[symbol];
// Preludes reexport all their imports
assert!(matches!(src_visibility, Visibility::Public));
imports.push((symbol.clone(), decl.clone(), path.clone()))
}
// Collect those glob-imported items that the source module reexports. There should be no
// name clashes in a prelude, so item reexports and glob reexports can be treated the same
// way.
let mut symbols = src_mod
.root_items()
.use_glob_synonyms
.keys()
.clone()
.collect::<Vec<_>>();
symbols.sort();
for symbol in symbols {
let bindings = &src_mod.root_items().use_glob_synonyms[symbol];
for (path, decl, src_visibility) in bindings.iter() {
// Preludes reexport all their imports.
assert!(matches!(src_visibility, Visibility::Public));
imports.push((symbol.clone(), decl.clone(), path.clone()))
}
}
let implemented_traits = src_mod.root_items().implemented_traits.clone();
let dst_mod = self.current_module_mut();
dst_mod
.current_items_mut()
.implemented_traits
.extend(implemented_traits, engines);
let dst_prelude_synonyms = &mut dst_mod.current_items_mut().prelude_synonyms;
imports.iter().for_each(|(symbol, decl, path)| {
// Preludes should not contain name clashes
assert!(!dst_prelude_synonyms.contains_key(symbol));
dst_prelude_synonyms.insert(symbol.clone(), (path.clone(), decl.clone()));
});
Ok(())
}
/// Given a path to a `src` module, create synonyms to every symbol in that module to the
/// current module.
///
/// This is used when an import path contains an asterisk.
///
/// `src` is assumed to be absolute.
pub(crate) fn star_import_to_current_module(
&mut self,
handler: &Handler,
engines: &Engines,
src: &ModulePath,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
self.check_module_visibility(handler, src)?;
let src_mod = self.require_module_from_absolute_path(handler, src)?;
let mut decls_and_item_imports = vec![];
// Collect all items declared in the source module
let mut symbols = src_mod
.root_items()
.symbols
.keys()
.clone()
.collect::<Vec<_>>();
symbols.sort();
for symbol in symbols {
let decl = &src_mod.root_items().symbols[symbol];
if self.is_ancestor_of_current_module(src) || decl.visibility(engines).is_public() {
decls_and_item_imports.push((symbol.clone(), decl.clone(), src.to_vec()));
}
}
// Collect those item-imported items that the source module reexports
// These live in the same namespace as local declarations, so no shadowing is possible
let mut symbols = src_mod
.root_items()
.use_item_synonyms
.keys()
.clone()
.collect::<Vec<_>>();
symbols.sort();
for symbol in symbols {
let (_, path, decl, src_visibility) = &src_mod.root_items().use_item_synonyms[symbol];
if src_visibility.is_public() {
decls_and_item_imports.push((symbol.clone(), decl.clone(), path.clone()))
}
}
// Collect those glob-imported items that the source module reexports. These may be shadowed
// by local declarations and item imports in the source module, so they are treated
// separately.
let mut glob_imports = vec![];
let mut symbols = src_mod
.root_items()
.use_glob_synonyms
.keys()
.clone()
.collect::<Vec<_>>();
symbols.sort();
for symbol in symbols {
let bindings = &src_mod.root_items().use_glob_synonyms[symbol];
// Ignore if the symbol is shadowed by a local declaration or an item import in the source module
if !decls_and_item_imports
.iter()
.any(|(other_symbol, _, _)| symbol == other_symbol)
{
for (path, decl, src_visibility) in bindings.iter() {
if src_visibility.is_public() {
glob_imports.push((symbol.clone(), decl.clone(), path.clone()))
}
}
}
}
let implemented_traits = src_mod.root_items().implemented_traits.clone();
let dst_mod = self.current_module_mut();
dst_mod
.current_items_mut()
.implemented_traits
.extend(implemented_traits, engines);
decls_and_item_imports
.iter()
.chain(glob_imports.iter())
.for_each(|(symbol, decl, path)| {
dst_mod.current_items_mut().insert_glob_use_symbol(
engines,
symbol.clone(),
path.clone(),
decl,
visibility,
)
});
Ok(())
}
/// Pull all variants from the enum `enum_name` from the given `src` module and import them all into the `dst` module.
///
/// Paths are assumed to be absolute.
pub(crate) fn variant_star_import_to_current_module(
&mut self,
handler: &Handler,
engines: &Engines,
src: &ModulePath,
enum_name: &Ident,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
self.check_module_visibility(handler, src)?;
let parsed_decl_engine = engines.pe();
let decl_engine = engines.de();
let (decl, path) = self.item_lookup(handler, engines, enum_name, src, false)?;
match decl {
ResolvedDeclaration::Parsed(Declaration::EnumDeclaration(decl_id)) => {
let enum_decl = parsed_decl_engine.get_enum(&decl_id);
for variant in enum_decl.variants.iter() {
let variant_name = &variant.name;
let variant_decl =
Declaration::EnumVariantDeclaration(EnumVariantDeclaration {
enum_ref: decl_id,
variant_name: variant_name.clone(),
variant_decl_span: variant.span.clone(),
});
// import it this way.
self.current_module_mut()
.current_items_mut()
.insert_glob_use_symbol(
engines,
variant_name.clone(),
path.clone(),
&ResolvedDeclaration::Parsed(variant_decl),
visibility,
);
}
}
ResolvedDeclaration::Typed(TyDecl::EnumDecl(ty::EnumDecl { decl_id, .. })) => {
let enum_decl = decl_engine.get_enum(&decl_id);
let enum_ref = DeclRef::new(
enum_decl.call_path.suffix.clone(),
decl_id,
enum_decl.span(),
);
for variant_decl in enum_decl.variants.iter() {
let variant_name = &variant_decl.name;
let decl =
ResolvedDeclaration::Typed(TyDecl::EnumVariantDecl(ty::EnumVariantDecl {
enum_ref: enum_ref.clone(),
variant_name: variant_name.clone(),
variant_decl_span: variant_decl.span.clone(),
}));
// import it this way.
self.current_module_mut()
.current_items_mut()
.insert_glob_use_symbol(
engines,
variant_name.clone(),
path.clone(),
&decl,
visibility,
);
}
}
_ => {
return Err(handler.emit_err(CompileError::Internal(
"Attempting to import variants of something that isn't an enum",
enum_name.span(),
)));
}
};
Ok(())
}
/// Pull a single item from a `src` module and import it into the current module.
///
/// The item we want to import is the last item in path because this is a `self` import.
pub(crate) fn self_import_to_current_module(
&mut self,
handler: &Handler,
engines: &Engines,
src: &ModulePath,
alias: Option<Ident>,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
let (last_item, src) = src.split_last().expect("guaranteed by grammar");
self.item_import_to_current_module(handler, engines, src, last_item, alias, visibility)
}
/// Pull a single `item` from the given `src` module and import it into the current module.
///
/// `src` is assumed to be absolute.
pub(crate) fn item_import_to_current_module(
&mut self,
handler: &Handler,
engines: &Engines,
src: &ModulePath,
item: &Ident,
alias: Option<Ident>,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
self.check_module_visibility(handler, src)?;
let src_mod = self.require_module_from_absolute_path(handler, src)?;
let (decl, path) = self.item_lookup(handler, engines, item, src, false)?;
let mut impls_to_insert = TraitMap::default();
if decl.is_typed() {
// We only handle trait imports when handling typed declarations,
// that is, when performing type-checking, and not when collecting.
// Update this once the type system is updated to refer to parsed
// declarations.
// if this is an enum or struct or function, import its implementations
if let Ok(type_id) = decl.return_type(&Handler::default(), engines) {
impls_to_insert.extend(
src_mod
.root_items()
.implemented_traits
.filter_by_type_item_import(type_id, engines),
engines,
);
}
// if this is a trait, import its implementations
let decl_span = decl.span(engines);
if decl.is_trait() {
// TODO: we only import local impls from the source namespace
// this is okay for now but we'll need to device some mechanism to collect all available trait impls
impls_to_insert.extend(
src_mod
.root_items()
.implemented_traits
.filter_by_trait_decl_span(decl_span),
engines,
);
}
}
// no matter what, import it this way though.
let dst_mod = self.current_module_mut();
let check_name_clash = |name| {
if dst_mod.current_items().use_item_synonyms.contains_key(name) {
handler.emit_err(CompileError::ShadowsOtherSymbol { name: name.into() });
}
};
match alias {
Some(alias) => {
check_name_clash(&alias);
dst_mod
.current_items_mut()
.use_item_synonyms
.insert(alias.clone(), (Some(item.clone()), path, decl, visibility))
}
None => {
check_name_clash(item);
dst_mod
.current_items_mut()
.use_item_synonyms
.insert(item.clone(), (None, path, decl, visibility))
}
};
dst_mod
.current_items_mut()
.implemented_traits
.extend(impls_to_insert, engines);
Ok(())
}
/// Pull a single variant `variant` from the enum `enum_name` from the given `src` module and
/// import it into the current module.
///
/// `src` is assumed to be absolute.
#[allow(clippy::too_many_arguments)]
pub(crate) fn variant_import_to_current_module(
&mut self,
handler: &Handler,
engines: &Engines,
src: &ModulePath,
enum_name: &Ident,
variant_name: &Ident,
alias: Option<Ident>,
visibility: Visibility,
) -> Result<(), ErrorEmitted> {
self.check_module_visibility(handler, src)?;
let decl_engine = engines.de();
let parsed_decl_engine = engines.pe();
let (decl, path) = self.item_lookup(handler, engines, enum_name, src, false)?;
match decl {
ResolvedDeclaration::Parsed(decl) => {
if let Declaration::EnumDeclaration(decl_id) = decl {
let enum_decl = parsed_decl_engine.get_enum(&decl_id);
if let Some(variant_decl) =
enum_decl.variants.iter().find(|v| v.name == *variant_name)
{
// import it this way.
let dst_mod = self.current_module_mut();
let check_name_clash = |name| {
if dst_mod.current_items().use_item_synonyms.contains_key(name) {
handler.emit_err(CompileError::ShadowsOtherSymbol {
name: name.into(),
});
}
};
match alias {
Some(alias) => {
check_name_clash(&alias);
dst_mod.current_items_mut().use_item_synonyms.insert(
alias.clone(),
(
Some(variant_name.clone()),
path,
ResolvedDeclaration::Parsed(
Declaration::EnumVariantDeclaration(
EnumVariantDeclaration {
enum_ref: decl_id,
variant_name: variant_name.clone(),
variant_decl_span: variant_decl.span.clone(),
},
),
),
visibility,
),
);
}
None => {
check_name_clash(variant_name);
dst_mod.current_items_mut().use_item_synonyms.insert(
variant_name.clone(),
(
None,
path,
ResolvedDeclaration::Parsed(
Declaration::EnumVariantDeclaration(
EnumVariantDeclaration {
enum_ref: decl_id,
variant_name: variant_name.clone(),
variant_decl_span: variant_decl.span.clone(),
},
),
),
visibility,
),
);
}
};
} else {
return Err(handler.emit_err(CompileError::SymbolNotFound {
name: variant_name.clone(),
span: variant_name.span(),
}));
}
}
}
ResolvedDeclaration::Typed(decl) => {
if let TyDecl::EnumDecl(ty::EnumDecl { decl_id, .. }) = decl {
let enum_decl = decl_engine.get_enum(&decl_id);
let enum_ref = DeclRef::new(
enum_decl.call_path.suffix.clone(),
decl_id,
enum_decl.span(),
);
if let Some(variant_decl) =
enum_decl.variants.iter().find(|v| v.name == *variant_name)
{
// import it this way.
let dst_mod = self.current_module_mut();
let check_name_clash = |name| {
if dst_mod.current_items().use_item_synonyms.contains_key(name) {
handler.emit_err(CompileError::ShadowsOtherSymbol {
name: name.into(),
});
}
};
match alias {
Some(alias) => {
check_name_clash(&alias);
dst_mod.current_items_mut().use_item_synonyms.insert(
alias.clone(),
(
Some(variant_name.clone()),
path,
ResolvedDeclaration::Typed(TyDecl::EnumVariantDecl(
ty::EnumVariantDecl {
enum_ref: enum_ref.clone(),
variant_name: variant_name.clone(),
variant_decl_span: variant_decl.span.clone(),
},
)),
visibility,
),
);
}
None => {
check_name_clash(variant_name);
dst_mod.current_items_mut().use_item_synonyms.insert(
variant_name.clone(),
(
None,
path,
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/namespace/resolved_declaration.rs | sway-core/src/semantic_analysis/namespace/resolved_declaration.rs | use std::fmt;
use crate::{
decl_engine::DeclEngine,
engine_threading::*,
language::{
parsed::*,
ty::{self, EnumDecl, StructDecl, TyDecl},
Visibility,
},
TypeId,
};
use sway_error::handler::{ErrorEmitted, Handler};
#[derive(Clone, Debug)]
pub enum ResolvedDeclaration {
Parsed(Declaration),
Typed(ty::TyDecl),
}
impl DisplayWithEngines for ResolvedDeclaration {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
match self {
ResolvedDeclaration::Parsed(decl) => DisplayWithEngines::fmt(decl, f, engines),
ResolvedDeclaration::Typed(decl) => DisplayWithEngines::fmt(decl, f, engines),
}
}
}
impl DebugWithEngines for ResolvedDeclaration {
fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
match self {
ResolvedDeclaration::Parsed(decl) => DebugWithEngines::fmt(decl, f, engines),
ResolvedDeclaration::Typed(decl) => DebugWithEngines::fmt(decl, f, engines),
}
}
}
impl PartialEqWithEngines for ResolvedDeclaration {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
match (self, other) {
(ResolvedDeclaration::Parsed(lhs), ResolvedDeclaration::Parsed(rhs)) => {
lhs.eq(rhs, ctx)
}
(ResolvedDeclaration::Typed(lhs), ResolvedDeclaration::Typed(rhs)) => lhs.eq(rhs, ctx),
// TODO: Right now we consider differently represented resolved declarations to not be
// equal. This is only used for comparing paths when doing imports, and we will be able
// to safely remove it once we introduce normalized paths.
(ResolvedDeclaration::Parsed(_lhs), ResolvedDeclaration::Typed(_rhs)) => false,
(ResolvedDeclaration::Typed(_lhs), ResolvedDeclaration::Parsed(_rhs)) => false,
}
}
}
impl ResolvedDeclaration {
pub fn is_typed(&self) -> bool {
match self {
ResolvedDeclaration::Parsed(_) => false,
ResolvedDeclaration::Typed(_) => true,
}
}
pub fn resolve_parsed(self, decl_engine: &DeclEngine) -> Declaration {
match self {
ResolvedDeclaration::Parsed(decl) => decl,
ResolvedDeclaration::Typed(ty_decl) => ty_decl
.get_parsed_decl(decl_engine)
.expect("expecting valid parsed declaration"),
}
}
pub fn expect_parsed(self) -> Declaration {
match self {
ResolvedDeclaration::Parsed(decl) => decl,
ResolvedDeclaration::Typed(_ty_decl) => panic!(),
}
}
pub fn expect_typed(self) -> ty::TyDecl {
match self {
ResolvedDeclaration::Parsed(_) => panic!(),
ResolvedDeclaration::Typed(ty_decl) => ty_decl,
}
}
pub fn expect_typed_ref(&self) -> &ty::TyDecl {
match self {
ResolvedDeclaration::Parsed(_) => panic!(),
ResolvedDeclaration::Typed(ty_decl) => ty_decl,
}
}
pub(crate) fn to_struct_decl(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<ResolvedDeclaration, ErrorEmitted> {
match self {
ResolvedDeclaration::Parsed(decl) => decl
.to_struct_decl(handler, engines)
.map(|id| ResolvedDeclaration::Parsed(Declaration::StructDeclaration(id))),
ResolvedDeclaration::Typed(decl) => decl.to_struct_decl(handler, engines).map(|id| {
ResolvedDeclaration::Typed(TyDecl::StructDecl(StructDecl { decl_id: id }))
}),
}
}
pub(crate) fn to_enum_decl(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<ResolvedDeclaration, ErrorEmitted> {
match self {
ResolvedDeclaration::Parsed(decl) => decl
.to_enum_decl(handler, engines)
.map(|id| ResolvedDeclaration::Parsed(Declaration::EnumDeclaration(id))),
ResolvedDeclaration::Typed(decl) => decl
.to_enum_id(handler, engines)
.map(|id| ResolvedDeclaration::Typed(TyDecl::EnumDecl(EnumDecl { decl_id: id }))),
}
}
pub(crate) fn visibility(&self, engines: &Engines) -> Visibility {
match self {
ResolvedDeclaration::Parsed(decl) => decl.visibility(engines.pe()),
ResolvedDeclaration::Typed(decl) => decl.visibility(engines.de()),
}
}
pub(crate) fn span(&self, engines: &Engines) -> sway_types::Span {
match self {
ResolvedDeclaration::Parsed(decl) => decl.span(engines),
ResolvedDeclaration::Typed(decl) => decl.span(engines),
}
}
pub(crate) fn return_type(
&self,
handler: &Handler,
engines: &Engines,
) -> Result<TypeId, ErrorEmitted> {
match self {
ResolvedDeclaration::Parsed(_decl) => unreachable!(),
ResolvedDeclaration::Typed(decl) => decl.return_type(handler, engines),
}
}
pub(crate) fn is_trait(&self) -> bool {
match self {
ResolvedDeclaration::Parsed(decl) => {
matches!(decl, Declaration::TraitDeclaration(_))
}
ResolvedDeclaration::Typed(decl) => {
matches!(decl, TyDecl::TraitDecl(_))
}
}
}
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/namespace/lexical_scope.rs | sway-core/src/semantic_analysis/namespace/lexical_scope.rs | use crate::{
decl_engine::{parsed_engine::ParsedDeclEngineGet, parsed_id::ParsedDeclId, *},
engine_threading::{Engines, PartialEqWithEngines, PartialEqWithEnginesContext},
language::{
parsed::{Declaration, FunctionDeclaration},
ty::{self, TyDecl, TyStorageDecl},
Visibility,
},
namespace::*,
semantic_analysis::{ast_node::ConstShadowingMode, GenericShadowingMode},
type_system::*,
};
use super::{ResolvedDeclaration, TraitMap};
use parking_lot::RwLock;
use sway_error::{
error::{CompileError, ShadowingSource},
handler::{ErrorEmitted, Handler},
};
use sway_types::{span::Span, IdentUnique, Named, Spanned};
use std::{collections::HashMap, sync::Arc};
pub enum ResolvedFunctionDecl {
Parsed(ParsedDeclId<FunctionDeclaration>),
Typed(DeclRefFunction),
}
impl ResolvedFunctionDecl {
pub fn expect_typed(self) -> DeclRefFunction {
match self {
ResolvedFunctionDecl::Parsed(_) => panic!(),
ResolvedFunctionDecl::Typed(fn_ref) => fn_ref,
}
}
}
// The following types were using im::OrdMap but it revealed to be
// much slower than using HashMap and sorting on iterationn.
pub(super) type SymbolMap = HashMap<Ident, ResolvedDeclaration>;
pub(super) type SymbolUniqueMap = HashMap<IdentUnique, ResolvedDeclaration>;
type SourceIdent = Ident;
pub(super) type PreludeSynonyms = HashMap<Ident, (ModulePathBuf, ResolvedDeclaration)>;
pub(super) type GlobSynonyms =
HashMap<Ident, Vec<(ModulePathBuf, ResolvedDeclaration, Visibility)>>;
pub(super) type ItemSynonyms = HashMap<
Ident,
(
Option<SourceIdent>,
ModulePathBuf,
ResolvedDeclaration,
Visibility,
),
>;
/// Represents a lexical scope integer-based identifier, which can be used to reference
/// specific a lexical scope.
pub type LexicalScopeId = usize;
/// Represents a lexical scope path, a vector of lexical scope identifiers, which specifies
/// the path from root to a specific lexical scope in the hierarchy.
pub type LexicalScopePath = Vec<LexicalScopeId>;
/// A `LexicalScope` contains a set of all items that exist within the lexical scope via declaration or
/// importing, along with all its associated hierarchical scopes.
#[derive(Clone, Debug, Default)]
pub struct LexicalScope {
/// The set of symbols, implementations, synonyms and aliases present within this scope.
pub items: Items,
/// The set of available scopes defined inside this scope's hierarchy.
pub children: Vec<LexicalScopeId>,
/// The parent scope associated with this scope. Will be None for a root scope.
pub parent: Option<LexicalScopeId>,
/// The parent while visiting scopes and push popping scopes from a stack.
/// This may differ from parent as we may revisit the scope in a different order during type check.
pub visitor_parent: Option<LexicalScopeId>,
/// The declaration associated with this scope. This will initially be a [ParsedDeclId],
/// but can be replaced to be a [DeclId] once the declaration is type checked.
pub declaration: Option<ResolvedDeclaration>,
}
/// The set of items that exist within some lexical scope via declaration or importing.
#[derive(Clone, Debug, Default)]
pub struct Items {
/// An map from `Ident`s to their associated declarations.
pub(crate) symbols: SymbolMap,
/// An map from `IdentUnique`s to their associated declarations.
/// This uses an Arc<RwLock<SymbolUniqueMap>> so it is shared between all
/// Items clones. This is intended so we can keep the symbols of previous
/// lexical scopes while collecting_unifications scopes.
pub(crate) symbols_unique_while_collecting_unifications: Arc<RwLock<SymbolUniqueMap>>,
pub(crate) implemented_traits: TraitMap,
/// Contains symbols imported from the standard library preludes.
///
/// The import are asserted to never have a name clash. The imported names are always private
/// rather than public (`use ...` rather than `pub use ...`), since the bindings cannot be
/// accessed from outside the importing module. The preludes are asserted to not contain name
/// clashes.
pub(crate) prelude_synonyms: PreludeSynonyms,
/// Contains symbols imported using star imports (`use foo::*`.).
///
/// When star importing from multiple modules the same name may be imported more than once. This
/// is not an error, but it is an error to use the name without a module path. To represent
/// this, use_glob_synonyms maps identifiers to a vector of (module path, type declaration)
/// tuples.
pub(crate) use_glob_synonyms: GlobSynonyms,
/// Contains symbols imported using item imports (`use foo::bar`).
///
/// For aliased item imports `use ::foo::bar::Baz as Wiz` the map key is `Wiz`. `Baz` is stored
/// as the optional source identifier for error reporting purposes.
pub(crate) use_item_synonyms: ItemSynonyms,
/// If there is a storage declaration (which are only valid in contracts), store it here.
pub(crate) declared_storage: Option<DeclRefStorage>,
}
impl Items {
/// Immutable access to the inner symbol map.
pub fn symbols(&self) -> &SymbolMap {
&self.symbols
}
#[allow(clippy::too_many_arguments)]
pub fn apply_storage_load(
&self,
handler: &Handler,
engines: &Engines,
namespace: &Namespace,
namespace_names: &[Ident],
fields: &[Ident],
storage_fields: &[ty::TyStorageField],
storage_keyword_span: Span,
) -> Result<(ty::TyStorageAccess, TypeId), ErrorEmitted> {
match self.declared_storage {
Some(ref decl_ref) => {
let storage = engines.de().get_storage(&decl_ref.id().clone());
storage.apply_storage_load(
handler,
engines,
namespace,
namespace_names,
fields,
storage_fields,
storage_keyword_span,
)
}
None => Err(handler.emit_err(CompileError::NoDeclaredStorage {
span: fields[0].span(),
})),
}
}
pub fn set_storage_declaration(
&mut self,
handler: &Handler,
decl_ref: DeclRefStorage,
) -> Result<(), ErrorEmitted> {
if self.declared_storage.is_some() {
return Err(handler.emit_err(CompileError::MultipleStorageDeclarations {
span: decl_ref.span(),
}));
}
self.declared_storage = Some(decl_ref);
Ok(())
}
pub fn get_all_declared_symbols(&self) -> Vec<&Ident> {
let mut keys: Vec<_> = self.symbols().keys().collect();
keys.sort();
keys
}
pub fn resolve_symbol(
&self,
handler: &Handler,
engines: &Engines,
symbol: &Ident,
current_mod_path: &ModulePathBuf,
) -> Result<Option<(ResolvedDeclaration, ModulePathBuf)>, ErrorEmitted> {
// Check locally declared items. Any name clash with imports will have already been reported as an error.
if let Some(decl) = self.symbols.get(symbol) {
return Ok(Some((decl.clone(), current_mod_path.clone())));
}
// Check item imports
if let Some((_, decl_path, decl, _)) = self.use_item_synonyms.get(symbol) {
return Ok(Some((decl.clone(), decl_path.clone())));
}
// Check glob imports
if let Some(decls) = self.use_glob_synonyms.get(symbol) {
if decls.len() == 1 {
return Ok(Some((decls[0].1.clone(), decls[0].0.clone())));
} else if decls.is_empty() {
return Err(handler.emit_err(CompileError::Internal(
"The name {symbol} was bound in a star import, but no corresponding module paths were found",
symbol.span(),
)));
} else {
return Err(handler.emit_err(CompileError::SymbolWithMultipleBindings {
name: symbol.clone(),
paths: decls
.iter()
.map(|(path, decl, _)| {
get_path_for_decl(path, decl, engines, ¤t_mod_path[0]).join("::")
})
.collect(),
span: symbol.span(),
}));
}
}
// Check prelude imports
if let Some((decl_path, decl)) = self.prelude_synonyms.get(symbol) {
return Ok(Some((decl.clone(), decl_path.clone())));
}
Ok(None)
}
pub(crate) fn insert_parsed_symbol(
handler: &Handler,
engines: &Engines,
module: &mut Module,
name: Ident,
item: Declaration,
const_shadowing_mode: ConstShadowingMode,
generic_shadowing_mode: GenericShadowingMode,
) -> Result<(), ErrorEmitted> {
Self::insert_symbol(
handler,
engines,
module,
name,
ResolvedDeclaration::Parsed(item),
const_shadowing_mode,
generic_shadowing_mode,
false,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn insert_typed_symbol(
handler: &Handler,
engines: &Engines,
module: &mut Module,
name: Ident,
item: ty::TyDecl,
const_shadowing_mode: ConstShadowingMode,
generic_shadowing_mode: GenericShadowingMode,
collecting_unifications: bool,
) -> Result<(), ErrorEmitted> {
Self::insert_symbol(
handler,
engines,
module,
name,
ResolvedDeclaration::Typed(item),
const_shadowing_mode,
generic_shadowing_mode,
collecting_unifications,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn insert_symbol(
handler: &Handler,
engines: &Engines,
module: &mut Module,
name: Ident,
item: ResolvedDeclaration,
const_shadowing_mode: ConstShadowingMode,
generic_shadowing_mode: GenericShadowingMode,
collecting_unifications: bool,
) -> Result<(), ErrorEmitted> {
let parsed_decl_engine = engines.pe();
let decl_engine = engines.de();
#[allow(unused)]
let append_shadowing_error_parsed =
|ident: &Ident,
decl: &Declaration,
is_use: bool,
is_alias: bool,
item: &Declaration,
const_shadowing_mode: ConstShadowingMode| {
use Declaration::*;
match (
ident,
decl,
is_use,
is_alias,
&item,
const_shadowing_mode,
generic_shadowing_mode,
) {
// A general remark for using the `ShadowingSource::LetVar`.
// If the shadowing is detected at this stage, the variable is for
// sure a local variable, because in the case of pattern matching
// struct field variables, the error is already reported and
// the compilation do not proceed to the point of inserting
// the pattern variable into the items.
// variable shadowing a constant
(
constant_ident,
ConstantDeclaration(decl_id),
is_imported_constant,
is_alias,
VariableDeclaration { .. },
_,
_,
) => {
handler.emit_err(CompileError::ConstantsCannotBeShadowed {
shadowing_source: ShadowingSource::LetVar,
name: (&name).into(),
constant_span: constant_ident.span(),
constant_decl_span: if is_imported_constant {
parsed_decl_engine.get(decl_id).span.clone()
} else {
Span::dummy()
},
is_alias,
});
}
// variable shadowing a configurable
(
configurable_ident,
ConfigurableDeclaration(_),
_,
_,
VariableDeclaration { .. },
_,
_,
) => {
handler.emit_err(CompileError::ConfigurablesCannotBeShadowed {
shadowing_source: ShadowingSource::LetVar,
name: (&name).into(),
configurable_span: configurable_ident.span(),
});
}
// constant shadowing a constant sequentially
(
constant_ident,
ConstantDeclaration(decl_id),
is_imported_constant,
is_alias,
ConstantDeclaration { .. },
ConstShadowingMode::Sequential,
_,
) => {
handler.emit_err(CompileError::ConstantsCannotBeShadowed {
shadowing_source: ShadowingSource::Const,
name: (&name).into(),
constant_span: constant_ident.span(),
constant_decl_span: if is_imported_constant {
parsed_decl_engine.get(decl_id).span.clone()
} else {
Span::dummy()
},
is_alias,
});
}
// constant shadowing a configurable sequentially
(
configurable_ident,
ConfigurableDeclaration(_),
_,
_,
ConstantDeclaration { .. },
ConstShadowingMode::Sequential,
_,
) => {
handler.emit_err(CompileError::ConfigurablesCannotBeShadowed {
shadowing_source: ShadowingSource::Const,
name: (&name).into(),
configurable_span: configurable_ident.span(),
});
}
// constant shadowing a variable
(_, VariableDeclaration(decl_id), _, _, ConstantDeclaration { .. }, _, _) => {
handler.emit_err(CompileError::ConstantShadowsVariable {
name: (&name).into(),
variable_span: parsed_decl_engine.get(decl_id).name.span(),
});
}
// constant shadowing a constant item-style (outside of a function body)
(
constant_ident,
ConstantDeclaration { .. },
_,
_,
ConstantDeclaration { .. },
ConstShadowingMode::ItemStyle,
_,
) => {
handler.emit_err(CompileError::ConstantDuplicatesConstantOrConfigurable {
existing_constant_or_configurable: "Constant",
new_constant_or_configurable: "Constant",
name: (&name).into(),
existing_span: constant_ident.span(),
});
}
// constant shadowing a configurable item-style (outside of a function body)
(
configurable_ident,
ConfigurableDeclaration { .. },
_,
_,
ConstantDeclaration { .. },
ConstShadowingMode::ItemStyle,
_,
) => {
handler.emit_err(CompileError::ConstantDuplicatesConstantOrConfigurable {
existing_constant_or_configurable: "Configurable",
new_constant_or_configurable: "Constant",
name: (&name).into(),
existing_span: configurable_ident.span(),
});
}
// configurable shadowing a constant item-style (outside of a function body)
(
constant_ident,
ConstantDeclaration { .. },
_,
_,
ConfigurableDeclaration { .. },
ConstShadowingMode::ItemStyle,
_,
) => {
handler.emit_err(CompileError::ConstantDuplicatesConstantOrConfigurable {
existing_constant_or_configurable: "Constant",
new_constant_or_configurable: "Configurable",
name: (&name).into(),
existing_span: constant_ident.span(),
});
}
// type or type alias shadowing another type or type alias
// trait/abi shadowing another trait/abi
// type or type alias shadowing a trait/abi, or vice versa
(
_,
StructDeclaration { .. }
| EnumDeclaration { .. }
| TypeAliasDeclaration { .. }
| TraitDeclaration { .. }
| AbiDeclaration { .. },
_,
_,
StructDeclaration { .. }
| EnumDeclaration { .. }
| TypeAliasDeclaration { .. }
| TraitDeclaration { .. }
| AbiDeclaration { .. },
_,
_,
) => {
handler.emit_err(CompileError::MultipleDefinitionsOfName {
name: name.clone(),
span: name.span(),
});
}
_ => {}
}
};
let append_shadowing_error_typed =
|ident: &Ident,
decl: &ty::TyDecl,
is_use: bool,
is_alias: bool,
item: &ty::TyDecl,
const_shadowing_mode: ConstShadowingMode| {
use ty::TyDecl::*;
match (
ident,
decl,
is_use,
is_alias,
&item,
const_shadowing_mode,
generic_shadowing_mode,
) {
// A general remark for using the `ShadowingSource::LetVar`.
// If the shadowing is detected at this stage, the variable is for
// sure a local variable, because in the case of pattern matching
// struct field variables, the error is already reported and
// the compilation do not proceed to the point of inserting
// the pattern variable into the items.
// variable shadowing a constant
(
constant_ident,
ConstantDecl(constant_decl),
is_imported_constant,
is_alias,
VariableDecl { .. },
_,
_,
) => {
handler.emit_err(CompileError::ConstantsCannotBeShadowed {
shadowing_source: ShadowingSource::LetVar,
name: (&name).into(),
constant_span: constant_ident.span(),
constant_decl_span: if is_imported_constant {
decl_engine.get(&constant_decl.decl_id).span.clone()
} else {
Span::dummy()
},
is_alias,
});
}
// variable shadowing a configurable
(configurable_ident, ConfigurableDecl(_), _, _, VariableDecl { .. }, _, _) => {
handler.emit_err(CompileError::ConfigurablesCannotBeShadowed {
shadowing_source: ShadowingSource::LetVar,
name: (&name).into(),
configurable_span: configurable_ident.span(),
});
}
// constant shadowing a constant sequentially
(
constant_ident,
ConstantDecl(constant_decl),
is_imported_constant,
is_alias,
ConstantDecl { .. },
ConstShadowingMode::Sequential,
_,
) => {
handler.emit_err(CompileError::ConstantsCannotBeShadowed {
shadowing_source: ShadowingSource::Const,
name: (&name).into(),
constant_span: constant_ident.span(),
constant_decl_span: if is_imported_constant {
decl_engine.get(&constant_decl.decl_id).span.clone()
} else {
Span::dummy()
},
is_alias,
});
}
// constant shadowing a configurable sequentially
(
configurable_ident,
ConfigurableDecl(_),
_,
_,
ConstantDecl { .. },
ConstShadowingMode::Sequential,
_,
) => {
handler.emit_err(CompileError::ConfigurablesCannotBeShadowed {
shadowing_source: ShadowingSource::Const,
name: (&name).into(),
configurable_span: configurable_ident.span(),
});
}
// constant shadowing a variable
(_, VariableDecl(variable_decl), _, _, ConstantDecl { .. }, _, _) => {
handler.emit_err(CompileError::ConstantShadowsVariable {
name: (&name).into(),
variable_span: variable_decl.name.span(),
});
}
// constant shadowing a constant item-style (outside of a function body)
(
constant_ident,
ConstantDecl { .. },
_,
_,
ConstantDecl { .. },
ConstShadowingMode::ItemStyle,
_,
) => {
handler.emit_err(CompileError::ConstantDuplicatesConstantOrConfigurable {
existing_constant_or_configurable: "Constant",
new_constant_or_configurable: "Constant",
name: (&name).into(),
existing_span: constant_ident.span(),
});
}
// constant shadowing a configurable item-style (outside of a function body)
(
configurable_ident,
ConfigurableDecl { .. },
_,
_,
ConstantDecl { .. },
ConstShadowingMode::ItemStyle,
_,
) => {
handler.emit_err(CompileError::ConstantDuplicatesConstantOrConfigurable {
existing_constant_or_configurable: "Configurable",
new_constant_or_configurable: "Constant",
name: (&name).into(),
existing_span: configurable_ident.span(),
});
}
// configurable shadowing a constant item-style (outside of a function body)
(
constant_ident,
ConstantDecl { .. },
_,
_,
ConfigurableDecl { .. },
ConstShadowingMode::ItemStyle,
_,
) => {
handler.emit_err(CompileError::ConstantDuplicatesConstantOrConfigurable {
existing_constant_or_configurable: "Constant",
new_constant_or_configurable: "Configurable",
name: (&name).into(),
existing_span: constant_ident.span(),
});
}
// type or type alias shadowing another type or type alias
// trait/abi shadowing another trait/abi
// type or type alias shadowing a trait/abi, or vice versa
(
_,
StructDecl { .. }
| EnumDecl { .. }
| TypeAliasDecl { .. }
| TraitDecl { .. }
| AbiDecl { .. },
_,
_,
StructDecl { .. }
| EnumDecl { .. }
| TypeAliasDecl { .. }
| TraitDecl { .. }
| AbiDecl { .. },
_,
_,
) => {
handler.emit_err(CompileError::MultipleDefinitionsOfName {
name: name.clone(),
span: name.span(),
});
}
// generic parameter shadowing another generic parameter
(
_,
GenericTypeForFunctionScope { .. },
_,
_,
GenericTypeForFunctionScope { .. },
_,
GenericShadowingMode::Disallow,
) => {
handler.emit_err(CompileError::GenericShadowsGeneric {
name: (&name).into(),
});
}
_ => {}
}
};
let append_shadowing_error =
|ident: &Ident,
decl: &ResolvedDeclaration,
is_use: bool,
is_alias: bool,
item: &ResolvedDeclaration,
const_shadowing_mode: ConstShadowingMode| {
if const_shadowing_mode == ConstShadowingMode::Allow {
return;
}
match (decl, item) {
// TODO: Do not handle any shadowing errors while handling parsed declarations yet,
// or else we will emit errors in a different order from the source code order.
// Update this once the full AST resolving pass is in.
(ResolvedDeclaration::Typed(_decl), ResolvedDeclaration::Parsed(_item)) => {}
(ResolvedDeclaration::Parsed(_decl), ResolvedDeclaration::Parsed(_item)) => {}
(ResolvedDeclaration::Typed(decl), ResolvedDeclaration::Typed(item)) => {
append_shadowing_error_typed(
ident,
decl,
is_use,
is_alias,
item,
const_shadowing_mode,
)
}
_ => unreachable!(),
}
};
let _ = module.walk_scope_chain_early_return(|lexical_scope| {
if let Some((ident, decl)) = lexical_scope.items.symbols.get_key_value(&name) {
append_shadowing_error(
ident,
decl,
false,
false,
&item.clone(),
const_shadowing_mode,
);
}
if let Some((ident, (imported_ident, _, decl, _))) =
lexical_scope.items.use_item_synonyms.get_key_value(&name)
{
append_shadowing_error(
ident,
decl,
true,
imported_ident.is_some(),
&item,
const_shadowing_mode,
);
}
Ok(None::<()>)
});
if collecting_unifications {
module
.current_items_mut()
.symbols_unique_while_collecting_unifications
.write()
.insert(name.clone().into(), item.clone());
}
module.current_items_mut().symbols.insert(name, item);
Ok(())
}
// Add a new binding into use_glob_synonyms. The symbol may already be bound by an earlier
// insertion, in which case the new binding is added as well so that multiple bindings exist.
//
// There are a few edge cases were a new binding will replace an old binding. These edge cases
// are a consequence of the prelude reexports not being implemented properly. See comments in
// the code for details.
pub(crate) fn insert_glob_use_symbol(
&mut self,
engines: &Engines,
symbol: Ident,
src_path: ModulePathBuf,
decl: &ResolvedDeclaration,
visibility: Visibility,
) {
if let Some(cur_decls) = self.use_glob_synonyms.get_mut(&symbol) {
// Name already bound. Check if the decl is already imported
let ctx = PartialEqWithEnginesContext::new(engines);
match cur_decls
.iter()
.position(|(_cur_path, cur_decl, _cur_visibility)| cur_decl.eq(decl, &ctx))
{
Some(index) if matches!(visibility, Visibility::Public) => {
// The name is already bound to this decl. If the new symbol is more visible
// than the old one, then replace the old one.
cur_decls[index] = (src_path.to_vec(), decl.clone(), visibility);
}
Some(_) => {
// Same binding as the existing one. Do nothing.
}
None => {
// New decl for this name. Add it to the end
cur_decls.push((src_path.to_vec(), decl.clone(), visibility));
}
}
} else {
let new_vec = vec![(src_path.to_vec(), decl.clone(), visibility)];
self.use_glob_synonyms.insert(symbol, new_vec);
}
}
pub(crate) fn check_symbol(&self, name: &Ident) -> Result<ResolvedDeclaration, CompileError> {
self.symbols
.get(name)
.cloned()
.ok_or_else(|| CompileError::SymbolNotFound {
name: name.clone(),
span: name.span(),
})
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | true |
FuelLabs/sway | https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-core/src/semantic_analysis/ast_node/mod.rs | sway-core/src/semantic_analysis/ast_node/mod.rs | pub mod code_block;
pub mod declaration;
pub mod expression;
pub mod modes;
pub(crate) use expression::*;
pub(crate) use modes::*;
use crate::{
language::{parsed::*, ty},
semantic_analysis::*,
type_system::*,
Engines, Ident,
};
use sway_error::{
handler::{ErrorEmitted, Handler},
warning::{CompileWarning, Warning},
};
use sway_types::{span::Span, Spanned};
use super::symbol_collection_context::SymbolCollectionContext;
impl ty::TyAstNode {
pub(crate) fn collect(
handler: &Handler,
engines: &Engines,
ctx: &mut SymbolCollectionContext,
node: &AstNode,
) -> Result<(), ErrorEmitted> {
match node.content.clone() {
AstNodeContent::UseStatement(stmt) => {
collect_use_statement(handler, engines, ctx, &stmt);
}
AstNodeContent::IncludeStatement(_i) => (),
AstNodeContent::Declaration(decl) => ty::TyDecl::collect(handler, engines, ctx, decl)?,
AstNodeContent::Expression(expr) => {
ty::TyExpression::collect(handler, engines, ctx, &expr)?
}
AstNodeContent::Error(_spans, _err) => (),
};
Ok(())
}
pub(crate) fn type_check(
handler: &Handler,
mut ctx: TypeCheckContext,
node: &AstNode,
) -> Result<Self, ErrorEmitted> {
let type_engine = ctx.engines.te();
let decl_engine = ctx.engines.de();
let engines = ctx.engines();
let node = ty::TyAstNode {
content: match node.content.clone() {
AstNodeContent::UseStatement(stmt) => {
handle_use_statement(&mut ctx, &stmt, handler);
ty::TyAstNodeContent::SideEffect(ty::TySideEffect {
side_effect: ty::TySideEffectVariant::UseStatement(ty::TyUseStatement {
alias: stmt.alias,
call_path: stmt.call_path,
span: stmt.span,
is_relative_to_package_root: stmt.is_relative_to_package_root,
import_type: stmt.import_type,
}),
})
}
AstNodeContent::IncludeStatement(i) => {
ty::TyAstNodeContent::SideEffect(ty::TySideEffect {
side_effect: ty::TySideEffectVariant::IncludeStatement(
ty::TyIncludeStatement {
mod_name: i.mod_name,
span: i.span,
visibility: i.visibility,
},
),
})
}
AstNodeContent::Declaration(decl) => ty::TyAstNodeContent::Declaration(
ty::TyDecl::type_check(handler, &mut ctx, decl)?,
),
AstNodeContent::Expression(expr) => {
let mut ctx = ctx;
match expr.kind {
ExpressionKind::ImplicitReturn(_) => {
// Do not use any type annotation with implicit returns as that
// will later cause type inference errors when matching implicit block
// types.
}
_ => {
ctx = ctx
.with_help_text("")
.with_type_annotation(type_engine.new_unknown());
}
}
let inner = ty::TyExpression::type_check(handler, ctx, &expr)
.unwrap_or_else(|err| ty::TyExpression::error(err, expr.span(), engines));
ty::TyAstNodeContent::Expression(inner)
}
AstNodeContent::Error(spans, err) => ty::TyAstNodeContent::Error(spans, err),
},
span: node.span.clone(),
};
if let ty::TyAstNode {
content: ty::TyAstNodeContent::Expression(ty::TyExpression { expression, .. }),
..
} = &node
{
match expression {
ty::TyExpressionVariant::ImplicitReturn(_) => {}
_ => {
if !node
.type_info(type_engine)
.can_safely_ignore(type_engine, decl_engine)
{
handler.emit_warn(CompileWarning {
warning_content: Warning::UnusedReturnValue {
r#type: engines.help_out(node.type_info(type_engine)).to_string(),
},
span: node.span.clone(),
})
};
}
}
}
Ok(node)
}
}
fn collect_use_statement(
handler: &Handler,
engines: &Engines,
ctx: &mut SymbolCollectionContext,
stmt: &UseStatement,
) {
let path = ctx.namespace.parsed_path_to_full_path(
engines,
&stmt.call_path,
stmt.is_relative_to_package_root,
);
let _ = match stmt.import_type {
ImportType::Star => {
// try a standard starimport first
let star_import_handler = Handler::default();
let import = ctx.star_import(&star_import_handler, engines, &path, stmt.reexport);
if import.is_ok() {
handler.append(star_import_handler);
import
} else if path.len() >= 2 {
// if it doesn't work it could be an enum star import
if let Some((enum_name, path)) = path.split_last() {
let variant_import_handler = Handler::default();
let variant_import = ctx.variant_star_import(
&variant_import_handler,
engines,
path,
enum_name,
stmt.reexport,
);
if variant_import.is_ok() {
handler.append(variant_import_handler);
variant_import
} else {
handler.append(star_import_handler);
import
}
} else {
handler.append(star_import_handler);
import
}
} else {
handler.append(star_import_handler);
import
}
}
ImportType::SelfImport(_) => {
ctx.self_import(handler, engines, &path, stmt.alias.clone(), stmt.reexport)
}
ImportType::Item(ref s) => {
// try a standard item import first
let item_import_handler = Handler::default();
let import = ctx.item_import(
&item_import_handler,
engines,
&path,
s,
stmt.alias.clone(),
stmt.reexport,
);
if import.is_ok() {
handler.append(item_import_handler);
import
} else if path.len() >= 2 {
// if it doesn't work it could be an enum variant import
// For this to work the path must have at least 2 elements: The current package name and the enum name
if let Some((enum_name, path)) = path.split_last() {
let variant_import_handler = Handler::default();
let variant_import = ctx.variant_import(
&variant_import_handler,
engines,
path,
enum_name,
s,
stmt.alias.clone(),
stmt.reexport,
);
if variant_import.is_ok() {
handler.append(variant_import_handler);
variant_import
} else {
handler.append(item_import_handler);
import
}
} else {
handler.append(item_import_handler);
import
}
} else {
handler.append(item_import_handler);
import
}
}
};
}
// To be removed once TypeCheckContext is ported to use SymbolCollectionContext.
fn handle_use_statement(ctx: &mut TypeCheckContext<'_>, stmt: &UseStatement, handler: &Handler) {
let path = ctx.namespace.parsed_path_to_full_path(
ctx.engines,
&stmt.call_path,
stmt.is_relative_to_package_root,
);
let _ = match stmt.import_type {
ImportType::Star => {
// try a standard starimport first
let star_import_handler = Handler::default();
let import = ctx.star_import(&star_import_handler, &path, stmt.reexport);
if import.is_ok() {
handler.append(star_import_handler);
import
} else if path.len() >= 2 {
// if it doesn't work it could be an enum star import
if let Some((enum_name, path)) = path.split_last() {
let variant_import_handler = Handler::default();
let variant_import = ctx.variant_star_import(
&variant_import_handler,
path,
enum_name,
stmt.reexport,
);
if variant_import.is_ok() {
handler.append(variant_import_handler);
variant_import
} else {
handler.append(star_import_handler);
import
}
} else {
handler.append(star_import_handler);
import
}
} else {
handler.append(star_import_handler);
import
}
}
ImportType::SelfImport(_) => {
ctx.self_import(handler, &path, stmt.alias.clone(), stmt.reexport)
}
ImportType::Item(ref s) => {
// try a standard item import first
let item_import_handler = Handler::default();
let import = ctx.item_import(
&item_import_handler,
&path,
s,
stmt.alias.clone(),
stmt.reexport,
);
if import.is_ok() {
handler.append(item_import_handler);
import
} else if path.len() >= 2 {
// if it doesn't work it could be an enum variant import
// For this to work the path must have at least 2 elements: The current package name and the enum name.
if let Some((enum_name, path)) = path.split_last() {
let variant_import_handler = Handler::default();
let variant_import = ctx.variant_import(
&variant_import_handler,
path,
enum_name,
s,
stmt.alias.clone(),
stmt.reexport,
);
if variant_import.is_ok() {
handler.append(variant_import_handler);
variant_import
} else {
handler.append(item_import_handler);
import
}
} else {
handler.append(item_import_handler);
import
}
} else {
handler.append(item_import_handler);
import
}
}
};
}
| rust | Apache-2.0 | cc8f867043f3ec2c14ec4088d449cde603929a80 | 2026-01-04T15:31:58.694488Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.