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-ast/src/keywords.rs
sway-ast/src/keywords.rs
use crate::priv_prelude::*; /// The type is a keyword. pub trait Keyword: Spanned + Sized { /// Creates the keyword from the given `span`. fn new(span: Span) -> Self; /// Returns an identifier for this keyword. fn ident(&self) -> Ident; /// What the string representation of the keyword is when lexing. const AS_STR: &'static str; } macro_rules! define_keyword ( ($ty_name:ident, $keyword:literal) => { #[derive(Clone, Debug, Serialize)] pub struct $ty_name { span: Span, } impl Spanned for $ty_name { fn span(&self) -> Span { self.span.clone() } } impl Keyword for $ty_name { fn new(span: Span) -> Self { $ty_name { span } } fn ident(&self) -> Ident { Ident::new(self.span()) } const AS_STR: &'static str = $keyword; } impl From<$ty_name> for Ident { fn from(o: $ty_name) -> Ident { o.ident() } } }; ); define_keyword!(ScriptToken, "script"); define_keyword!(ContractToken, "contract"); define_keyword!(PredicateToken, "predicate"); define_keyword!(LibraryToken, "library"); define_keyword!(ModToken, "mod"); define_keyword!(PubToken, "pub"); define_keyword!(UseToken, "use"); define_keyword!(AsToken, "as"); define_keyword!(StructToken, "struct"); define_keyword!(ClassToken, "class"); // Not in the language! Exists for recovery. define_keyword!(EnumToken, "enum"); define_keyword!(SelfToken, "self"); define_keyword!(FnToken, "fn"); define_keyword!(TraitToken, "trait"); define_keyword!(ImplToken, "impl"); define_keyword!(ForToken, "for"); define_keyword!(InToken, "in"); define_keyword!(AbiToken, "abi"); define_keyword!(ConstToken, "const"); define_keyword!(StorageToken, "storage"); define_keyword!(StrToken, "str"); define_keyword!(AsmToken, "asm"); define_keyword!(ReturnToken, "return"); define_keyword!(IfToken, "if"); define_keyword!(ElseToken, "else"); define_keyword!(MatchToken, "match"); define_keyword!(MutToken, "mut"); define_keyword!(LetToken, "let"); define_keyword!(WhileToken, "while"); define_keyword!(WhereToken, "where"); define_keyword!(RefToken, "ref"); define_keyword!(TrueToken, "true"); define_keyword!(FalseToken, "false"); define_keyword!(BreakToken, "break"); define_keyword!(ContinueToken, "continue"); define_keyword!(ConfigurableToken, "configurable"); define_keyword!(TypeToken, "type"); define_keyword!(PtrToken, "__ptr"); define_keyword!(SliceToken, "__slice"); define_keyword!(PanicToken, "panic"); /// The type is a token. pub trait Token: Spanned + Sized { /// Creates the token from the given `span`. fn new(span: Span) -> Self; /// Returns an identifier for this token. fn ident(&self) -> Ident; /// The sequence of punctuations that make up the token. const PUNCT_KINDS: &'static [PunctKind]; /// Punctuations that will not follow the token. const NOT_FOLLOWED_BY: &'static [PunctKind]; /// What the string representation of the token is when lexing. const AS_STR: &'static str; } macro_rules! define_token ( ($ty_name:ident, $description:literal, $as_str:literal, [$($punct_kinds:ident),*], [$($not_followed_by:ident),*]) => { #[derive(Clone, Debug, Serialize)] pub struct $ty_name { span: Span, } impl Default for $ty_name { fn default() -> Self { Self { span: Span::dummy() } } } impl Spanned for $ty_name { fn span(&self) -> Span { self.span.clone() } } impl Token for $ty_name { fn new(span: Span) -> Self { $ty_name { span } } fn ident(&self) -> Ident { Ident::new(self.span()) } const PUNCT_KINDS: &'static [PunctKind] = &[$(PunctKind::$punct_kinds,)*]; const NOT_FOLLOWED_BY: &'static [PunctKind] = &[$(PunctKind::$not_followed_by,)*]; const AS_STR: &'static str = $as_str; } impl From<$ty_name> for Ident { fn from(o: $ty_name) -> Ident { o.ident() } } }; ); define_token!(SemicolonToken, "a semicolon", ";", [Semicolon], []); define_token!( ForwardSlashToken, "a forward slash", "/", [ForwardSlash], [Equals] ); define_token!( DoubleColonToken, "a double colon (::)", "::", [Colon, Colon], [Colon] ); define_token!(StarToken, "an asterisk (*)", "*", [Star], [Equals]); define_token!(DoubleStarToken, "`**`", "**", [Star, Star], []); define_token!(CommaToken, "a comma", ",", [Comma], []); define_token!(ColonToken, "a colon", ":", [Colon], [Colon]); define_token!( RightArrowToken, "`->`", "->", [Sub, GreaterThan], [GreaterThan, Equals] ); define_token!(LessThanToken, "`<`", "<", [LessThan], [LessThan, Equals]); define_token!( GreaterThanToken, "`>`", ">", [GreaterThan], [GreaterThan, Equals] ); define_token!(OpenAngleBracketToken, "`<`", "<", [LessThan], []); define_token!(CloseAngleBracketToken, "`>`", ">", [GreaterThan], []); define_token!(EqToken, "`=`", "=", [Equals], [GreaterThan, Equals]); define_token!(AddEqToken, "`+=`", "+=", [Add, Equals], []); define_token!(SubEqToken, "`-=`", "-=", [Sub, Equals], []); define_token!(StarEqToken, "`*=`", "*=", [Star, Equals], []); define_token!(DivEqToken, "`/=`", "/=", [ForwardSlash, Equals], []); define_token!(ShlEqToken, "`<<=`", "<<=", [LessThan, LessThan, Equals], []); define_token!( ShrEqToken, "`>>=`", ">>=", [GreaterThan, GreaterThan, Equals], [] ); define_token!( FatRightArrowToken, "`=>`", "=>", [Equals, GreaterThan], [GreaterThan, Equals] ); define_token!(DotToken, "`.`", ".", [Dot], []); define_token!(DoubleDotToken, "`..`", "..", [Dot, Dot], [Dot]); define_token!(BangToken, "`!`", "!", [Bang], [Equals]); define_token!(PercentToken, "`%`", "%", [Percent], []); define_token!(AddToken, "`+`", "+", [Add], [Equals]); define_token!(SubToken, "`-`", "-", [Sub], [Equals]); define_token!( ShrToken, "`>>`", ">>", [GreaterThan, GreaterThan], [GreaterThan, Equals] ); define_token!( ShlToken, "`<<`", "<<", [LessThan, LessThan], [LessThan, Equals] ); define_token!(AmpersandToken, "`&`", "&", [Ampersand], [Ampersand]); define_token!(CaretToken, "`^`", "^", [Caret], []); define_token!(PipeToken, "`|`", "|", [Pipe], [Pipe]); define_token!( DoubleEqToken, "`==`", "==", [Equals, Equals], [Equals, GreaterThan] ); define_token!( BangEqToken, "`!=`", "!=", [Bang, Equals], [Equals, GreaterThan] ); define_token!( GreaterThanEqToken, "`>=`", ">=", [GreaterThan, Equals], [Equals, GreaterThan] ); define_token!( LessThanEqToken, "`<=`", "<=", [LessThan, Equals], [Equals, GreaterThan] ); define_token!( DoubleAmpersandToken, "`&&`", "&&", [Ampersand, Ampersand], [Ampersand] ); define_token!(DoublePipeToken, "`||`", "||", [Pipe, Pipe], [Pipe]); define_token!(UnderscoreToken, "`_`", "_", [Underscore], [Underscore]); define_token!(HashToken, "`#`", "#", [Sharp], []); define_token!(HashBangToken, "`#!`", "#!", [Sharp, Bang], []);
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/submodule.rs
sway-ast/src/submodule.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub struct Submodule { pub mod_token: ModToken, pub name: Ident, pub semicolon_token: SemicolonToken, pub visibility: Option<PubToken>, } impl Spanned for Submodule { fn span(&self) -> Span { Span::join(self.mod_token.span(), &self.semicolon_token.span()) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/punctuated.rs
sway-ast/src/punctuated.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub struct Punctuated<T, P> { pub value_separator_pairs: Vec<(T, P)>, pub final_value_opt: Option<Box<T>>, } impl<T, P> Punctuated<T, P> { pub fn empty() -> Self { Self { value_separator_pairs: vec![], final_value_opt: None, } } pub fn single(value: T) -> Self { Self { value_separator_pairs: vec![], final_value_opt: Some(Box::new(value)), } } pub fn iter(&self) -> impl Iterator<Item = &T> { self.value_separator_pairs .iter() .map(|(t, _)| t) .chain(self.final_value_opt.iter().map(|t| &**t)) } pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> { self.value_separator_pairs .iter_mut() .map(|(t, _)| t) .chain(self.final_value_opt.iter_mut().map(|t| &mut **t)) } /// Returns true if the [Punctuated] ends with the punctuation token. /// E.g., `fn fun(x: u64, y: u64,)`. pub fn has_trailing_punctuation(&self) -> bool { !self.value_separator_pairs.is_empty() && self.final_value_opt.is_none() } /// Returns true if the [Punctuated] has neither value separator pairs, /// nor the final value. /// E.g., `fn fun()`. pub fn is_empty(&self) -> bool { self.value_separator_pairs.is_empty() && self.final_value_opt.is_none() } } impl<T, P> IntoIterator for Punctuated<T, P> { type Item = T; type IntoIter = PunctuatedIter<T, P>; fn into_iter(self) -> PunctuatedIter<T, P> { PunctuatedIter { value_separator_pairs: self.value_separator_pairs.into_iter(), final_value_opt: self.final_value_opt, } } } pub struct PunctuatedIter<T, P> { value_separator_pairs: std::vec::IntoIter<(T, P)>, final_value_opt: Option<Box<T>>, } impl<T, P> Iterator for PunctuatedIter<T, P> { type Item = T; fn next(&mut self) -> Option<T> { match self.value_separator_pairs.next() { Some((value, _separator)) => Some(value), None => self.final_value_opt.take().map(|final_value| *final_value), } } } impl<'a, T, P> IntoIterator for &'a Punctuated<T, P> { type Item = &'a T; type IntoIter = PunctuatedRefIter<'a, T, P>; fn into_iter(self) -> PunctuatedRefIter<'a, T, P> { PunctuatedRefIter { punctuated: self, index: 0, } } } pub struct PunctuatedRefIter<'a, T, P> { punctuated: &'a Punctuated<T, P>, index: usize, } impl<'a, T, P> Iterator for PunctuatedRefIter<'a, T, P> { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { if self.index > self.punctuated.value_separator_pairs.len() { return None; } match self.punctuated.value_separator_pairs.get(self.index) { None => match &self.punctuated.final_value_opt { Some(value) => { self.index += 1; Some(value) } None => None, }, Some((value, _separator)) => { self.index += 1; Some(value) } } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/generics.rs
sway-ast/src/generics.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub enum GenericParam { Trait { ident: Ident }, Const { ident: Ident, ty: Ident }, } #[derive(Clone, Debug, Serialize)] pub struct GenericParams { pub parameters: AngleBrackets<Punctuated<GenericParam, CommaToken>>, } #[derive(Clone, Debug, Serialize)] pub struct GenericArgs { pub parameters: AngleBrackets<Punctuated<Ty, CommaToken>>, } impl Spanned for GenericArgs { fn span(&self) -> Span { self.parameters.span() } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/literal.rs
sway-ast/src/literal.rs
use crate::priv_prelude::*; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Deserialize)] pub struct LitString { pub span: Span, pub parsed: String, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Deserialize)] pub struct LitChar { pub span: Span, pub parsed: char, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Deserialize)] pub struct LitInt { pub span: Span, pub parsed: BigUint, pub ty_opt: Option<(LitIntType, Span)>, /// True if this [LitInt] represents a `b256` hex literal /// in a manually generated lexed tree. /// /// `b256` hex literals are not explicitly modeled in the /// [Literal]. During parsing, they are parsed as [LitInt] /// with [LitInt::ty_opt] set to `None`. /// /// To properly render `b256` manually created hex literals, /// that are not backed by a [Span] in the source code, /// we need this additional information, to distinguish /// them from `u256` hex literals. pub is_generated_b256: bool, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Deserialize)] pub enum LitIntType { U8, U16, U32, U64, U256, I8, I16, I32, I64, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Deserialize)] pub struct LitBool { pub span: Span, pub kind: LitBoolType, } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash, Serialize, Deserialize)] pub enum LitBoolType { True, False, } impl From<LitBoolType> for bool { fn from(item: LitBoolType) -> Self { match item { LitBoolType::True => true, LitBoolType::False => false, } } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Deserialize)] pub enum Literal { String(LitString), Char(LitChar), Int(LitInt), Bool(LitBool), } impl Literal { /// Friendly type name string of the [Literal] used for various reportings. pub fn friendly_type_name(&self) -> &'static str { use Literal::*; match self { String(_) => "str", Char(_) => "char", Int(lit_int) => { if lit_int.is_generated_b256 { "b256" } else { lit_int .ty_opt .as_ref() .map_or("numeric", |(ty, _)| match ty { LitIntType::U8 => "u8", LitIntType::U16 => "u16", LitIntType::U32 => "u32", LitIntType::U64 => "u64", LitIntType::U256 => "u256", LitIntType::I8 => "i8", LitIntType::I16 => "i16", LitIntType::I32 => "i32", LitIntType::I64 => "i64", }) } } Bool(_) => "bool", } } } impl Spanned for LitString { fn span(&self) -> Span { self.span.clone() } } impl Spanned for LitChar { fn span(&self) -> Span { self.span.clone() } } impl Spanned for LitInt { fn span(&self) -> Span { match &self.ty_opt { Some((_lit_int_ty, span)) => Span::join(self.span.clone(), span), None => self.span.clone(), } } } impl Spanned for LitBool { fn span(&self) -> Span { self.span.clone() } } impl Spanned for Literal { fn span(&self) -> Span { match self { Literal::String(lit_string) => lit_string.span(), Literal::Char(lit_char) => lit_char.span(), Literal::Int(lit_int) => lit_int.span(), Literal::Bool(lit_bool) => lit_bool.span(), } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/statement.rs
sway-ast/src/statement.rs
use sway_error::handler::ErrorEmitted; use crate::priv_prelude::*; #[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, Serialize)] pub enum Statement { Let(StatementLet), Item(Item), Expr { expr: Expr, semicolon_token_opt: Option<SemicolonToken>, }, // to handle parser recovery: Error represents an unknown statement Error(Box<[Span]>, #[serde(skip_serializing)] ErrorEmitted), } #[derive(Clone, Debug, Serialize)] pub struct StatementLet { pub let_token: LetToken, pub pattern: Pattern, pub ty_opt: Option<(ColonToken, Ty)>, pub eq_token: EqToken, pub expr: Expr, pub semicolon_token: SemicolonToken, } impl Spanned for Statement { fn span(&self) -> Span { match self { Statement::Let(statement_let) => statement_let.span(), Statement::Item(item) => item.span(), Statement::Expr { expr, semicolon_token_opt, } => match semicolon_token_opt { None => expr.span(), Some(semicolon_token) => Span::join(expr.span(), &semicolon_token.span()), }, Statement::Error(spans, _) => Span::join_all(spans.iter().cloned()), } } } impl Spanned for StatementLet { fn span(&self) -> Span { Span::join(self.let_token.span(), &self.semicolon_token.span()) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/intrinsics.rs
sway-ast/src/intrinsics.rs
use serde::{Deserialize, Serialize}; use std::fmt; #[derive(Eq, PartialEq, Debug, Clone, Hash, Serialize, Deserialize)] pub enum Intrinsic { IsReferenceType, SizeOfType, SizeOfVal, SizeOfStr, IsStrArray, AssertIsStrArray, ToStrArray, Eq, Gt, Lt, Gtf, AddrOf, StateClear, StateLoadWord, StateStoreWord, StateLoadQuad, StateStoreQuad, Log, Add, Sub, Mul, Div, And, Or, Xor, Lsh, Rsh, Mod, Revert, PtrAdd, PtrSub, Smo, Not, JmpMem, ContractCall, // __contract_call(params, coins, asset_id, gas) ContractRet, // __contract_ret(ptr, len) EncodeBufferEmpty, // let buffer: (raw_ptr, u64, u64) = __encode_buffer_empty() EncodeBufferAppend, // let buffer: (raw_ptr, u64, u64) = __encode_buffer_append(buffer, primitive data type) EncodeBufferAsRawSlice, // let slice: raw_slice = __encode_buffer_as_raw_slice(buffer) Slice, // let ref_to_slice = __slice::<T: array or ref_to_slice>(item: T, inclusive_start_index, exclusive_end_index) ElemAt, // let elem: &T = __elem_at::<T: array or ref_to_slice>(item: T, index) Transmute, // let dst: B = __transmute::<A, B>(src) Dbg, // __dbg(value) Alloc, // __alloc<T>(size: u64) -> raw_ptr RuntimeMemoryId, // __runtime_mem_id::<T>() -> u64 EncodingMemoryId, // __encoding_mem_id::<T>() -> u64 } impl fmt::Display for Intrinsic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match self { Intrinsic::IsReferenceType => "is_reference_type", Intrinsic::IsStrArray => "is_str_type", Intrinsic::SizeOfType => "size_of", Intrinsic::SizeOfVal => "size_of_val", Intrinsic::SizeOfStr => "size_of_str_array", Intrinsic::AssertIsStrArray => "assert_is_str_array", Intrinsic::ToStrArray => "to_str_array", Intrinsic::Eq => "eq", Intrinsic::Gt => "gt", Intrinsic::Lt => "lt", Intrinsic::Gtf => "gtf", Intrinsic::AddrOf => "addr_of", Intrinsic::StateClear => "state_clear", Intrinsic::StateLoadWord => "state_load_word", Intrinsic::StateStoreWord => "state_store_word", Intrinsic::StateLoadQuad => "state_load_quad", Intrinsic::StateStoreQuad => "state_store_quad", Intrinsic::Log => "log", Intrinsic::Add => "add", Intrinsic::Sub => "sub", Intrinsic::Mul => "mul", Intrinsic::Div => "div", Intrinsic::And => "and", Intrinsic::Or => "or", Intrinsic::Xor => "xor", Intrinsic::Lsh => "lsh", Intrinsic::Rsh => "rsh", Intrinsic::Mod => "mod", Intrinsic::Revert => "revert", Intrinsic::PtrAdd => "ptr_add", Intrinsic::PtrSub => "ptr_sub", Intrinsic::Smo => "smo", Intrinsic::Not => "not", Intrinsic::JmpMem => "jmp_mem", Intrinsic::ContractCall => "contract_call", Intrinsic::ContractRet => "contract_ret", Intrinsic::EncodeBufferEmpty => "encode_buffer_empty", Intrinsic::EncodeBufferAppend => "encode_buffer_append", Intrinsic::EncodeBufferAsRawSlice => "encode_buffer_as_raw_slice", Intrinsic::Slice => "slice", Intrinsic::ElemAt => "elem_at", Intrinsic::Transmute => "transmute", Intrinsic::Dbg => "dbg", Intrinsic::Alloc => "alloc", Intrinsic::RuntimeMemoryId => "runtime_mem_id", Intrinsic::EncodingMemoryId => "encoding_mem_id", }; write!(f, "{s}") } } impl Intrinsic { pub fn try_from_str(raw: &str) -> Option<Intrinsic> { use Intrinsic::*; Some(match raw { "__is_reference_type" => IsReferenceType, "__is_str_array" => IsStrArray, "__size_of" => SizeOfType, "__size_of_val" => SizeOfVal, "__size_of_str_array" => SizeOfStr, "__assert_is_str_array" => AssertIsStrArray, "__to_str_array" => ToStrArray, "__eq" => Eq, "__gt" => Gt, "__lt" => Lt, "__gtf" => Gtf, "__addr_of" => AddrOf, "__state_clear" => StateClear, "__state_load_word" => StateLoadWord, "__state_store_word" => StateStoreWord, "__state_load_quad" => StateLoadQuad, "__state_store_quad" => StateStoreQuad, "__log" => Log, "__add" => Add, "__sub" => Sub, "__mul" => Mul, "__div" => Div, "__and" => And, "__or" => Or, "__xor" => Xor, "__lsh" => Lsh, "__rsh" => Rsh, "__mod" => Mod, "__revert" => Revert, "__ptr_add" => PtrAdd, "__ptr_sub" => PtrSub, "__smo" => Smo, "__not" => Not, "__jmp_mem" => JmpMem, "__contract_call" => ContractCall, "__contract_ret" => ContractRet, "__encode_buffer_empty" => EncodeBufferEmpty, "__encode_buffer_append" => EncodeBufferAppend, "__encode_buffer_as_raw_slice" => EncodeBufferAsRawSlice, "__slice" => Slice, "__elem_at" => ElemAt, "__transmute" => Transmute, "__dbg" => Dbg, "__alloc" => Alloc, "__runtime_mem_id" => RuntimeMemoryId, "__encoding_mem_id" => EncodingMemoryId, _ => return None, }) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/assignable.rs
sway-ast/src/assignable.rs
use crate::priv_prelude::*; /// Left-hand side of an assignment. #[derive(Clone, Debug, Serialize)] pub enum Assignable { /// A single variable or a path to a part of an aggregate. /// E.g.: /// - `my_variable` /// - `array[0].field.x.1` /// /// Note that within the path, we cannot have dereferencing /// (except, of course, in expressions inside of array index operator). /// This is guaranteed by the grammar. /// E.g., an expression like this is not allowed by the grammar: /// `my_struct.*expr` ElementAccess(ElementAccess), /// Dereferencing of an arbitrary reference expression. /// E.g.: /// - *my_ref /// - **if x > 0 { &mut &mut a } else { &mut &mut b } Deref { star_token: StarToken, expr: Box<Expr>, }, } #[derive(Clone, Debug, Serialize)] pub enum ElementAccess { Var(Ident), Index { target: Box<ElementAccess>, arg: SquareBrackets<Box<Expr>>, }, FieldProjection { target: Box<ElementAccess>, dot_token: DotToken, name: Ident, }, TupleFieldProjection { target: Box<ElementAccess>, dot_token: DotToken, field: BigUint, field_span: Span, }, Deref { target: Box<ElementAccess>, star_token: StarToken, /// Multiple Derefs can be nested, this is true for the outer most Deref. is_root_element: bool, }, } impl Spanned for Assignable { fn span(&self) -> Span { match self { Assignable::ElementAccess(element_access) => element_access.span(), Assignable::Deref { star_token, expr } => Span::join(star_token.span(), &expr.span()), } } } impl Spanned for ElementAccess { fn span(&self) -> Span { match self { ElementAccess::Var(name) => name.span(), ElementAccess::Index { target, arg } => Span::join(target.span(), &arg.span()), ElementAccess::FieldProjection { target, name, .. } => { Span::join(target.span(), &name.span()) } ElementAccess::TupleFieldProjection { target, field_span, .. } => Span::join(target.span(), field_span), ElementAccess::Deref { target, star_token, is_root_element: _, } => Span::join(target.span(), &star_token.span()), } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/brackets.rs
sway-ast/src/brackets.rs
use crate::priv_prelude::*; macro_rules! define_brackets ( ($ty_name:ident) => { #[derive(Clone, Debug, Serialize)] pub struct $ty_name<T> { pub inner: T, pub span: Span, } impl<T> $ty_name<T> { pub fn new(inner: T, span: Span) -> $ty_name<T> { $ty_name { inner, span, } } pub fn get(&self) -> &T { &self.inner } pub fn into_inner(self) -> T { self.inner } } impl<T> Spanned for $ty_name<T> { fn span(&self) -> Span { self.span.clone() } } }; ); define_brackets!(Braces); define_brackets!(Parens); define_brackets!(SquareBrackets); #[derive(Clone, Debug, Serialize)] pub struct AngleBrackets<T> { pub open_angle_bracket_token: OpenAngleBracketToken, pub inner: T, pub close_angle_bracket_token: CloseAngleBracketToken, } impl<T> AngleBrackets<T> { pub fn into_inner(self) -> T { self.inner } } impl<T> Spanned for AngleBrackets<T> { fn span(&self) -> Span { Span::join( self.open_angle_bracket_token.span(), &self.close_angle_bracket_token.span(), ) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/token.rs
sway-ast/src/token.rs
use crate::priv_prelude::*; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Spacing { Joint, Alone, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] pub struct Punct { pub span: Span, pub kind: PunctKind, pub spacing: Spacing, } impl Spanned for Punct { fn span(&self) -> Span { self.span.clone() } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] pub struct GenericGroup<T> { pub delimiter: Delimiter, pub token_stream: T, pub span: Span, } pub type Group = GenericGroup<TokenStream>; pub type CommentedGroup = GenericGroup<CommentedTokenStream>; impl<T> Spanned for GenericGroup<T> { fn span(&self) -> Span { self.span.clone() } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] pub enum CommentKind { /// A newlined comment is a comment with a preceding newline before another token. /// /// # Examples /// /// ```sway /// pub fn main() -> bool { /// // Newlined comment /// true /// } /// ``` Newlined, /// A trailing comment is a comment without a preceding newline before another token. /// /// # Examples /// /// ```sway /// var foo = 1; // Trailing comment /// ``` Trailing, /// An inlined comment is a block comment nested between 2 tokens without a newline after it. /// /// # Examples /// /// ```sway /// fn some_function(baz: /* inlined comment */ u64) {} /// ``` Inlined, /// A multiline comment is a block comment that may be nested between 2 tokens with 1 or more newlines within it. /// /// # Examples /// /// ```sway /// fn some_function(baz: /* multiline /// comment */ u64) {} /// ``` Multilined, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] pub struct Comment { pub span: Span, pub comment_kind: CommentKind, } impl Spanned for Comment { fn span(&self) -> Span { self.span.clone() } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] pub enum DocStyle { Outer, Inner, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] pub struct DocComment { pub span: Span, pub content_span: Span, pub doc_style: DocStyle, } impl Spanned for DocComment { fn span(&self) -> Span { self.span.clone() } } /// Allows for generalizing over commented and uncommented token streams. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] pub enum GenericTokenTree<T> { Punct(Punct), Ident(Ident), Group(GenericGroup<T>), Literal(Literal), DocComment(DocComment), } pub type TokenTree = GenericTokenTree<TokenStream>; pub type CommentedTree = GenericTokenTree<CommentedTokenStream>; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] pub enum CommentedTokenTree { Comment(Comment), Tree(CommentedTree), } impl CommentedGroup { pub fn strip_comments(self) -> Group { Group { delimiter: self.delimiter, token_stream: self.token_stream.strip_comments(), span: self.span, } } } impl<T> Spanned for GenericTokenTree<T> { fn span(&self) -> Span { match self { Self::Punct(punct) => punct.span(), Self::Ident(ident) => ident.span(), Self::Group(group) => group.span(), Self::Literal(literal) => literal.span(), Self::DocComment(doc_comment) => doc_comment.span(), } } } impl Spanned for CommentedTokenTree { fn span(&self) -> Span { match self { Self::Comment(cmt) => cmt.span(), Self::Tree(tt) => tt.span(), } } } impl<T> From<Punct> for GenericTokenTree<T> { fn from(punct: Punct) -> Self { Self::Punct(punct) } } impl<T> From<Ident> for GenericTokenTree<T> { fn from(ident: Ident) -> Self { Self::Ident(ident) } } impl<T> From<GenericGroup<T>> for GenericTokenTree<T> { fn from(group: GenericGroup<T>) -> Self { Self::Group(group) } } impl<T> From<Literal> for GenericTokenTree<T> { fn from(lit: Literal) -> Self { Self::Literal(lit) } } impl<T> From<DocComment> for GenericTokenTree<T> { fn from(doc_comment: DocComment) -> Self { Self::DocComment(doc_comment) } } impl From<Comment> for CommentedTokenTree { fn from(comment: Comment) -> Self { Self::Comment(comment) } } impl From<CommentedTree> for CommentedTokenTree { fn from(tree: CommentedTree) -> Self { Self::Tree(tree) } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] pub struct TokenStream { token_trees: Vec<TokenTree>, full_span: Span, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] pub struct CommentedTokenStream { pub token_trees: Vec<CommentedTokenTree>, pub full_span: Span, } #[extension_trait] impl CharExt for char { fn as_open_delimiter(self) -> Option<Delimiter> { match self { '(' => Some(Delimiter::Parenthesis), '{' => Some(Delimiter::Brace), '[' => Some(Delimiter::Bracket), _ => None, } } fn as_close_delimiter(self) -> Option<Delimiter> { match self { ')' => Some(Delimiter::Parenthesis), '}' => Some(Delimiter::Brace), ']' => Some(Delimiter::Bracket), _ => None, } } fn as_punct_kind(self) -> Option<PunctKind> { match self { ';' => Some(PunctKind::Semicolon), ':' => Some(PunctKind::Colon), '/' => Some(PunctKind::ForwardSlash), ',' => Some(PunctKind::Comma), '*' => Some(PunctKind::Star), '+' => Some(PunctKind::Add), '-' => Some(PunctKind::Sub), '<' => Some(PunctKind::LessThan), '>' => Some(PunctKind::GreaterThan), '=' => Some(PunctKind::Equals), '.' => Some(PunctKind::Dot), '!' => Some(PunctKind::Bang), '%' => Some(PunctKind::Percent), '&' => Some(PunctKind::Ampersand), '^' => Some(PunctKind::Caret), '|' => Some(PunctKind::Pipe), '_' => Some(PunctKind::Underscore), '#' => Some(PunctKind::Sharp), _ => None, } } } impl TokenStream { pub fn token_trees(&self) -> &[TokenTree] { &self.token_trees } } impl Spanned for TokenStream { fn span(&self) -> Span { self.full_span.clone() } } impl CommentedTokenTree { pub fn strip_comments(self) -> Option<TokenTree> { let commented_tt = match self { Self::Comment(_) => return None, Self::Tree(commented_tt) => commented_tt, }; let tt = match commented_tt { CommentedTree::Punct(punct) => punct.into(), CommentedTree::Ident(ident) => ident.into(), CommentedTree::Group(group) => group.strip_comments().into(), CommentedTree::Literal(lit) => lit.into(), CommentedTree::DocComment(doc_comment) => doc_comment.into(), }; Some(tt) } } impl CommentedTokenStream { pub fn token_trees(&self) -> &[CommentedTokenTree] { &self.token_trees } pub fn strip_comments(self) -> TokenStream { let token_trees = self .token_trees .into_iter() .filter_map(|tree| tree.strip_comments()) .collect(); TokenStream { token_trees, full_span: self.full_span, } } } impl Spanned for CommentedTokenStream { fn span(&self) -> Span { self.full_span.clone() } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/expr/asm.rs
sway-ast/src/expr/asm.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub struct AsmBlock { pub asm_token: AsmToken, pub registers: Parens<Punctuated<AsmRegisterDeclaration, CommaToken>>, pub contents: Braces<AsmBlockContents>, } #[derive(Clone, Debug, Serialize)] pub struct AsmRegisterDeclaration { pub register: Ident, pub value_opt: Option<(ColonToken, Box<Expr>)>, } #[derive(Clone, Debug, Serialize)] pub struct AsmBlockContents { pub instructions: Vec<(Instruction, SemicolonToken)>, pub final_expr_opt: Option<AsmFinalExpr>, } #[derive(Clone, Debug, Serialize)] pub struct AsmFinalExpr { pub register: Ident, pub ty_opt: Option<(ColonToken, Ty)>, } #[derive(Clone, Debug, Serialize)] pub struct AsmImmediate { pub span: Span, pub parsed: BigUint, } impl Spanned for AsmImmediate { fn span(&self) -> Span { self.span.clone() } } impl Spanned for AsmBlock { fn span(&self) -> Span { Span::join(self.asm_token.span(), &self.contents.span()) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/expr/op_code.rs
sway-ast/src/expr/op_code.rs
use crate::priv_prelude::*; macro_rules! define_op_code ( ($ty_name:ident, $s:literal) => ( #[derive(Clone, Debug, Serialize)] pub struct $ty_name { span: Span, } impl Spanned for $ty_name { fn span(&self) -> Span { self.span.clone() } } ); ); macro_rules! op_code_ty ( (reg) => { Ident }; (imm) => { AsmImmediate }; ); macro_rules! push_register_arg_idents ( ($vec_name:ident, ()) => {}; ($vec_name:ident, ($arg_name_head:ident: reg, $($arg_name:ident: $arg_ty:tt,)*)) => { $vec_name.push($arg_name_head.clone()); push_register_arg_idents!($vec_name, ($($arg_name: $arg_ty,)*)) }; ($vec_name:ident, ($arg_name_head:ident: imm, $($arg_name:ident: $arg_ty:tt,)*)) => { let _ = $arg_name_head; push_register_arg_idents!($vec_name, ($($arg_name: $arg_ty,)*)) }; ); macro_rules! push_immediate_idents ( ($vec_name:ident, ()) => {}; ($vec_name:ident, ($arg_name_head:ident: reg, $($arg_name:ident: $arg_ty:tt,)*)) => { let _ = $arg_name_head; push_immediate_idents!($vec_name, ($($arg_name: $arg_ty,)*)) }; ($vec_name:ident, ($arg_name_head:ident: imm, $($arg_name:ident: $arg_ty:tt,)*)) => { $vec_name.push(Ident::new($arg_name_head.span())); push_immediate_idents!($vec_name, ($($arg_name: $arg_ty,)*)) }; ); macro_rules! ignore_remaining ( () => {}; ($arg_name_head:ident: $arg_ty_head:tt, $($arg_name:ident: $arg_ty:tt,)*) => {{ let _ = $arg_name_head; ignore_remaining!($($arg_name: $arg_ty,)*); }}; ); macro_rules! immediate_ident_opt ( () => { None }; ($arg_name_head:ident: reg, $($arg_name:ident: $arg_ty:tt,)*) => {{ let _ = $arg_name_head; immediate_ident_opt!($($arg_name: $arg_ty,)*) }}; ($arg_name_head:ident: imm, $($arg_name:ident: $arg_ty:tt,)*) => {{ ignore_remaining!($($arg_name: $arg_ty,)*); Some(Ident::new($arg_name_head.span())) }}; ); macro_rules! get_span ( ($start:expr, ()) => { $start }; ($start:expr, ($arg_name:ident,)) => { Span::join($start, &$arg_name.span()) }; ($start:expr, ($arg_name_head:ident, $($arg_name:ident,)*)) => {{ let _ = $arg_name_head; get_span!($start, ($($arg_name,)*)) }}; ); /// A specific instruction. pub trait Inst { /// The instruction's literal in source code. const LIT: &'static str; /// Arguments to the instruction. type Args; fn instruction(ident: Ident, args: Self::Args) -> Instruction; } macro_rules! define_op_codes ( ($(($op_name:ident, $ty_name:ident, $s:literal, ($($arg_name:ident: $arg_ty:tt),*)),)*) => { $( define_op_code!($ty_name, $s); impl Inst for $ty_name { const LIT: &'static str = $s; type Args = ($(op_code_ty!($arg_ty),)*); fn instruction(ident: Ident, ($($arg_name,)*): Self::Args) -> Instruction { Instruction::$op_name { token: $ty_name { span: ident.span().clone() }, $($arg_name,)* } } } )* #[derive(Clone, Debug, Serialize)] pub enum Instruction { $($op_name { token: $ty_name, $($arg_name: op_code_ty!($arg_ty),)* },)* } impl Instruction { pub fn op_code_ident(&self) -> Ident { match self { $(Instruction::$op_name { token, .. } => { Ident::new(token.span()) },)* } } pub fn op_code_as_str(&self) -> &'static str { match self { $(Instruction::$op_name { .. } => { $s },)* } } #[allow(clippy::vec_init_then_push)] pub fn register_arg_idents(&self) -> Vec<Ident> { match self { $(Instruction::$op_name { $($arg_name,)* .. } => { #[allow(unused_mut)] let mut ret = Vec::new(); push_register_arg_idents!(ret, ($($arg_name: $arg_ty,)*)); ret },)* } } pub fn immediate_ident_opt(&self) -> Option<Ident> { match self { $(Instruction::$op_name { $($arg_name,)* .. } => { immediate_ident_opt!($($arg_name: $arg_ty,)*) },)* } } #[allow(clippy::vec_init_then_push)] pub fn immediate_idents(&self) -> Vec<Ident> { match self { $(Instruction::$op_name { $($arg_name,)* .. } => { #[allow(unused_mut)] let mut ret = Vec::new(); push_immediate_idents!(ret, ($($arg_name: $arg_ty,)*)); ret },)* } } } impl Spanned for Instruction { fn span(&self) -> Span { match self { $(Instruction::$op_name { token, $($arg_name,)* } => { get_span!(token.span(), ($($arg_name,)*)) },)* } } } }; ); define_op_codes!( /* Arithmetic/Logic (ALU) Instructions */ (Add, AddOpcode, "add", (ret: reg, lhs: reg, rhs: reg)), (Addi, AddiOpcode, "addi", (ret: reg, lhs: reg, rhs: imm)), (And, AndOpcode, "and", (ret: reg, lhs: reg, rhs: reg)), (Andi, AndiOpcode, "andi", (ret: reg, lhs: reg, rhs: imm)), (Div, DivOpcode, "div", (ret: reg, lhs: reg, rhs: reg)), (Divi, DiviOpcode, "divi", (ret: reg, lhs: reg, rhs: imm)), (Eq, EqOpcode, "eq", (ret: reg, lhs: reg, rhs: reg)), (Exp, ExpOpcode, "exp", (ret: reg, base: reg, power: reg)), (Expi, ExpiOpcode, "expi", (ret: reg, base: reg, power: imm)), (Gt, GtOpcode, "gt", (ret: reg, lhs: reg, rhs: reg)), (Lt, LtOpcode, "lt", (ret: reg, lhs: reg, rhs: reg)), (Mlog, MlogOpcode, "mlog", (ret: reg, arg: reg, base: reg)), (Mod, ModOpcode, "mod", (ret: reg, lhs: reg, rhs: reg)), (Modi, ModiOpcode, "modi", (ret: reg, lhs: reg, rhs: imm)), (Move, MoveOpcode, "move", (ret: reg, from: reg)), (Movi, MoviOpcode, "movi", (ret: reg, arg: imm)), (Mroo, MrooOpcode, "mroo", (ret: reg, arg: reg, root: reg)), (Mul, MulOpcode, "mul", (ret: reg, lhs: reg, rhs: reg)), (Muli, MuliOpcode, "muli", (ret: reg, lhs: reg, rhs: imm)), (Noop, NoopOpcode, "noop", ()), (Not, NotOpcode, "not", (ret: reg, arg: reg)), (Or, OrOpcode, "or", (ret: reg, lhs: reg, rhs: reg)), (Ori, OriOpcode, "ori", (ret: reg, lhs: reg, rhs: imm)), (Sll, SllOpcode, "sll", (ret: reg, lhs: reg, rhs: reg)), (Slli, SlliOpcode, "slli", (ret: reg, lhs: reg, rhs: imm)), (Srl, SrlOpcode, "srl", (ret: reg, lhs: reg, rhs: reg)), (Srli, SrliOpcode, "srli", (ret: reg, lhs: reg, rhs: imm)), (Sub, SubOpcode, "sub", (ret: reg, lhs: reg, rhs: reg)), (Subi, SubiOpcode, "subi", (ret: reg, lhs: reg, rhs: imm)), (Wqcm, WqcmOpcode, "wqcm", (ret: reg, lhs: reg, rhs: reg, op_mode: imm)), (Wqop, WqopOpcode, "wqop", (ret: reg, lhs: reg, rhs: reg, op_mode: imm)), (Wqml, WqmlOpcode, "wqml", (ret: reg, lhs: reg, rhs: reg, indirect: imm)), (Wqdv, WqdvOpcode, "wqdv", (ret: reg, lhs: reg, rhs: reg, indirect: imm)), (Wqmd, WqmdOpcode, "wqmd", (ret: reg, lhs_a: reg, lhs_b: reg, rhs: reg)), (Wqam, WqamOpcode, "wqam", (ret: reg, lhs_a: reg, lhs_b: reg, rhs: reg)), (Wqmm, WqmmOpcode, "wqmm", (ret: reg, lhs_a: reg, lhs_b: reg, rhs: reg)), (Xor, XorOpcode, "xor", (ret: reg, lhs: reg, rhs: reg)), (Xori, XoriOpcode, "xori", (ret: reg, lhs: reg, rhs: imm)), /* Control Flow Instructions */ (Jmp, JmpOpcode, "jmp", (offset: reg)), (Ji, JiOpcode, "ji", (offset: imm)), (Jne, JneOpcode, "jne", (lhs: reg, rhs: reg, offset: reg)), (Jnei, JneiOpcode, "jnei", (lhs: reg, rhs: reg, offset: imm)), (Jnzi, JnziOpcode, "jnzi", (arg: reg, offset: imm)), (Jmpb, JmpbOpcode, "jmpb", (offset_reg: reg, offset: imm)), (Jmpf, JmpfOpcode, "jmpf", (offset_reg: reg, offset: imm)), (Jnzb, JnzbOpcode, "jnzb", (arg: reg, offset_reg: reg, offset: imm)), (Jnzf, JnzfOpcode, "jnzf", (arg: reg, offset_reg: reg, offset: imm)), (Jneb, JnebOpcode, "jneb", (lhs: reg, rhs: reg, offset_reg: reg, offset: imm)), (Jnef, JnefOpcode, "jnef", (lhs: reg, rhs: reg, offset_reg: reg, offset: imm)), (Jal, JalOpcode, "jal", (addr: reg, offset_reg: reg, offset: imm)), (Ret, RetOpcode, "ret", (value: reg)), /* Memory Instructions */ (Aloc, AlocOpcode, "aloc", (size: reg)), (Cfei, CfeiOpcode, "cfei", (size: imm)), (Cfsi, CfsiOpcode, "cfsi", (size: imm)), (Cfe, CfeOpcode, "cfe", (size: reg)), (Cfs, CfsOpcode, "cfs", (size: reg)), (Lb, LbOpcode, "lb", (ret: reg, addr: reg, offset: imm)), (Lw, LwOpcode, "lw", (ret: reg, addr: reg, offset: imm)), (Mcl, MclOpcode, "mcl", (addr: reg, size: reg)), (Mcli, McliOpcode, "mcli", (addr: reg, size: imm)), ( Mcp, McpOpcode, "mcp", (dst_addr: reg, src_addr: reg, size: reg) ), ( Mcpi, McpiOpcode, "mcpi", (dst_addr: reg, src_addr: reg, size: imm) ), ( Meq, MeqOpcode, "meq", (ret: reg, lhs_addr: reg, rhs_addr: reg, size: reg) ), (Sb, SbOpcode, "sb", (addr: reg, value: reg, offset: imm)), (Sw, SwOpcode, "sw", (addr: reg, value: reg, offset: imm)), /* Contract Instructions */ (Bal, BalOpcode, "bal", (ret: reg, asset: reg, contract: reg)), (Bhei, BheiOpcode, "bhei", (ret: reg)), (Bhsh, BhshOpcode, "bhsh", (addr: reg, height: reg)), (Burn, BurnOpcode, "burn", (coins: reg, sub_id: reg)), ( Call, CallOpcode, "call", (args_addr: reg, coins: reg, asset: reg, gas: reg) ), (Cb, CbOpcode, "cb", (addr: reg)), ( Ccp, CcpOpcode, "ccp", (dst_addr: reg, contract: reg, src_addr: reg, size: reg) ), (Croo, CrooOpcode, "croo", (addr: reg, contract: reg)), (Csiz, CsizOpcode, "csiz", (ret: reg, contract: reg)), (Bsiz, BsizOpcode, "bsiz", (ret: reg, contract: reg)), (Ldc, LdcOpcode, "ldc", (contract: reg, addr: reg, size: reg, mode: imm)), (Bldd, BlddOpcode, "bldd", (dst_ptr: reg, addr: reg, offset: reg, len: reg)), ( Log, LogOpcode, "log", (reg_a: reg, reg_b: reg, reg_c: reg, reg_d: reg) ), ( Logd, LogdOpcode, "logd", (reg_a: reg, reg_b: reg, addr: reg, size: reg) ), (Mint, MintOpcode, "mint", (coins: reg, sub_id: reg)), (Retd, RetdOpcode, "retd", (addr: reg, size: reg)), (Rvrt, RvrtOpcode, "rvrt", (value: reg)), ( Smo, SmoOpcode, "smo", (addr: reg, len: reg, output: reg, coins: reg) ), (Scwq, ScwqOpcode, "scwq", (addr: reg, is_set: reg, len: reg)), ( Srw, SrwOpcode, "srw", (ret: reg, is_set: reg, state_addr: reg) ), ( Srwq, SrwqOpcode, "srwq", (addr: reg, is_set: reg, state_addr: reg, count: reg) ), ( Sww, SwwOpcode, "sww", (state_addr: reg, is_set: reg, value: reg) ), ( Swwq, SwwqOpcode, "swwq", (state_addr: reg, is_set: reg, addr: reg, count: reg) ), (Time, TimeOpcode, "time", (ret: reg, height: reg)), (Tr, TrOpcode, "tr", (contract: reg, coins: reg, asset: reg)), ( Tro, TroOpcode, "tro", (addr: reg, output: reg, coins: reg, asset: reg) ), /* Cryptographic Instructions */ (Eck1, Eck1Opcode, "eck1", (addr: reg, sig: reg, hash: reg)), (Ecr1, Ecr1Opcode, "ecr1", (addr: reg, sig: reg, hash: reg)), (Ed19, Ed19Opcode, "ed19", (addr: reg, sig: reg, hash: reg, len: reg)), (K256, K256Opcode, "k256", (addr: reg, data: reg, size: reg)), (S256, S256Opcode, "s256", (addr: reg, data: reg, size: reg)), (ECOP, ECOPOpcode, "ecop", (dst_addr: reg, curve: reg, operation: reg, src_addr: reg)), (EPAR, EPAROpcode, "epar", (ret: reg, curve: reg, groups_of_points: reg, addr: reg)), /* Other Instructions */ (Ecal, EcalOpcode, "ecal", (reg_a: reg, reg_b: reg, reg_c: reg, reg_d: reg)), (Flag, FlagOpcode, "flag", (value: reg)), (Gm, GmOpcode, "gm", (ret: reg, op: imm)), ( Gtf, GtfOpcode, "gtf", (ret: reg, index: reg, tx_field_id: imm) ), /* Non-VM Instructions */ (Blob, BlobOpcode, "blob", (size: imm)), );
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/expr/mod.rs
sway-ast/src/expr/mod.rs
use sway_error::handler::ErrorEmitted; use crate::{assignable::ElementAccess, priv_prelude::*, PathExprSegment}; pub mod asm; pub mod op_code; #[derive(Clone, Debug, Serialize)] pub enum Expr { /// A malformed expression. /// /// Used for parser recovery when we cannot form a more specific node. Error(Box<[Span]>, #[serde(skip_serializing)] ErrorEmitted), Path(PathExpr), Literal(Literal), AbiCast { abi_token: AbiToken, args: Parens<AbiCastArgs>, }, Struct { path: PathExpr, fields: Braces<Punctuated<ExprStructField, CommaToken>>, }, Tuple(Parens<ExprTupleDescriptor>), Parens(Parens<Box<Expr>>), Block(Braces<CodeBlockContents>), Array(SquareBrackets<ExprArrayDescriptor>), Asm(AsmBlock), Return { return_token: ReturnToken, expr_opt: Option<Box<Expr>>, }, Panic { panic_token: PanicToken, expr_opt: Option<Box<Expr>>, }, If(IfExpr), Match { match_token: MatchToken, value: Box<Expr>, branches: Braces<Vec<MatchBranch>>, }, While { while_token: WhileToken, condition: Box<Expr>, block: Braces<CodeBlockContents>, }, For { for_token: ForToken, in_token: InToken, value_pattern: Pattern, iterator: Box<Expr>, block: Braces<CodeBlockContents>, }, FuncApp { func: Box<Expr>, args: Parens<Punctuated<Expr, CommaToken>>, }, Index { target: Box<Expr>, arg: SquareBrackets<Box<Expr>>, }, MethodCall { target: Box<Expr>, dot_token: DotToken, path_seg: PathExprSegment, contract_args_opt: Option<Braces<Punctuated<ExprStructField, CommaToken>>>, args: Parens<Punctuated<Expr, CommaToken>>, }, FieldProjection { target: Box<Expr>, dot_token: DotToken, name: Ident, }, TupleFieldProjection { target: Box<Expr>, dot_token: DotToken, field: BigUint, field_span: Span, }, Ref { ampersand_token: AmpersandToken, mut_token: Option<MutToken>, expr: Box<Expr>, }, Deref { star_token: StarToken, expr: Box<Expr>, }, Not { bang_token: BangToken, expr: Box<Expr>, }, Mul { lhs: Box<Expr>, star_token: StarToken, rhs: Box<Expr>, }, Div { lhs: Box<Expr>, forward_slash_token: ForwardSlashToken, rhs: Box<Expr>, }, Pow { lhs: Box<Expr>, double_star_token: DoubleStarToken, rhs: Box<Expr>, }, Modulo { lhs: Box<Expr>, percent_token: PercentToken, rhs: Box<Expr>, }, Add { lhs: Box<Expr>, add_token: AddToken, rhs: Box<Expr>, }, Sub { lhs: Box<Expr>, sub_token: SubToken, rhs: Box<Expr>, }, Shl { lhs: Box<Expr>, shl_token: ShlToken, rhs: Box<Expr>, }, Shr { lhs: Box<Expr>, shr_token: ShrToken, rhs: Box<Expr>, }, BitAnd { lhs: Box<Expr>, ampersand_token: AmpersandToken, rhs: Box<Expr>, }, BitXor { lhs: Box<Expr>, caret_token: CaretToken, rhs: Box<Expr>, }, BitOr { lhs: Box<Expr>, pipe_token: PipeToken, rhs: Box<Expr>, }, Equal { lhs: Box<Expr>, double_eq_token: DoubleEqToken, rhs: Box<Expr>, }, NotEqual { lhs: Box<Expr>, bang_eq_token: BangEqToken, rhs: Box<Expr>, }, LessThan { lhs: Box<Expr>, less_than_token: LessThanToken, rhs: Box<Expr>, }, GreaterThan { lhs: Box<Expr>, greater_than_token: GreaterThanToken, rhs: Box<Expr>, }, LessThanEq { lhs: Box<Expr>, less_than_eq_token: LessThanEqToken, rhs: Box<Expr>, }, GreaterThanEq { lhs: Box<Expr>, greater_than_eq_token: GreaterThanEqToken, rhs: Box<Expr>, }, LogicalAnd { lhs: Box<Expr>, double_ampersand_token: DoubleAmpersandToken, rhs: Box<Expr>, }, LogicalOr { lhs: Box<Expr>, double_pipe_token: DoublePipeToken, rhs: Box<Expr>, }, Reassignment { assignable: Assignable, reassignment_op: ReassignmentOp, expr: Box<Expr>, }, Break { break_token: BreakToken, }, Continue { continue_token: ContinueToken, }, } impl Spanned for Expr { fn span(&self) -> Span { match self { Expr::Error(spans, _) => spans .iter() .cloned() .reduce(|s1: Span, s2: Span| Span::join(s1, &s2)) .unwrap(), Expr::Path(path_expr) => path_expr.span(), Expr::Literal(literal) => literal.span(), Expr::AbiCast { abi_token, args } => Span::join(abi_token.span(), &args.span()), Expr::Struct { path, fields } => Span::join(path.span(), &fields.span()), Expr::Tuple(tuple_expr) => tuple_expr.span(), Expr::Parens(parens) => parens.span(), Expr::Block(block_expr) => block_expr.span(), Expr::Array(array_expr) => array_expr.span(), Expr::Asm(asm_block) => asm_block.span(), Expr::Return { return_token, expr_opt, } => { let start = return_token.span(); let end = match expr_opt { Some(expr) => expr.span(), None => return_token.span(), }; Span::join(start, &end) } Expr::Panic { panic_token, expr_opt, } => { let start = panic_token.span(); let end = match expr_opt { Some(expr) => expr.span(), None => panic_token.span(), }; Span::join(start, &end) } Expr::If(if_expr) => if_expr.span(), Expr::Match { match_token, branches, .. } => Span::join(match_token.span(), &branches.span()), Expr::While { while_token, block, .. } => Span::join(while_token.span(), &block.span()), Expr::For { for_token, block, .. } => Span::join(for_token.span(), &block.span()), Expr::FuncApp { func, args } => Span::join(func.span(), &args.span()), Expr::Index { target, arg } => Span::join(target.span(), &arg.span()), Expr::MethodCall { target, args, .. } => Span::join(target.span(), &args.span()), Expr::FieldProjection { target, name, .. } => Span::join(target.span(), &name.span()), Expr::TupleFieldProjection { target, field_span, .. } => Span::join(target.span(), field_span), Expr::Ref { ampersand_token, expr, .. } => Span::join(ampersand_token.span(), &expr.span()), Expr::Deref { star_token, expr } => Span::join(star_token.span(), &expr.span()), Expr::Not { bang_token, expr } => Span::join(bang_token.span(), &expr.span()), Expr::Pow { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::Mul { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::Div { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::Modulo { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::Add { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::Sub { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::Shl { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::Shr { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::BitAnd { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::BitXor { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::BitOr { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::Equal { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::NotEqual { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::LessThan { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::GreaterThan { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::LessThanEq { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::GreaterThanEq { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::LogicalAnd { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::LogicalOr { lhs, rhs, .. } => Span::join(lhs.span(), &rhs.span()), Expr::Reassignment { assignable, expr, .. } => Span::join(assignable.span(), &expr.span()), Expr::Break { break_token } => break_token.span(), Expr::Continue { continue_token } => continue_token.span(), } } } #[derive(Clone, Debug, Serialize)] pub struct ReassignmentOp { pub variant: ReassignmentOpVariant, pub span: Span, } #[derive(Clone, Debug, Serialize)] pub enum ReassignmentOpVariant { Equals, AddEquals, SubEquals, MulEquals, DivEquals, ShlEquals, ShrEquals, } impl ReassignmentOpVariant { pub fn std_name(&self) -> &'static str { match self { ReassignmentOpVariant::Equals => "eq", ReassignmentOpVariant::AddEquals => "add", ReassignmentOpVariant::SubEquals => "subtract", ReassignmentOpVariant::MulEquals => "multiply", ReassignmentOpVariant::DivEquals => "divide", ReassignmentOpVariant::ShlEquals => "lsh", ReassignmentOpVariant::ShrEquals => "rsh", } } pub fn as_str(&self) -> &'static str { match self { ReassignmentOpVariant::Equals => EqToken::AS_STR, ReassignmentOpVariant::AddEquals => AddEqToken::AS_STR, ReassignmentOpVariant::SubEquals => SubEqToken::AS_STR, ReassignmentOpVariant::MulEquals => StarEqToken::AS_STR, ReassignmentOpVariant::DivEquals => DivEqToken::AS_STR, ReassignmentOpVariant::ShlEquals => ShlEqToken::AS_STR, ReassignmentOpVariant::ShrEquals => ShrEqToken::AS_STR, } } } #[derive(Clone, Debug, Serialize)] pub struct AbiCastArgs { pub name: PathType, pub comma_token: CommaToken, pub address: Box<Expr>, } #[allow(clippy::type_complexity)] #[derive(Clone, Debug, Serialize)] pub struct IfExpr { pub if_token: IfToken, pub condition: IfCondition, pub then_block: Braces<CodeBlockContents>, pub else_opt: Option<( ElseToken, LoopControlFlow<Braces<CodeBlockContents>, Box<IfExpr>>, )>, } #[derive(Clone, Debug, Serialize)] pub enum IfCondition { Expr(Box<Expr>), Let { let_token: LetToken, lhs: Box<Pattern>, eq_token: EqToken, rhs: Box<Expr>, }, } #[derive(Clone, Debug, Serialize)] pub enum LoopControlFlow<B, C = ()> { Continue(C), Break(B), } impl Spanned for IfExpr { fn span(&self) -> Span { let start = self.if_token.span(); let end = match &self.else_opt { Some((_else_token, tail)) => match tail { LoopControlFlow::Break(block) => block.span(), LoopControlFlow::Continue(if_expr) => if_expr.span(), }, None => self.then_block.span(), }; Span::join(start, &end) } } #[derive(Clone, Debug, Serialize)] pub enum ExprTupleDescriptor { Nil, Cons { head: Box<Expr>, comma_token: CommaToken, tail: Punctuated<Expr, CommaToken>, }, } #[derive(Clone, Debug, Serialize)] pub enum ExprArrayDescriptor { Sequence(Punctuated<Expr, CommaToken>), Repeat { value: Box<Expr>, semicolon_token: SemicolonToken, length: Box<Expr>, }, } #[derive(Clone, Debug, Serialize)] pub struct MatchBranch { pub pattern: Pattern, pub fat_right_arrow_token: FatRightArrowToken, pub kind: MatchBranchKind, } impl Spanned for MatchBranch { fn span(&self) -> Span { Span::join(self.pattern.span(), &self.kind.span()) } } #[allow(clippy::large_enum_variant)] #[derive(Debug, Clone, Serialize)] pub enum MatchBranchKind { Block { block: Braces<CodeBlockContents>, comma_token_opt: Option<CommaToken>, }, Expr { expr: Expr, comma_token: CommaToken, }, } impl Spanned for MatchBranchKind { fn span(&self) -> Span { match self { MatchBranchKind::Block { block, comma_token_opt, } => match comma_token_opt { Some(comma_token) => Span::join(block.span(), &comma_token.span()), None => block.span(), }, MatchBranchKind::Expr { expr, comma_token } => { Span::join(expr.span(), &comma_token.span()) } } } } #[derive(Clone, Debug, Serialize)] pub struct CodeBlockContents { pub statements: Vec<Statement>, pub final_expr_opt: Option<Box<Expr>>, pub span: Span, } impl Spanned for CodeBlockContents { fn span(&self) -> Span { self.span.clone() } } #[derive(Clone, Debug, Serialize)] pub struct ExprStructField { pub field_name: Ident, pub expr_opt: Option<(ColonToken, Box<Expr>)>, } impl Spanned for ExprStructField { fn span(&self) -> Span { match &self.expr_opt { None => self.field_name.span(), Some((_colon_token, expr)) => Span::join(self.field_name.span(), &expr.span()), } } } impl Expr { /// Returns the resulting [Assignable] if the `self` is a /// valid [Assignable], or an error containing the [Expr] /// which causes the `self` to be an invalid [Assignable]. /// /// In case of an error, the returned [Expr] can be `self` /// or any subexpression of `self` that is not allowed /// in assignment targets. #[allow(clippy::result_large_err)] pub fn try_into_assignable(self) -> Result<Assignable, Expr> { if let Expr::Deref { star_token, expr } = self { Ok(Assignable::Deref { star_token, expr }) } else { Ok(Assignable::ElementAccess( self.try_into_element_access(false)?, )) } } #[allow(clippy::result_large_err)] fn try_into_element_access( self, accept_deref_without_parens: bool, ) -> Result<ElementAccess, Expr> { match self.clone() { Expr::Path(path_expr) => match path_expr.try_into_ident() { Ok(name) => Ok(ElementAccess::Var(name)), Err(path_expr) => Err(Expr::Path(path_expr)), }, Expr::Index { target, arg } => match target.try_into_element_access(false) { Ok(target) => Ok(ElementAccess::Index { target: Box::new(target), arg, }), error => error, }, Expr::FieldProjection { target, dot_token, name, } => match target.try_into_element_access(false) { Ok(target) => Ok(ElementAccess::FieldProjection { target: Box::new(target), dot_token, name, }), error => error, }, Expr::TupleFieldProjection { target, dot_token, field, field_span, } => match target.try_into_element_access(false) { Ok(target) => Ok(ElementAccess::TupleFieldProjection { target: Box::new(target), dot_token, field, field_span, }), error => error, }, Expr::Parens(Parens { inner, .. }) => { if let Expr::Deref { expr, star_token } = *inner { match expr.try_into_element_access(true) { Ok(target) => Ok(ElementAccess::Deref { target: Box::new(target), star_token, is_root_element: true, }), error => error, } } else { Err(self) } } Expr::Deref { expr, star_token } if accept_deref_without_parens => { match expr.try_into_element_access(true) { Ok(target) => Ok(ElementAccess::Deref { target: Box::new(target), star_token, is_root_element: false, }), error => error, } } expr => Err(expr), } } pub fn is_control_flow(&self) -> bool { match self { Expr::Block(..) | Expr::Asm(..) | Expr::If(..) | Expr::Match { .. } | Expr::While { .. } | Expr::For { .. } => true, Expr::Error(..) | Expr::Path(..) | Expr::Literal(..) | Expr::AbiCast { .. } | Expr::Struct { .. } | Expr::Tuple(..) | Expr::Parens(..) | Expr::Array(..) | Expr::Return { .. } | Expr::Panic { .. } | Expr::FuncApp { .. } | Expr::Index { .. } | Expr::MethodCall { .. } | Expr::FieldProjection { .. } | Expr::TupleFieldProjection { .. } | Expr::Ref { .. } | Expr::Deref { .. } | Expr::Not { .. } | Expr::Mul { .. } | Expr::Div { .. } | Expr::Pow { .. } | Expr::Modulo { .. } | Expr::Add { .. } | Expr::Sub { .. } | Expr::Shl { .. } | Expr::Shr { .. } | Expr::BitAnd { .. } | Expr::BitXor { .. } | Expr::BitOr { .. } | Expr::Equal { .. } | Expr::NotEqual { .. } | Expr::LessThan { .. } | Expr::GreaterThan { .. } | Expr::LessThanEq { .. } | Expr::GreaterThanEq { .. } | Expr::LogicalAnd { .. } | Expr::LogicalOr { .. } | Expr::Reassignment { .. } | Expr::Break { .. } | Expr::Continue { .. } => false, } } /// Friendly [Expr] name string used for error reporting, pub fn friendly_name(&self) -> &'static str { match self { Expr::Error(_, _) => "error", Expr::Path(_) => "path", Expr::Literal(_) => "literal", Expr::AbiCast { .. } => "ABI cast", Expr::Struct { .. } => "struct instantiation", Expr::Tuple(_) => "tuple", Expr::Parens(_) => "parentheses", // Note the plural! Expr::Block(_) => "block", Expr::Array(_) => "array", Expr::Asm(_) => "assembly block", Expr::Return { .. } => "return", Expr::Panic { .. } => "panic", Expr::If(_) => "if expression", Expr::Match { .. } => "match expression", Expr::While { .. } => "while loop", Expr::For { .. } => "for loop", Expr::FuncApp { .. } => "function call", Expr::Index { .. } => "array element access", Expr::MethodCall { .. } => "method call", Expr::FieldProjection { .. } => "struct field access", Expr::TupleFieldProjection { .. } => "tuple element access", Expr::Ref { .. } => "referencing", Expr::Deref { .. } => "dereferencing", Expr::Not { .. } => "negation", Expr::Mul { .. } => "multiplication", Expr::Div { .. } => "division", Expr::Pow { .. } => "power operation", Expr::Modulo { .. } => "modulo operation", Expr::Add { .. } => "addition", Expr::Sub { .. } => "subtraction", Expr::Shl { .. } => "left shift", Expr::Shr { .. } => "right shift", Expr::BitAnd { .. } => "bitwise and", Expr::BitXor { .. } => "bitwise xor", Expr::BitOr { .. } => "bitwise or", Expr::Equal { .. } => "equality", Expr::NotEqual { .. } => "non equality", Expr::LessThan { .. } => "less than operation", Expr::GreaterThan { .. } => "greater than operation", Expr::LessThanEq { .. } => "less than or equal operation", Expr::GreaterThanEq { .. } => "greater than or equal operation", Expr::LogicalAnd { .. } => "logical and", Expr::LogicalOr { .. } => "logical or", Expr::Reassignment { .. } => "reassignment", Expr::Break { .. } => "break", Expr::Continue { .. } => "continue", } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/ty/mod.rs
sway-ast/src/ty/mod.rs
use crate::priv_prelude::*; #[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, Serialize)] pub enum Ty { Path(PathType), Tuple(Parens<TyTupleDescriptor>), Array(SquareBrackets<TyArrayDescriptor>), StringSlice(StrToken), StringArray { str_token: StrToken, length: SquareBrackets<Box<Expr>>, }, Infer { underscore_token: UnderscoreToken, }, Ptr { ptr_token: PtrToken, ty: SquareBrackets<Box<Ty>>, }, Slice { slice_token: Option<SliceToken>, ty: SquareBrackets<Box<Ty>>, }, Ref { ampersand_token: AmpersandToken, mut_token: Option<MutToken>, ty: Box<Ty>, }, Never { bang_token: BangToken, }, Expr(Box<Expr>), } impl Spanned for Ty { fn span(&self) -> Span { match self { Ty::Path(path_type) => path_type.span(), Ty::Tuple(tuple_type) => tuple_type.span(), Ty::Array(array_type) => array_type.span(), Ty::StringSlice(str_token) => str_token.span(), Ty::StringArray { str_token, length } => Span::join(str_token.span(), &length.span()), Ty::Infer { underscore_token } => underscore_token.span(), Ty::Ptr { ptr_token, ty } => Span::join(ptr_token.span(), &ty.span()), Ty::Slice { slice_token, ty } => { let span = slice_token .as_ref() .map(|s| Span::join(s.span(), &ty.span())); span.unwrap_or_else(|| ty.span()) } Ty::Ref { ampersand_token, mut_token: _, ty, } => Span::join(ampersand_token.span(), &ty.span()), Ty::Never { bang_token } => bang_token.span(), Ty::Expr(expr) => expr.span(), } } } impl Ty { pub fn name_span(&self) -> Option<Span> { if let Ty::Path(path_type) = self { Some(path_type.last_segment().name.span()) } else { None } } } #[derive(Clone, Debug, Serialize)] pub enum TyTupleDescriptor { Nil, Cons { head: Box<Ty>, comma_token: CommaToken, tail: Punctuated<Ty, CommaToken>, }, } impl TyTupleDescriptor { pub fn to_tys(self) -> Vec<Ty> { match self { TyTupleDescriptor::Nil => vec![], TyTupleDescriptor::Cons { head, tail, .. } => { let mut tys = vec![*head]; for ty in tail.into_iter() { tys.push(ty); } tys } } } } #[derive(Clone, Debug, Serialize)] pub struct TyArrayDescriptor { pub ty: Box<Ty>, pub semicolon_token: SemicolonToken, pub length: Box<Expr>, }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/item_abi.rs
sway-ast/src/item/item_abi.rs
use crate::{priv_prelude::*, ItemTraitItem}; #[derive(Clone, Debug, Serialize)] pub struct ItemAbi { pub abi_token: AbiToken, pub name: Ident, pub super_traits: Option<(ColonToken, Traits)>, pub abi_items: Braces<Vec<Annotated<ItemTraitItem>>>, pub abi_defs_opt: Option<Braces<Vec<Annotated<ItemFn>>>>, } impl Spanned for ItemAbi { fn span(&self) -> Span { let start = self.abi_token.span(); let end = match &self.abi_defs_opt { Some(abi_defs) => abi_defs.span(), None => self.abi_items.span(), }; Span::join(start, &end) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/item_storage.rs
sway-ast/src/item/item_storage.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub struct ItemStorage { pub storage_token: StorageToken, pub entries: Braces<Punctuated<Annotated<StorageEntry>, CommaToken>>, } impl Spanned for ItemStorage { fn span(&self) -> Span { Span::join(self.storage_token.span(), &self.entries.span()) } } #[derive(Clone, Debug, Serialize)] pub struct StorageEntry { pub name: Ident, pub namespace: Option<Braces<Punctuated<Annotated<Box<StorageEntry>>, CommaToken>>>, pub field: Option<StorageField>, } impl StorageEntry { /// Friendly name of the [StorageEntry] kind, namespace or field, /// used for various reportings. pub fn friendly_kind_name(&self) -> &'static str { if self.namespace.is_some() { "storage namespace" } else { "storage field" } } } impl Spanned for StorageEntry { fn span(&self) -> Span { if let Some(namespace) = &self.namespace { Span::join(self.name.span(), &namespace.span()) } else if let Some(field) = &self.field { Span::join(self.name.span(), &field.span()) } else { self.name.span() } } } #[derive(Clone, Debug, Serialize)] pub struct StorageField { pub name: Ident, pub in_token: Option<InToken>, pub key_expr: Option<Expr>, pub colon_token: ColonToken, pub ty: Ty, pub eq_token: EqToken, pub initializer: Expr, } impl Spanned for StorageField { fn span(&self) -> Span { Span::join_all([ self.name.span(), self.colon_token.span(), self.ty.span(), self.eq_token.span(), self.initializer.span(), ]) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/item_enum.rs
sway-ast/src/item/item_enum.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub struct ItemEnum { pub visibility: Option<PubToken>, pub enum_token: EnumToken, pub name: Ident, pub generics: Option<GenericParams>, pub where_clause_opt: Option<WhereClause>, pub fields: Braces<Punctuated<Annotated<TypeField>, CommaToken>>, } impl Spanned for ItemEnum { fn span(&self) -> Span { let start = match &self.visibility { Some(pub_token) => pub_token.span(), None => self.enum_token.span(), }; let end = self.fields.span(); Span::join(start, &end) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/item_type_alias.rs
sway-ast/src/item/item_type_alias.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub struct ItemTypeAlias { pub visibility: Option<PubToken>, pub name: Ident, pub type_token: TypeToken, pub eq_token: EqToken, pub ty: Ty, pub semicolon_token: SemicolonToken, } impl Spanned for ItemTypeAlias { fn span(&self) -> Span { let start = self.type_token.span(); let end = self.semicolon_token.span(); Span::join(start, &end) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/item_const.rs
sway-ast/src/item/item_const.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub struct ItemConst { pub pub_token: Option<PubToken>, pub const_token: ConstToken, pub name: Ident, pub ty_opt: Option<(ColonToken, Ty)>, pub eq_token_opt: Option<EqToken>, pub expr_opt: Option<Expr>, pub semicolon_token: SemicolonToken, } impl Spanned for ItemConst { fn span(&self) -> Span { let start = match &self.pub_token { Some(pub_token) => pub_token.span(), None => self.const_token.span(), }; let end = match &self.expr_opt { Some(expr) => expr.span(), None => match &self.ty_opt { Some((_colon, ty)) => ty.span(), None => self.name.span(), }, }; Span::join(start, &end) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/item_configurable.rs
sway-ast/src/item/item_configurable.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub struct ItemConfigurable { pub configurable_token: ConfigurableToken, pub fields: Braces<Punctuated<Annotated<ConfigurableField>, CommaToken>>, } impl Spanned for ItemConfigurable { fn span(&self) -> Span { Span::join(self.configurable_token.span(), &self.fields.span()) } } #[derive(Clone, Debug, Serialize)] pub struct ConfigurableField { pub name: Ident, pub colon_token: ColonToken, pub ty: Ty, pub eq_token: EqToken, pub initializer: Expr, } impl Spanned for ConfigurableField { fn span(&self) -> Span { Span::join_all([ self.name.span(), self.colon_token.span(), self.ty.span(), self.eq_token.span(), self.initializer.span(), ]) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/item_struct.rs
sway-ast/src/item/item_struct.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub struct ItemStruct { pub visibility: Option<PubToken>, pub struct_token: StructToken, pub name: Ident, pub generics: Option<GenericParams>, pub where_clause_opt: Option<WhereClause>, pub fields: Braces<Punctuated<Annotated<TypeField>, CommaToken>>, } impl Spanned for ItemStruct { fn span(&self) -> Span { let start = match &self.visibility { Some(pub_token) => pub_token.span(), None => self.struct_token.span(), }; let end = self.fields.span(); Span::join(start, &end) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/mod.rs
sway-ast/src/item/mod.rs
use sway_error::handler::ErrorEmitted; use crate::priv_prelude::*; pub mod item_abi; pub mod item_configurable; pub mod item_const; pub mod item_enum; pub mod item_fn; pub mod item_impl; pub mod item_storage; pub mod item_struct; pub mod item_trait; pub mod item_type_alias; pub mod item_use; pub type Item = Annotated<ItemKind>; impl Spanned for Item { fn span(&self) -> Span { match self.attributes.first() { Some(attr0) => Span::join(attr0.span(), &self.value.span()), None => self.value.span(), } } } #[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, Serialize)] pub enum ItemKind { Submodule(Submodule), Use(ItemUse), Struct(ItemStruct), Enum(ItemEnum), Fn(ItemFn), Trait(ItemTrait), Impl(ItemImpl), Abi(ItemAbi), Const(ItemConst), Storage(ItemStorage), Configurable(ItemConfigurable), TypeAlias(ItemTypeAlias), // to handle parser recovery: Error represents an incomplete item Error(Box<[Span]>, #[serde(skip_serializing)] ErrorEmitted), } impl ItemKind { /// [ItemKind]'s friendly name string used for various reportings. /// /// Note that all friendly names are lowercase. /// This is also the case for names containing acronyms like ABI. /// For contexts in which acronyms need to be uppercase, like /// e.g., error reporting, use `friendly_name_with_acronym` instead. pub fn friendly_name(&self) -> &'static str { use ItemKind::*; match self { Submodule(_) => "submodule (`mod`)", Use(_) => "import (`use`)", Struct(_) => "struct declaration", Enum(_) => "enum declaration", Fn(_) => "function declaration", Trait(_) => "trait declaration", Impl(item_impl) => match item_impl.trait_opt { Some(_) => "ABI or trait implementation", None => "inherent implementation", }, Abi(_) => "abi declaration", Const(_) => "constant declaration", Storage(_) => "contract storage declaration", Configurable(_) => "configurable declaration", TypeAlias(_) => "type alias declaration", Error(..) => "error", } } pub fn friendly_name_with_acronym(&self) -> &'static str { match self.friendly_name() { "abi declaration" => "ABI declaration", friendly_name => friendly_name, } } } impl Spanned for ItemKind { fn span(&self) -> Span { match self { ItemKind::Submodule(item_mod) => item_mod.span(), ItemKind::Use(item_use) => item_use.span(), ItemKind::Struct(item_struct) => item_struct.span(), ItemKind::Enum(item_enum) => item_enum.span(), ItemKind::Fn(item_fn) => item_fn.span(), ItemKind::Trait(item_trait) => item_trait.span(), ItemKind::Impl(item_impl) => item_impl.span(), ItemKind::Abi(item_abi) => item_abi.span(), ItemKind::Const(item_const) => item_const.span(), ItemKind::Storage(item_storage) => item_storage.span(), ItemKind::Configurable(item_configurable) => item_configurable.span(), ItemKind::TypeAlias(item_type_alias) => item_type_alias.span(), ItemKind::Error(spans, _) => Span::join_all(spans.iter().cloned()), } } } #[derive(Clone, Debug, Serialize)] pub struct TypeField { pub visibility: Option<PubToken>, pub name: Ident, pub colon_token: ColonToken, pub ty: Ty, } impl Spanned for TypeField { fn span(&self) -> Span { let start = match &self.visibility { Some(pub_token) => pub_token.span(), None => self.name.span(), }; let end = self.ty.span(); Span::join(start, &end) } } #[derive(Clone, Debug, Serialize)] pub enum FnArgs { Static(Punctuated<FnArg, CommaToken>), NonStatic { self_token: SelfToken, ref_self: Option<RefToken>, mutable_self: Option<MutToken>, args_opt: Option<(CommaToken, Punctuated<FnArg, CommaToken>)>, }, } impl FnArgs { /// Returns all the [FnArg]s, from the function signature defined by `self`. /// /// If the `self` is [FnArgs::NonStatic], the first `self` argument is not /// returned, because it is not an [FnArg]. pub fn args(&self) -> Vec<&FnArg> { match self { Self::Static(punctuated) => punctuated.iter().collect(), Self::NonStatic { args_opt, .. } => args_opt .as_ref() .map_or(vec![], |(_comma_token, punctuated)| { punctuated.iter().collect() }), } } /// Returns all the [FnArg]s, from the function signature defined by `self`. /// /// If the `self` is [FnArgs::NonStatic], the first `self` argument is not /// returned, because it is not an [FnArg]. pub fn args_mut(&mut self) -> Vec<&mut FnArg> { match self { Self::Static(punctuated) => punctuated.iter_mut().collect(), Self::NonStatic { args_opt, .. } => args_opt .as_mut() .map_or(vec![], |(_comma_token, punctuated)| { punctuated.iter_mut().collect() }), } } } #[derive(Clone, Debug, Serialize)] pub struct FnArg { pub pattern: Pattern, pub colon_token: ColonToken, pub ty: Ty, } impl Spanned for FnArg { fn span(&self) -> Span { Span::join(self.pattern.span(), &self.ty.span()) } } #[derive(Clone, Debug, Serialize)] pub struct FnSignature { pub visibility: Option<PubToken>, pub fn_token: FnToken, pub name: Ident, pub generics: Option<GenericParams>, pub arguments: Parens<FnArgs>, pub return_type_opt: Option<(RightArrowToken, Ty)>, pub where_clause_opt: Option<WhereClause>, } impl Spanned for FnSignature { fn span(&self) -> Span { let start = match &self.visibility { Some(pub_token) => pub_token.span(), None => self.fn_token.span(), }; let end = match &self.where_clause_opt { Some(where_clause) => where_clause.span(), None => match &self.return_type_opt { Some((_right_arrow, ty)) => ty.span(), None => self.arguments.span(), }, }; Span::join(start, &end) } } #[derive(Clone, Debug, Serialize)] pub struct TraitType { pub name: Ident, pub type_token: TypeToken, pub eq_token_opt: Option<EqToken>, pub ty_opt: Option<Ty>, pub semicolon_token: SemicolonToken, } impl Spanned for TraitType { fn span(&self) -> Span { let start = self.type_token.span(); let end = match &self.ty_opt { Some(ty_opt) => ty_opt.span(), None => self.name.span(), }; Span::join(start, &end) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/item_trait.rs
sway-ast/src/item/item_trait.rs
use sway_error::handler::ErrorEmitted; use crate::priv_prelude::*; #[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, Serialize)] pub enum ItemTraitItem { Fn(FnSignature, Option<SemicolonToken>), Const(ItemConst, Option<SemicolonToken>), Type(TraitType, Option<SemicolonToken>), // to handle parser recovery: Error represents an incomplete trait item Error(Box<[Span]>, #[serde(skip_serializing)] ErrorEmitted), } impl ItemTraitItem { /// [ItemTraitItem]'s friendly name string used for various reportings. pub fn friendly_name(&self) -> &'static str { use ItemTraitItem::*; match self { Fn(..) => "function signature", Const(..) => "associated constant", Type(..) => "associated type", Error(..) => "error", } } } #[derive(Clone, Debug, Serialize)] pub struct ItemTrait { pub visibility: Option<PubToken>, pub trait_token: TraitToken, pub name: Ident, pub generics: Option<GenericParams>, pub where_clause_opt: Option<WhereClause>, pub super_traits: Option<(ColonToken, Traits)>, pub trait_items: Braces<Vec<Annotated<ItemTraitItem>>>, pub trait_defs_opt: Option<Braces<Vec<Annotated<ItemFn>>>>, } impl Spanned for ItemTrait { fn span(&self) -> Span { let start = match &self.visibility { Some(pub_token) => pub_token.span(), None => self.trait_token.span(), }; let end = match &self.trait_defs_opt { Some(trait_defs) => trait_defs.span(), None => self.trait_items.span(), }; Span::join(start, &end) } } impl Spanned for ItemTraitItem { fn span(&self) -> Span { match self { ItemTraitItem::Fn(fn_decl, semicolon) => match semicolon.as_ref().map(|x| x.span()) { Some(semicolon) => Span::join(fn_decl.span(), &semicolon), None => fn_decl.span(), }, ItemTraitItem::Const(const_decl, semicolon) => { match semicolon.as_ref().map(|x| x.span()) { Some(semicolon) => Span::join(const_decl.span(), &semicolon), None => const_decl.span(), } } ItemTraitItem::Type(type_decl, semicolon) => { match semicolon.as_ref().map(|x| x.span()) { Some(semicolon) => Span::join(type_decl.span(), &semicolon), None => type_decl.span(), } } ItemTraitItem::Error(spans, _) => Span::join_all(spans.iter().cloned()), } } } #[derive(Clone, Debug, Serialize)] pub struct Traits { pub prefix: PathType, pub suffixes: Vec<(AddToken, PathType)>, } impl Traits { pub fn iter(&self) -> impl Iterator<Item = &PathType> { vec![&self.prefix] .into_iter() .chain(self.suffixes.iter().map(|(_add_token, path)| path)) } pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut PathType> { vec![&mut self.prefix] .into_iter() .chain(self.suffixes.iter_mut().map(|(_add_token, path)| path)) } } impl Spanned for Traits { fn span(&self) -> Span { match self.suffixes.last() { Some((_add_token, path_type)) => Span::join(self.prefix.span(), &path_type.span()), None => self.prefix.span(), } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/item_use.rs
sway-ast/src/item/item_use.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub struct ItemUse { pub visibility: Option<PubToken>, pub use_token: UseToken, pub root_import: Option<DoubleColonToken>, pub tree: UseTree, pub semicolon_token: SemicolonToken, } impl Spanned for ItemUse { fn span(&self) -> Span { let start = match &self.visibility { Some(pub_token) => pub_token.span(), None => self.use_token.span(), }; let end = self.semicolon_token.span(); Span::join(start, &end) } } #[derive(Clone, Debug, Serialize)] pub enum UseTree { Group { imports: Braces<Punctuated<UseTree, CommaToken>>, }, Name { name: Ident, }, Rename { name: Ident, as_token: AsToken, alias: Ident, }, Glob { star_token: StarToken, }, Path { prefix: Ident, double_colon_token: DoubleColonToken, suffix: Box<UseTree>, }, // to handle parsing recovery, e.g. foo:: Error { spans: Box<[Span]>, }, } impl Spanned for UseTree { fn span(&self) -> Span { match self { UseTree::Group { imports } => imports.span(), UseTree::Name { name } => name.span(), UseTree::Rename { name, alias, .. } => Span::join(name.span(), &alias.span()), UseTree::Glob { star_token } => star_token.span(), UseTree::Path { prefix, suffix, .. } => Span::join(prefix.span(), &suffix.span()), UseTree::Error { spans } => Span::join_all(spans.to_vec().clone()), } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/item_impl.rs
sway-ast/src/item/item_impl.rs
use crate::{priv_prelude::*, FnArgs}; /// Denotes to what kind of an item an [ItemImplItem] belongs. /// This enum is used mostly for reporting use cases. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ImplItemParent { Contract, // Currently we don't have cases that need further distinction. // Add other specific items like enum, struct, etc. when needed. Other, } #[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, Serialize)] pub enum ItemImplItem { Fn(ItemFn), Const(ItemConst), Type(TraitType), } impl ItemImplItem { /// [ItemImplItem]'s friendly name string used for various reportings. pub fn friendly_name(&self, parent: ImplItemParent) -> &'static str { use ItemImplItem::*; match self { Fn(item_fn) => match item_fn.fn_signature.arguments.inner { FnArgs::Static(_) => match parent { ImplItemParent::Contract => "contract method", ImplItemParent::Other => "associated function", }, FnArgs::NonStatic { .. } => "method", }, Const(..) => "associated constant", Type(..) => "associated type", } } } #[derive(Clone, Debug, Serialize)] pub struct ItemImpl { pub impl_token: ImplToken, pub generic_params_opt: Option<GenericParams>, pub trait_opt: Option<(PathType, ForToken)>, pub ty: Ty, pub where_clause_opt: Option<WhereClause>, pub contents: Braces<Vec<Annotated<ItemImplItem>>>, } impl Spanned for ItemImpl { fn span(&self) -> Span { Span::join(self.impl_token.span(), &self.contents.span()) } } impl Spanned for ItemImplItem { fn span(&self) -> Span { match self { ItemImplItem::Fn(fn_decl) => fn_decl.span(), ItemImplItem::Const(const_decl) => const_decl.span(), ItemImplItem::Type(type_decl) => type_decl.span(), } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/sway-ast/src/item/item_fn.rs
sway-ast/src/item/item_fn.rs
use crate::priv_prelude::*; #[derive(Clone, Debug, Serialize)] pub struct ItemFn { pub fn_signature: FnSignature, pub body: Braces<CodeBlockContents>, } impl Spanned for ItemFn { fn span(&self) -> Span { Span::join(self.fn_signature.span(), &self.body.span()) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/templates/sway-script-test-rs/template/build.rs
templates/sway-script-test-rs/template/build.rs
//! This build script is used to compile the sway project using `forc` prior to running tests. use std::process::Command; fn main() { Command::new("forc").args(&["build"]).status().unwrap(); }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/templates/sway-script-test-rs/template/tests/harness.rs
templates/sway-script-test-rs/template/tests/harness.rs
use fuels::prelude::*; // Load abi from json abigen!(Script( name = "MyScript", abi = "out/debug/{{project-name}}-abi.json" )); async fn get_script_instance() -> MyScript<WalletUnlocked> { // Launch a local network let wallets = launch_custom_provider_and_get_wallets( WalletsConfig::new( Some(1), /* Single wallet */ Some(1), /* Single coin (UTXO) */ Some(1_000_000_000), /* Amount per coin */ ), None, None, ) .await; let wallet = wallets.unwrap().pop().unwrap(); let bin_path = "./out/debug/{{project-name}}.bin"; let instance = MyScript::new(wallet.clone(), bin_path); instance } #[tokio::test] async fn can_get_script_instance() { const LUCKY_NUMBER: u64 = 777; let configurables = MyScriptConfigurables::default().with_SECRET_NUMBER(LUCKY_NUMBER.clone()).unwrap(); let instance = get_script_instance().await; // Now you have an instance of your script let response = instance.with_configurables(configurables).main().call().await.unwrap(); assert_eq!(response.value, LUCKY_NUMBER); // You can print logs from scripts to debug let logs = response.decode_logs(); println!("{:?}", logs); }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/templates/sway-test-rs/template/build.rs
templates/sway-test-rs/template/build.rs
//! This build script is used to compile the sway project using `forc` prior to running tests. use std::process::Command; fn main() { Command::new("forc").args(&["build"]).status().unwrap(); }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/templates/sway-test-rs/template/tests/harness.rs
templates/sway-test-rs/template/tests/harness.rs
use fuels::{prelude::*, types::ContractId}; // Load abi from json abigen!(Contract( name = "MyContract", abi = "out/debug/{{project-name}}-abi.json" )); async fn get_contract_instance() -> (MyContract<WalletUnlocked>, ContractId) { // Launch a local network and deploy the contract let mut wallets = launch_custom_provider_and_get_wallets( WalletsConfig::new( Some(1), /* Single wallet */ Some(1), /* Single coin (UTXO) */ Some(1_000_000_000), /* Amount per coin */ ), None, None, ) .await .unwrap(); let wallet = wallets.pop().unwrap(); let id = Contract::load_from( "./out/debug/{{project-name}}.bin", LoadConfiguration::default(), ) .unwrap() .deploy(&wallet, TxPolicies::default()) .await .unwrap(); let instance = MyContract::new(id.clone(), wallet); (instance, id.into()) } #[tokio::test] async fn can_get_contract_id() { let (_instance, _id) = get_contract_instance().await; // Now you have an instance of your contract you can use to test each function }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/templates/sway-predicate-test-rs/template/build.rs
templates/sway-predicate-test-rs/template/build.rs
//! This build script is used to compile the sway project using `forc` prior to running tests. use std::process::Command; fn main() { Command::new("forc").args(&["build"]).status().unwrap(); }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/templates/sway-predicate-test-rs/template/tests/harness.rs
templates/sway-predicate-test-rs/template/tests/harness.rs
use fuels::{accounts::{predicate::Predicate}, prelude::*}; // Load abi from json abigen!(Predicate( name = "MyPredicate", abi = "out/debug/{{project-name}}-abi.json" )); async fn get_predicate_instance() -> (WalletUnlocked, Predicate, AssetId) { let mut wallets = launch_custom_provider_and_get_wallets( WalletsConfig::new( Some(1), /* Single wallet */ Some(1), /* Single coin (UTXO) */ Some(1_000_000_000), /* Amount per coin */ ), None, None, ) .await .unwrap(); let wallet = wallets.pop().unwrap(); let provider = wallet.provider().clone().unwrap(); let base_asset_id = provider.base_asset_id().clone(); let bin_path = "./out/debug/{{project-name}}.bin"; let instance: Predicate = Predicate::load_from(bin_path).unwrap().with_provider(provider.clone()); (wallet, instance, base_asset_id) } async fn check_balances( wallet: &WalletUnlocked, instance: &Predicate, expected_wallet_balance: Option<u64>, expected_predicate_balance: Option<u64>, ) -> (u64, u64) { let wallet_bal = wallet.get_asset_balance(&AssetId::default()).await.unwrap(); let predicate_bal = instance.get_asset_balance(&AssetId::default()).await.unwrap(); if let Some(expected) = expected_wallet_balance { assert_eq!(wallet_bal, expected); } if let Some(expected) = expected_predicate_balance { assert_eq!(predicate_bal, expected); } (wallet_bal, predicate_bal) } #[tokio::test] async fn can_get_predicate_instance() { let (wallet, instance, base_asset_id) = get_predicate_instance().await; let predicate_root = instance.address(); // Check balances before funding predicate check_balances(&wallet, &instance, Some(1_000_000_000u64), None).await; // Fund predicate from wallet let _ = wallet.transfer(predicate_root, 1234, base_asset_id, TxPolicies::default()).await; // Check balances after funding predicate check_balances(&wallet, &instance, Some(999_998_766u64), Some(1234u64)).await; let _ = instance.transfer(wallet.address(), 1234, base_asset_id, TxPolicies::default()).await; // Check balances after transferring funds out of predicate check_balances(&wallet, &instance, Some(1_000_000_000u64), Some(0u64)).await; }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/test_macros/src/lib.rs
swayfmt/test_macros/src/lib.rs
/// Convenience macro for generating test cases for a parsed Item of ItemKind. /// This macro is a wrapper around the fmt_test! macro and simply passes the AST type /// to it. /// /// Provide a known good, and then some named test cases that should evaluate to /// that known good. e.g.: /// ``` /// # use paste::paste; /// # use prettydiff::{basic::DiffOp, diff_lines}; /// # use test_macros::fmt_test_item; fn main() { /// // test suite name known good ///fmt_test_item!(field_proj_foobar "foo.bar.baz.quux", /// // test case name should format to known good /// intermediate_whitespace "foo . bar . baz . quux"); /// # } /// ``` #[macro_export] macro_rules! fmt_test_item { ($scope:ident $desired_output:expr, $($name:ident $y:expr),+) =>{ $crate::fmt_test!(sway_ast::ItemKind, $scope $desired_output, $($name $y)+); }; } /// Convenience macro for generating test cases for a parsed Expr. /// This macro is a wrapper around the fmt_test! macro and simply passes the AST type /// to it. /// /// Provide a known good, and then some named test cases that should evaluate to /// that known good. e.g.: /// ``` /// # use paste::paste; /// # use prettydiff::{basic::DiffOp, diff_lines}; /// # use test_macros::fmt_test_expr; fn main() { /// // test suite name known good ///fmt_test_expr!(field_proj_foobar "foo.bar.baz.quux", /// // test case name should format to known good /// intermediate_whitespace "foo . bar . baz . quux"); /// # } /// ``` #[macro_export] macro_rules! fmt_test_expr { ($scope:ident $desired_output:expr, $($name:ident $y:expr),+) =>{ $crate::fmt_test!(sway_ast::Expr, $scope $desired_output, $($name $y)+); }; } /// Convenience macro for generating test cases. /// /// This macro should be wrapped by another macro, eg. `fmt_test_expr!` that passes /// in a Sway AST type, eg. sway_ast::Expr, and is not meant to be used directly. #[macro_export] macro_rules! fmt_test { ($ty:expr, $scope:ident $desired_output:expr, $($name:ident $y:expr),+) => { $crate::fmt_test_inner!($ty, $scope $desired_output, $($name $y)+ , remove_trailing_whitespace format!("{} \n\n\t ", $desired_output).as_str(), remove_beginning_whitespace format!(" \n\t{}", $desired_output).as_str(), identity $desired_output, /* test return is valid */ remove_beginning_and_trailing_whitespace format!(" \n\t {} \n\t ", $desired_output).as_str() ); }; } /// Inner macro for fmt_test! that does the actual formatting and presents the diffs. /// /// This macro is not meant to be called directly, but through fmt_test!. #[allow(clippy::crate_in_macro_def)] // Allow external parse crate #[macro_export] macro_rules! fmt_test_inner { ($ty:expr, $scope:ident $desired_output:expr, $($name:ident $y:expr),+) => { $( paste! { #[test] fn [<$scope _ $name>] () { let formatted_code = crate::parse::parse_format::<$ty>($y, sway_features::ExperimentalFeatures::default()).unwrap(); let changeset = diff_lines(&formatted_code, $desired_output); let count_of_updates = changeset.diff().len(); if count_of_updates != 0 { println!("FAILED: {count_of_updates} diff items."); } for diff in changeset.diff() { match diff { DiffOp::Equal(old) => { for o in old { println!("{}", o) } } DiffOp::Insert(new) => { for n in new { println_green(&format!("+{}", n)); } } DiffOp::Remove(old) => { for o in old { println_red(&format!("-{}", o)); } } DiffOp::Replace(old, new) => { for o in old { println_red(&format!("-{}", o)); } for n in new { println_green(&format!("+{}", n)); } } } } println!("{formatted_code}"); assert_eq!(&formatted_code, $desired_output) } } )+ } } #[macro_export] macro_rules! assert_eq_pretty { ($got:expr, $expected:expr) => { let got = &$got[..]; let expected = &$expected[..]; if got != expected { use similar::TextDiff; let diff = TextDiff::from_lines(expected, got); for op in diff.ops() { for change in diff.iter_changes(op) { match change.tag() { similar::ChangeTag::Equal => print!("{}", change), similar::ChangeTag::Insert => print!("\x1b[32m+{}\x1b[0m", change), // Green for additions similar::ChangeTag::Delete => print!("\x1b[31m-{}\x1b[0m", change), // Red for deletions } } } println!(); panic!("printed outputs differ!"); } }; }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/lib.rs
swayfmt/src/lib.rs
//! Based on `rustfmt`, `swayfmt` aims to be a transparent approach to formatting Sway code. //! //! `swayfmt` configurations can be adjusted with a `swayfmt.toml` config file declared at the root of a Sway project, //! however the default formatter does not require the presence of one and any fields omitted will remain as default. #![allow(dead_code)] pub mod comments; pub mod config; mod constants; mod error; mod formatter; mod items; mod module; pub mod parse; mod utils; pub use crate::formatter::{Format, Formatter}; pub use error::FormatterError;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/parse.rs
swayfmt/src/parse.rs
use crate::{error::ParseFileError, Formatter, FormatterError}; use sway_ast::{attribute::Annotated, token::CommentedTokenStream, Module}; use sway_error::handler::{ErrorEmitted, Handler}; use sway_features::ExperimentalFeatures; use sway_types::span::Source; pub fn with_handler<T>( run: impl FnOnce(&Handler) -> Result<T, ErrorEmitted>, ) -> Result<T, ParseFileError> { let handler = <_>::default(); let res = run(&handler); let (errors, _warnings, _infos) = handler.consume(); res.ok() .filter(|_| errors.is_empty()) .ok_or(ParseFileError(errors)) } pub fn parse_file( src: Source, experimental: ExperimentalFeatures, ) -> Result<Annotated<Module>, ParseFileError> { with_handler(|h| sway_parse::parse_file(h, src, None, experimental)) } pub fn lex(src: Source) -> Result<CommentedTokenStream, ParseFileError> { let end = src.text.len(); with_handler(|h| sway_parse::lex_commented(h, src, 0, end, &None)) } pub fn parse_format<P: sway_parse::Parse + crate::Format>( input: &str, experimental: ExperimentalFeatures, ) -> Result<String, FormatterError> { let parsed = with_handler(|handler| { let token_stream = sway_parse::lex(handler, input.into(), 0, input.len(), None)?; sway_parse::Parser::new(handler, &token_stream, experimental).parse::<P>() })?; // Allow test cases that include comments. let mut formatter = Formatter::default(); formatter.with_comments_context(input)?; let mut buf = <_>::default(); parsed.format(&mut buf, &mut formatter)?; Ok(buf) } /// Partially parses an AST node that implements sway_parse::Parse. /// This is used to insert comments locally. pub fn parse_snippet<P: sway_parse::Parse + crate::Format>( input: &str, experimental: ExperimentalFeatures, ) -> Result<P, ParseFileError> { with_handler(|handler| { let token_stream = sway_parse::lex(handler, input.into(), 0, input.len(), None)?; sway_parse::Parser::new(handler, &token_stream, experimental).parse::<P>() }) }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/comments.rs
swayfmt/src/comments.rs
use crate::{ formatter::FormattedCode, parse::parse_snippet, utils::map::{ byte_span::{ByteSpan, LeafSpans}, comments::CommentMap, }, Format, Formatter, FormatterError, }; use ropey::Rope; use std::{fmt::Write, ops::Range}; use sway_ast::token::{Comment, CommentKind}; use sway_types::{Span, Spanned}; pub type UnformattedCode = String; #[derive(Debug, Default, Clone)] pub struct CommentsContext { /// A BTreeMap of the mapping ByteSpan->Comment for inserting comments. pub map: CommentMap, /// Original unformatted code that the formatter tries to format. /// The Formatter requires this to preserve newlines between comments. unformatted_code: UnformattedCode, } impl CommentsContext { pub fn new(map: CommentMap, unformatted_code: UnformattedCode) -> Self { Self { map, unformatted_code, } } pub fn unformatted_code(&self) -> &str { &self.unformatted_code } } #[inline] pub fn has_comments_in_formatter(formatter: &Formatter, range: &Range<usize>) -> bool { formatter .comments_context .map .comments_between(range) .peekable() .peek() .is_some() } #[inline] pub fn has_comments<I: Iterator>(comments: I) -> bool { comments.peekable().peek().is_some() } /// This function collects newlines to insert after a given Comment span to preserve them. pub fn collect_newlines_after_comment( comments_context: &CommentsContext, comment: &Comment, ) -> String { comments_context.unformatted_code()[comment.span().end()..] .chars() .take_while(|&c| c.is_whitespace()) .filter(|&c| c == '\n') .collect() } /// Writes a trailing comment using potentially destructive 'truncate()' to strip the end /// of whitespaces. fn write_trailing_comment( formatted_code: &mut FormattedCode, comment: &Comment, ) -> Result<(), FormatterError> { formatted_code.truncate(formatted_code.trim_end().len()); writeln!(formatted_code, " {}", comment.span().as_str().trim_end())?; Ok(()) } /// Given a range, writes comments contained within the range. This function /// removes comments that are written here from the [CommentMap] for later use. /// /// Most comment formatting should be done using [rewrite_with_comments] in /// the context of the AST, but in some cases (eg. at the end of module) we require this function. /// /// Returns: /// `Ok(true)` on successful execution with comments written, /// `Ok(false)` on successful execution and if there are no comments within the given range, /// `Err` if a FormatterError was encountered. /// /// The `range` can be an empty [Range], or have its start being greater then its end. /// This is to support formatting arbitrary lexed trees, that are not necessarily backed by source code. pub fn write_comments( formatted_code: &mut FormattedCode, range: Range<usize>, formatter: &mut Formatter, ) -> Result<bool, FormatterError> { { let mut comments_iter = formatter .comments_context .map .comments_between(&range) .peekable(); if comments_iter.peek().is_none() { return Ok(false); }; // If the already formatted code ends with some pattern and doesn't already end with a newline, // we want to add a newline here. if formatted_code.ends_with(['{', '}']) && !formatted_code.ends_with('\n') { writeln!(formatted_code)?; } for comment in comments_iter { let newlines = collect_newlines_after_comment(&formatter.comments_context, comment); match comment.comment_kind { CommentKind::Newlined => { write!( formatted_code, "{}{}{}", formatter.indent_to_str()?, comment.span().as_str(), newlines )?; } CommentKind::Trailing => { write_trailing_comment(formatted_code, comment)?; } CommentKind::Inlined => { // We do a trim and truncate here to ensure that only a single whitespace separates // the inlined comment from the previous token. formatted_code.truncate(formatted_code.trim_end().len()); write!(formatted_code, " {} ", comment.span().as_str())?; } CommentKind::Multilined => { write!( formatted_code, "{}{}", formatter.indent_to_str()?, comment.span().as_str(), )?; } } } } // Keep comments that are NOT within `range` within the CommentMap. // This is destructive behavior for comments since if any steps above fail // and comments were not written, `retains()` will still delete these comments. formatter .comments_context .map .retain(|bs, _| !bs.contained_within(&range)); Ok(true) } /// The main function that rewrites a piece of formatted code with comments found in its unformatted version. /// /// This takes a given AST node's unformatted span, its leaf spans and its formatted code (a string) and /// parses the equivalent formatted version to get its leaf spans. We traverse the spaces between both /// formatted and unformatted leaf spans to find possible comments and inserts them between. /// /// The `unformatted_span` can be an empty [Span]. This is to support formatting arbitrary lexed trees, /// that are not necessarily backed by source code. pub fn rewrite_with_comments<T: sway_parse::Parse + Format + LeafSpans>( formatter: &mut Formatter, unformatted_span: Span, unformatted_leaf_spans: Vec<ByteSpan>, formatted_code: &mut FormattedCode, last_formatted: usize, ) -> Result<(), FormatterError> { // Since we are adding comments into formatted code, in the next iteration the spans we find for the formatted code needs to be offsetted // as the total length of comments we added in previous iterations. let mut offset = 0; let mut to_rewrite = formatted_code[last_formatted..].to_string(); let formatted_leaf_spans = parse_snippet::<T>(&formatted_code[last_formatted..], formatter.experimental)?.leaf_spans(); let mut previous_unformatted_leaf_span = unformatted_leaf_spans .first() .ok_or(FormatterError::CommentError)?; let mut previous_formatted_leaf_span = formatted_leaf_spans .first() .ok_or(FormatterError::CommentError)?; for (unformatted_leaf_span, formatted_leaf_span) in unformatted_leaf_spans .iter() .zip(formatted_leaf_spans.iter()) { // Search for comments between the previous leaf span's end and the next leaf span's start let range = std::ops::Range { start: previous_unformatted_leaf_span.end, end: unformatted_leaf_span.start, }; let iter = formatter.comments_context.map.comments_between(&range); let mut comments_found = vec![]; for i in iter { comments_found.push(i.clone()); } if !comments_found.is_empty() { let extra_newlines = collect_extra_newlines(unformatted_span.clone(), &comments_found); offset += insert_after_span( previous_formatted_leaf_span, comments_found.clone(), offset, &mut to_rewrite, extra_newlines, )?; formatter .comments_context .map .retain(|bs, _| !bs.contained_within(&range)) } previous_unformatted_leaf_span = unformatted_leaf_span; previous_formatted_leaf_span = formatted_leaf_span; } formatted_code.truncate(last_formatted); write!(formatted_code, "{to_rewrite}")?; Ok(()) } /// Collect extra newline before comment(s). The main purpose of this function is to maintain /// newlines between comments when inserting multiple comments at once. fn collect_extra_newlines(unformatted_span: Span, comments_found: &Vec<Comment>) -> Vec<usize> { // The first comment is always assumed to have no extra newlines before itself. let mut extra_newlines = vec![0]; if comments_found.len() == 1 { return extra_newlines; } let mut prev_comment: Option<&Comment> = None; for comment in comments_found { if let Some(prev_comment) = prev_comment { // Get whitespace between the end of the previous comment and the start of the next. let whitespace_between = unformatted_span.as_str()[prev_comment.span().end() - unformatted_span.start() ..comment.span().start() - unformatted_span.start()] .to_string(); // Count the number of newline characters we found above. // By default, we want 0 extra newlines, but if there are more than 1 extra newline, we want to squash it to 1. let mut extra_newlines_count = 0; if whitespace_between.chars().filter(|&c| c == '\n').count() > 1 { extra_newlines_count = 1; }; extra_newlines.push(extra_newlines_count); } prev_comment = Some(comment); } extra_newlines } /// Check if a block is empty. When formatted without comments, empty code blocks are formatted into "{}", which is what this check is for. fn is_empty_block(formatted_code: &FormattedCode, end: usize) -> bool { formatted_code.chars().nth(end - 1) == Some('{') && formatted_code.chars().nth(end) == Some('}') } /// Main driver of writing comments. This function is a no-op if the block of code is empty. /// /// This iterates through comments inserts each of them after a given span and returns the offset. /// While inserting comments this also inserts whitespaces/newlines so that alignment is intact. /// To do the above, there are some whitespace heuristics we stick to: /// /// 1) Assume comments are anchored to the line below, and follow its alignment. /// 2) In some cases the line below is the end of the function eg. it contains only a closing brace '}'. /// in such cases we then try to anchor the comment to the line above. /// 3) In the cases of entirely empty blocks we actually should prefer using `write_comments` over /// `rewrite_with_comments` since `write_comments` would have the formatter's indentation context. fn insert_after_span( from: &ByteSpan, comments_to_insert: Vec<Comment>, offset: usize, formatted_code: &mut FormattedCode, extra_newlines: Vec<usize>, ) -> Result<usize, FormatterError> { let mut comment_str = String::new(); // We want to anchor the comment to the next line, and here, // we make the assumption here that comments will never be right before the final leaf span. let mut indent = formatted_code[from.end + offset..] .chars() .take_while(|c| c.is_whitespace()) .collect::<String>(); // In the case of empty blocks, we do not know the indentation of comments at that time. // Writing comments in empty blocks has to be deferred to `write_comments` instead, which will // contain the Formatter's indentation context. if !is_empty_block(formatted_code, from.end) { // There can be cases where comments are at the end. // If so, we try to 'pin' our comment's indentation to the previous line instead. if formatted_code.chars().nth(from.end + offset + indent.len()) == Some('}') { // It could be possible that the first comment found here is a Trailing, // then a Newlined. // We want all subsequent newlined comments to follow the indentation of the // previous line that is NOT a comment. if comments_to_insert .iter() .any(|c| c.comment_kind == CommentKind::Newlined) { // Find and assign the indentation of the previous line to `indent`. let prev_line = formatted_code[..from.end + offset] .trim_end() .chars() .rev() .take_while(|&c| c != '\n') .collect::<String>(); indent = prev_line .chars() .rev() .take_while(|c| c.is_whitespace()) .collect(); if let Some(comment) = comments_to_insert.first() { if comment.comment_kind != CommentKind::Trailing { comment_str.push('\n'); } } } } for (comment, extra_newlines) in comments_to_insert.iter().zip(extra_newlines) { // Check for newlines to preserve. for _ in 0..extra_newlines { comment_str.push('\n'); } match comment.comment_kind { CommentKind::Trailing => { if comments_to_insert.len() > 1 && indent.starts_with('\n') { write!(comment_str, " {}", comment.span().as_str())?; } else { writeln!(comment_str, " {}", comment.span().as_str())?; } } CommentKind::Newlined => { if comments_to_insert.len() > 1 && indent.starts_with('\n') { write!(comment_str, "{}{}", indent, comment.span().as_str())?; } else { writeln!(comment_str, "{}{}", indent, comment.span().as_str())?; } } CommentKind::Inlined => { if !formatted_code[..from.end].ends_with(' ') { write!(comment_str, " ")?; } write!(comment_str, "{}", comment.span().as_str())?; if !formatted_code[from.end + offset..].starts_with([' ', '\n']) { write!(comment_str, " ")?; } } CommentKind::Multilined => { write!(comment_str, "{}{}", indent, comment.span().as_str())?; } }; } let mut src_rope = Rope::from_str(formatted_code); // We do a sanity check here to ensure that we don't insert an extra newline // if the place at which we're going to insert comments already ends with '\n'. if let Some(char) = src_rope.get_char(from.end + offset) { if char == '\n' && comment_str.ends_with('\n') { comment_str.pop(); } }; // Insert the actual comment(s). src_rope .try_insert(from.end + offset, &comment_str) .map_err(|_| FormatterError::CommentError)?; formatted_code.clear(); formatted_code.push_str(&src_rope.to_string()); } // In order to handle special characters, we return the number of characters rather than // the size of the string. Ok(comment_str.chars().count()) } #[cfg(test)] mod tests { use super::*; use crate::utils::map::byte_span::ByteSpan; /// For readability of the assertions, the comments written within these snippets will be the /// ByteSpan representations instead of some random comment, /// eg. the below '// 10-18' comment is representative of its start (10) and end (18) index /// This way we have contextual knowledge of what the source code looks like when we /// do 'comments_ctx.map.get(&ByteSpan { start: 10, end: 18 })'. /// If more tests are to be added here, it is highly encouraged to follow this convention. #[test] fn test_collect_newlines_after_comment() { let commented_code = r#"contract; // 10-18 pub fn main() -> bool { true } "#; let mut comments_ctx = CommentsContext::new( CommentMap::from_src(commented_code.into()).unwrap(), commented_code.to_string(), ); assert_eq!( collect_newlines_after_comment( &comments_ctx, comments_ctx .map .get(&ByteSpan { start: 10, end: 18 }) .unwrap(), ), "\n" ); let multiline_comment = r#"contract; pub fn main() -> bool { // 38-46 // 51-59 true } "#; comments_ctx = CommentsContext::new( CommentMap::from_src(multiline_comment.into()).unwrap(), multiline_comment.to_string(), ); assert_eq!( collect_newlines_after_comment( &comments_ctx, comments_ctx .map .get(&ByteSpan { start: 38, end: 46 }) .unwrap(), ), "\n" ); let multi_newline_comments = r#"contract; pub fn main() -> bool { // 38-46 // 52-60 true } "#; comments_ctx = CommentsContext::new( CommentMap::from_src(multi_newline_comments.into()).unwrap(), multi_newline_comments.to_string(), ); assert_eq!( collect_newlines_after_comment( &comments_ctx, comments_ctx .map .get(&ByteSpan { start: 38, end: 46 }) .unwrap(), ), "\n\n" ); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/error.rs
swayfmt/src/error.rs
use std::{io, path::PathBuf}; use sway_error::error::CompileError; use thiserror::Error; #[derive(Debug, Clone, PartialEq, Eq, Hash, Error)] #[error("Unable to parse: {}", self.0.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("\n"))] pub struct ParseFileError(pub Vec<CompileError>); #[derive(Debug, Error)] pub enum FormatterError { #[error("Error parsing file: {0}")] ParseFileError(#[from] ParseFileError), #[error("Error formatting a message into a stream: {0}")] FormatError(#[from] std::fmt::Error), #[error("Error while adding comments")] CommentError, #[error("Error while formatting newline sequences")] NewlineSequenceError, #[error("Error while formatting file with syntax errors")] SyntaxError, } #[derive(Debug, Error)] pub enum ConfigError { #[error("failed to parse config: {err}")] Deserialize { err: toml::de::Error }, #[error("failed to read config at {:?}: {err}", path)] ReadConfig { path: PathBuf, err: io::Error }, #[error("could not find a `swayfmt.toml` in the given directory or its parents")] NotFound, }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/constants.rs
swayfmt/src/constants.rs
/// `swayfmt` file name. pub const SWAY_FORMAT_FILE_NAME: &str = "swayfmt.toml"; //FUNDAMENTALS /// Default max width of each line. pub const DEFAULT_MAX_LINE_WIDTH: usize = 100; /// Default tab size as spaces. pub const DEFAULT_TAB_SPACES: usize = 4; //HEURISTICS /// Default max width of the args of a function call before falling back to vertical formatting. pub const DEFAULT_FN_CALL_WIDTH: usize = 60; /// Default max width of the args of a function-like attributes before falling back to vertical formatting. pub const DEFAULT_ATTR_FN_LIKE_WIDTH: usize = 70; /// Default max width in the body of a user-defined structure literal before falling back to vertical formatting. pub const DEFAULT_STRUCTURE_LIT_WIDTH: usize = 18; /// Default max width of a user-defined structure field before falling back to vertical formatting. pub const DEFAULT_STRUCTURE_VAR_WIDTH: usize = 35; /// Default Maximum width of an array literal before falling back to vertical formatting. pub const DEFAULT_COLLECTION_WIDTH: usize = 80; /// Default width threshold for an array element to be considered short. pub const DEFAULT_SHORT_ARRAY_ELEM_WIDTH_THRESHOLD: usize = 10; /// Default max length of a chain to fit on a single line. pub const DEFAULT_CHAIN_WIDTH: usize = 60; /// Default max line length for single line if-else expression. pub const DEFAULT_SINGLE_LINE_IF_ELSE_WIDTH: usize = 50; //ITEMS /// Default max number of blank lines which can be put between items. pub const DEFAULT_BLANK_LINES_UPPER_BOUND: usize = 1; /// Default min number of blank lines which must be put between items. pub const DEFAULT_BLANK_LINES_LOWER_BOUND: usize = 0; /// Write an items and its attribute on the same line if their combined width is below a threshold. pub const DEFAULT_INLINE_ATTR_WIDTH: usize = 0; //COMMENTS /// Default max length of comments. pub const DEFAULT_MAX_COMMENT_WIDTH: usize = 80; //NEWLINE_STYLE pub(crate) const LINE_FEED: char = '\n'; pub(crate) const CARRIAGE_RETURN: char = '\r'; pub(crate) const WINDOWS_NEWLINE: &str = "\r\n"; pub(crate) const UNIX_NEWLINE: &str = "\n"; #[cfg(target_os = "windows")] pub(crate) const NEW_LINE: &str = WINDOWS_NEWLINE; #[cfg(not(target_os = "windows"))] pub(crate) const NEW_LINE: &str = UNIX_NEWLINE; //INDENT_STYLE // INDENT_BUFFER.len() = 81 pub(crate) const INDENT_BUFFER_LEN: usize = 80; pub(crate) const INDENT_BUFFER: &str = "\n "; // 8096 is close enough to infinite according to `rustfmt`. pub(crate) const INFINITE_SHAPE_WIDTH: usize = 8096; pub(crate) const HARD_TAB: char = '\t'; /// Default max number of newlines allowed in between statements before collapsing them to /// threshold pub const DEFAULT_NEWLINE_THRESHOLD: usize = 1; //IDENT pub(crate) const RAW_MODIFIER: &str = "r#";
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/formatter/shape.rs
swayfmt/src/formatter/shape.rs
//! Associated functions and tests for handling of indentation. use crate::{ config::{heuristics::WidthHeuristics, manifest::Config}, constants::{HARD_TAB, INDENT_BUFFER, INDENT_BUFFER_LEN}, FormatterError, }; use std::{ borrow::Cow, fmt::Write, ops::{Add, Sub}, }; #[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] pub(crate) struct Indent { /// Width of the block indent, in characters. /// Must be a multiple of `tab_spaces`. pub(crate) block_indent: usize, } impl Indent { /// Constructs a new instance of `Indent` with a given size. fn new(block_indent: usize) -> Self { Self { block_indent } } /// Constructs an empty instance of `Indent`. fn empty() -> Self { Self::new(0) } /// Adds a level of indentation specified by the `Formatter::config` to the current `block_indent`. fn block_indent(&mut self, config: &Config) { self.block_indent += config.whitespace.tab_spaces } /// Removes a level of indentation specified by the `Formatter::config` to the current `block_indent`. /// If the current level of indentation would be negative, leave it as is. fn block_unindent(&mut self, config: &Config) { let tab_spaces = config.whitespace.tab_spaces; if self.block_indent < tab_spaces { } else { self.block_indent -= tab_spaces } } /// Current indent size. pub(crate) fn width(&self) -> usize { self.block_indent } // Checks for either `hard_tabs` or `tab_spaces` and creates a // buffer of whitespace from the current level of indentation. // This also takes an offset which determines whether to add a new line. fn to_string_inner( self, config: &Config, offset: usize, ) -> Result<Cow<'static, str>, FormatterError> { let (num_tabs, num_spaces) = if config.whitespace.hard_tabs { (self.block_indent / config.whitespace.tab_spaces, 0) } else { (0, self.width()) }; let num_chars = num_tabs + num_spaces; if num_tabs == 0 && num_chars + offset <= INDENT_BUFFER_LEN { Ok(Cow::from(&INDENT_BUFFER[offset..=num_chars])) } else { let mut indent = String::with_capacity(num_chars + usize::from(offset == 0)); if offset == 0 { writeln!(indent)?; } for _ in 0..num_tabs { write!(indent, "{HARD_TAB}")?; } for _ in 0..num_spaces { write!(indent, " ")?; } Ok(Cow::from(indent)) } } /// A wrapper for `Indent::to_string_inner()` that does not add a new line. pub(crate) fn to_string(self, config: &Config) -> Result<Cow<'static, str>, FormatterError> { self.to_string_inner(config, 1) } /// A wrapper for `Indent::to_string_inner()` that also adds a new line. pub(crate) fn to_string_with_newline( self, config: &Config, ) -> Result<Cow<'static, str>, FormatterError> { self.to_string_inner(config, 0) } } impl Add for Indent { type Output = Indent; fn add(self, rhs: Indent) -> Indent { Indent { block_indent: self.block_indent + rhs.block_indent, } } } impl Sub for Indent { type Output = Indent; fn sub(self, rhs: Indent) -> Indent { Indent::new(self.block_indent - rhs.block_indent) } } /// Information about the line of code currently being evaluated. #[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] pub(crate) struct CodeLine { /// The current number of characters in the given code line. pub(crate) width: usize, pub(crate) line_style: LineStyle, pub(crate) expr_kind: ExprKind, /// Used in determining `SameLineWhere` formatting. pub(crate) has_where_clause: bool, /// Expression is too long to fit in a single line pub(crate) expr_new_line: bool, } impl CodeLine { pub(crate) fn from(line_style: LineStyle, expr_kind: ExprKind) -> Self { Self { width: Default::default(), line_style, expr_kind, has_where_clause: Default::default(), expr_new_line: false, } } pub(crate) fn reset_width(&mut self) { self.width = 0; } pub(crate) fn update_width(&mut self, new_width: usize) { self.width = new_width; } pub(crate) fn add_width(&mut self, extra_width: usize) { self.width += extra_width; } pub(crate) fn sub_width(&mut self, extra_width: usize) { self.width -= extra_width; } /// Update `CodeLine::line_style` with a given LineStyle. pub(crate) fn update_line_style(&mut self, line_style: LineStyle) { self.line_style = line_style; } /// Update `CodeLine::expr_kind` with a given ExprKind. pub(crate) fn update_expr_kind(&mut self, expr_kind: ExprKind) { self.expr_kind = expr_kind; } /// Update the value of `has_where_clause`. pub(crate) fn update_where_clause(&mut self, has_where_clause: bool) { self.has_where_clause = has_where_clause; } pub(crate) fn update_expr_new_line(&mut self, expr_new_line: bool) { self.expr_new_line = expr_new_line; } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) enum LineStyle { Normal, Inline, Multiline, } impl LineStyle { pub fn is_multiline(&self) -> bool { matches!(self, Self::Multiline) } } impl Default for LineStyle { fn default() -> Self { Self::Normal } } /// The type of expression to determine which part of `Config::heuristics` to use. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) enum ExprKind { Variable, Function, Struct, Collection, MethodChain, Conditional, Import, Undetermined, } impl Default for ExprKind { fn default() -> Self { Self::Undetermined } } /// The current shape of the formatter. #[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] pub struct Shape { /// The current indentation of code. pub(crate) indent: Indent, /// Used in determining which heuristics settings to use from the config /// and whether a code line is normal, inline or multiline. pub(crate) code_line: CodeLine, /// The definitive width settings from the `Config`. pub(crate) width_heuristics: WidthHeuristics, } impl Shape { // `indent` is the indentation of the first line. The next lines // should begin with at least `indent` spaces (except backwards // indentation). The first line should not begin with indentation. // `width` is the maximum number of characters on the last line // (excluding `indent`). The width of other lines is not limited by // `width`. // // Note that in reality, we sometimes use width for lines other than the // last (i.e., we are conservative). // .......*-------* // | | // | *-* // *-----| // |<------------>| max width // |<---->| indent // |<--->| width // /// A wrapper for `to_width_heuristics()` that also checks if the settings are default. pub(crate) fn apply_width_heuristics(&mut self, width_heuristics: WidthHeuristics) { if width_heuristics != WidthHeuristics::default() { self.width_heuristics = width_heuristics } } /// A wrapper for `Indent::block_indent()`. /// /// Adds a level of indentation specified by the `Formatter::config` to the current `block_indent`. pub(crate) fn block_indent(&mut self, config: &Config) { self.indent.block_indent(config) } /// A wrapper for `Indent::block_unindent()`. /// /// Removes a level of indentation specified by the `Formatter::config` to the current `block_indent`. /// If the current level of indentation would be negative, leave it as is. pub(crate) fn block_unindent(&mut self, config: &Config) { self.indent.block_unindent(config) } /// Checks the current status of a `CodeLine` against the `Shape::width_heuristics` to determine which /// `LineStyle` should be applied. pub(crate) fn get_line_style( &mut self, field_width: Option<usize>, body_width: Option<usize>, config: &Config, ) { match self.code_line.expr_kind { ExprKind::Struct => { // Get the width limit of a structure to be formatted into single line if `allow_inline_style` is true. if config.structures.small_structures_single_line { if self.code_line.width > config.whitespace.max_width || field_width.unwrap_or(0) > self.width_heuristics.structure_field_width || body_width.unwrap_or(0) > self.width_heuristics.structure_lit_width { self.code_line.update_line_style(LineStyle::Multiline) } else { self.code_line.update_line_style(LineStyle::Inline) } } else { self.code_line.update_line_style(LineStyle::Multiline) } } ExprKind::Collection => { if self.code_line.width > config.whitespace.max_width || body_width.unwrap_or(0) > self.width_heuristics.collection_width { self.code_line.update_line_style(LineStyle::Multiline) } else { self.code_line.update_line_style(LineStyle::Normal) } } ExprKind::Import => { if self.code_line.width > config.whitespace.max_width { self.code_line.update_line_style(LineStyle::Multiline) } else { self.code_line.update_line_style(LineStyle::Normal) } } ExprKind::Function => { if self.code_line.width > config.whitespace.max_width || body_width.unwrap_or(0) > self.width_heuristics.fn_call_width { self.code_line.update_line_style(LineStyle::Multiline) } else { self.code_line.update_line_style(LineStyle::Normal) } } ExprKind::Conditional => { if self.code_line.width < self.width_heuristics.single_line_if_else_max_width { self.code_line.update_line_style(LineStyle::Inline) } else if body_width.unwrap_or(0) > self.width_heuristics.chain_width { self.code_line.update_line_style(LineStyle::Multiline) } else { self.code_line.update_line_style(LineStyle::Normal) } } _ => self.code_line.update_line_style(LineStyle::default()), } } /// Create a new `Shape` with a new `CodeLine` from a given `LineStyle` and `ExprKind`. pub(crate) fn with_code_line_from(self, line_style: LineStyle, expr_kind: ExprKind) -> Self { Self { code_line: CodeLine::from(line_style, expr_kind), ..self } } /// Create a new `Shape` with default `CodeLine`. pub(crate) fn with_default_code_line(self) -> Self { let mut code_line = CodeLine::default(); code_line.update_expr_new_line(self.code_line.expr_new_line); Self { code_line, ..self } } } #[cfg(test)] mod test { use super::*; use crate::formatter::Formatter; #[test] fn indent_add_sub() { let indent = Indent::new(4) + Indent::new(8); assert_eq!(12, indent.block_indent); let indent = indent - Indent::new(4); assert_eq!(8, indent.block_indent); } #[test] fn indent_to_string_spaces() { let mut formatter = Formatter::default(); formatter.shape.indent = Indent::new(12); // 12 spaces assert_eq!( " ", formatter.shape.indent.to_string(&formatter.config).unwrap() ); } #[test] fn indent_to_string_hard_tabs() { let mut formatter = Formatter::default(); formatter.config.whitespace.hard_tabs = true; formatter.shape.indent = Indent::new(8); // 2 tabs + 4 spaces assert_eq!( "\t\t", formatter.shape.indent.to_string(&formatter.config).unwrap() ); } #[test] fn shape_block_indent() { let mut formatter = Formatter::default(); formatter.config.whitespace.tab_spaces = 24; let max_width = formatter.config.whitespace.max_width; formatter.shape.code_line.width = max_width; formatter.indent(); assert_eq!(max_width, formatter.shape.code_line.width); assert_eq!(24, formatter.shape.indent.block_indent); } #[test] fn test_get_line_style_struct() { let mut formatter = Formatter::default(); formatter.shape.code_line.update_expr_kind(ExprKind::Struct); formatter .shape .get_line_style(Some(9), Some(18), &formatter.config); assert_eq!(LineStyle::Inline, formatter.shape.code_line.line_style); formatter .shape .get_line_style(Some(10), Some(19), &formatter.config); assert_eq!(LineStyle::Multiline, formatter.shape.code_line.line_style); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/formatter/mod.rs
swayfmt/src/formatter/mod.rs
use self::shape::Shape; use crate::comments::{write_comments, CommentsContext}; use crate::parse::parse_file; use crate::utils::map::comments::CommentMap; use crate::utils::map::{newline::handle_newlines, newline_style::apply_newline_style}; pub use crate::{ config::manifest::Config, error::{ConfigError, FormatterError}, }; use std::{borrow::Cow, fmt::Write, path::Path, sync::Arc}; use sway_ast::attribute::Annotated; use sway_ast::Module; use sway_features::ExperimentalFeatures; use sway_types::span::Source; use sway_types::{SourceEngine, Spanned}; pub(crate) mod shape; #[derive(Debug, Clone, Default)] pub struct Formatter { pub source_engine: Arc<SourceEngine>, pub shape: Shape, pub config: Config, pub comments_context: CommentsContext, pub experimental: ExperimentalFeatures, /// Tracks spans that were removed during formatting (e.g., braces from single-element imports). /// Maps: unformatted_byte_position -> number_of_bytes_removed /// This allows handle_newlines() to adjust span mapping when AST structure changes. pub(crate) removed_spans: Vec<(usize, usize)>, } pub type FormattedCode = String; pub trait Format { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError>; } impl Formatter { pub fn from_dir(dir: &Path, experimental: ExperimentalFeatures) -> Result<Self, ConfigError> { let config = match Config::from_dir(dir) { Ok(config) => config, Err(ConfigError::NotFound) => Config::default(), Err(e) => return Err(e), }; Ok(Self { config, experimental, ..Default::default() }) } /// Adds a block to the indentation level of the current [`Shape`]. pub fn indent(&mut self) { self.shape.block_indent(&self.config); } /// Removes a block from the indentation level of the current [`Shape`]. pub fn unindent(&mut self) { self.shape.block_unindent(&self.config); } /// Returns the [`Shape`]'s indentation blocks as a `Cow<'static, str>`. pub fn indent_to_str(&self) -> Result<Cow<'static, str>, FormatterError> { self.shape.indent.to_string(&self.config) } /// Checks the current level of indentation before writing the indent str into the buffer. pub fn write_indent_into_buffer( &self, formatted_code: &mut FormattedCode, ) -> Result<(), FormatterError> { let indent_str = self.indent_to_str()?; if !formatted_code.ends_with(indent_str.as_ref()) { write!(formatted_code, "{indent_str}")? } Ok(()) } /// Collect a mapping of Span -> Comment from unformatted input. pub fn with_comments_context(&mut self, src: &str) -> Result<&mut Self, FormatterError> { let comments_context = CommentsContext::new(CommentMap::from_src(src.into())?, src.to_string()); self.comments_context = comments_context; Ok(self) } pub fn format(&mut self, src: Source) -> Result<FormattedCode, FormatterError> { let annotated_module = parse_file(src, self.experimental)?; self.format_module(&annotated_module) } pub fn format_module( &mut self, annotated_module: &Annotated<Module>, ) -> Result<FormattedCode, FormatterError> { // apply the width heuristics settings from the `Config` self.shape.apply_width_heuristics( self.config .heuristics .heuristics_pref .to_width_heuristics(self.config.whitespace.max_width), ); // Get the original trimmed source code. let module_kind_span = annotated_module.value.kind.span(); let src = module_kind_span.src().text.trim(); // Formatted code will be pushed here with raw newline style. // Which means newlines are not converted into system-specific versions until `apply_newline_style()`. // Use the length of src as a hint of the memory size needed for `raw_formatted_code`, // which will reduce the number of reallocations let mut raw_formatted_code = String::with_capacity(src.len()); self.with_comments_context(src)?; annotated_module.format(&mut raw_formatted_code, self)?; let mut formatted_code = String::from(&raw_formatted_code); // Write post-module comments write_comments( &mut formatted_code, annotated_module.value.span().end()..src.len() + 1, self, )?; // Add newline sequences handle_newlines( Arc::from(src), &annotated_module.value, formatted_code.as_str().into(), &mut formatted_code, self, )?; // Replace newlines with specified `NewlineStyle` apply_newline_style( self.config.whitespace.newline_style, &mut formatted_code, &raw_formatted_code, )?; if !formatted_code.ends_with('\n') { writeln!(formatted_code)?; } Ok(formatted_code) } pub(crate) fn with_shape<F, O>(&mut self, new_shape: Shape, f: F) -> O where F: FnOnce(&mut Self) -> O, { let prev_shape = self.shape; self.shape = new_shape; let output = f(self); self.shape = prev_shape; output // used to extract an output if needed } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/mod.rs
swayfmt/src/utils/mod.rs
use crate::formatter::*; use std::fmt::Write; use sway_types::ast::PunctKind; pub(crate) mod language; pub(crate) mod map; pub(crate) trait CurlyBrace { /// Handles brace open scenario. Checks the config for the placement of the brace. /// Modifies the current shape of the formatter. fn open_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError>; /// Handles brace close scenario. /// Currently it simply pushes a `}` and modifies the shape. fn close_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError>; } pub(crate) trait SquareBracket { fn open_square_bracket( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError>; fn close_square_bracket( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError>; } pub(crate) trait Parenthesis { /// Handles open parenthesis scenarios, checking the config for placement /// and modifying the shape of the formatter where necessary. fn open_parenthesis( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError>; /// Handles the closing parenthesis scenario. fn close_parenthesis( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError>; } pub(crate) fn open_angle_bracket(formatted_code: &mut FormattedCode) -> Result<(), FormatterError> { write!(formatted_code, "{}", PunctKind::LessThan.as_char())?; Ok(()) } pub(crate) fn close_angle_bracket( formatted_code: &mut FormattedCode, ) -> Result<(), FormatterError> { write!(formatted_code, "{}", PunctKind::GreaterThan.as_char())?; Ok(()) } pub(crate) fn colon(formatted_code: &mut FormattedCode) -> Result<(), FormatterError> { write!(formatted_code, "{}", PunctKind::Colon.as_char())?; Ok(()) }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/map/comments.rs
swayfmt/src/utils/map/comments.rs
use super::byte_span; use crate::{formatter::FormatterError, parse::lex, utils::map::byte_span::ByteSpan}; use std::{ collections::BTreeMap, ops::{ Bound::{Excluded, Included}, Deref, DerefMut, Range, }, }; use sway_ast::token::{Comment, CommentedTokenTree, CommentedTree}; use sway_types::span::Source; #[derive(Clone, Default, Debug)] pub struct CommentMap(pub BTreeMap<ByteSpan, Comment>); impl Deref for CommentMap { type Target = BTreeMap<ByteSpan, Comment>; fn deref(&self) -> &BTreeMap<ByteSpan, Comment> { &self.0 } } impl DerefMut for CommentMap { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl CommentMap { pub fn new() -> Self { Self(BTreeMap::new()) } /// Get the CommentedTokenStream and collect the spans -> Comment mapping for the input source /// code. pub fn from_src(input: Source) -> Result<Self, FormatterError> { // Pass the input through the lexer. let tts = lex(input)?; let tts = tts.token_trees().iter(); let mut comment_map = CommentMap::new(); for comment in tts { comment_map.collect_comments_from_token_stream(comment); } Ok(comment_map) } /// Given a range, return an iterator to comments contained within the range. pub fn comments_between<'a>( &'a self, range: &'a Range<usize>, ) -> impl Iterator<Item = &'a Comment> { self.iter().filter_map(|(bs, c)| { if bs.contained_within(range) { Some(c) } else { None } }) } /// Collects `Comment`s from the token stream and insert it with its span to the `CommentMap`. /// Handles both the standalone and in-block comments. fn collect_comments_from_token_stream(&mut self, commented_token_tree: &CommentedTokenTree) { match commented_token_tree { CommentedTokenTree::Comment(comment) => { let comment_span = ByteSpan { start: comment.span.start(), end: comment.span.end(), }; self.insert(comment_span, comment.clone()); } CommentedTokenTree::Tree(CommentedTree::Group(group)) => { for item in group.token_stream.token_trees().iter() { self.collect_comments_from_token_stream(item); } } _ => {} } } } trait CommentRange { /// Get comments in between given ByteSpans. This is wrapper around BtreeMap::range with a custom logic for beginning of the file. fn comments_in_range(&self, from: &ByteSpan, to: &ByteSpan) -> Vec<(ByteSpan, Comment)>; } impl CommentRange for CommentMap { fn comments_in_range(&self, from: &ByteSpan, to: &ByteSpan) -> Vec<(ByteSpan, Comment)> { // While searching for comments with given range, comment handler needs to check if the beginning of the range is actually the beginning of the file. // If that is the case we need to collect all the comments until the provided `to` ByteSpan. BtreeMap::range((Inclusive(from), Excluded(to))) won't be able to find comments // since both beginning of the file and first byte span have their start = 0. If we are looking from STARTING_BYTE_SPAN to `to`, we need to collect all until `to` byte span. if from == &byte_span::STARTING_BYTE_SPAN { self.range(..to) .map(|(byte_span, comment)| (byte_span.clone(), comment.clone())) .collect() } else { self.range((Included(from), Excluded(to))) .map(|(byte_span, comment)| (byte_span.clone(), comment.clone())) .collect() } } } #[cfg(test)] mod tests { use super::ByteSpan; use crate::utils::map::comments::{CommentMap, CommentRange}; use std::ops::Bound::Included; #[test] fn test_comment_span_map_standalone_comment() { let input = r#" // Single-line comment. let var = 256; // This is a comment. struct Foo { /* multi- * line- * comment */ bar: i32, } "#; let map = CommentMap::from_src(input.into()).unwrap(); assert!(!map.is_empty()); let range_start_span = ByteSpan { start: 0, end: 32 }; let range_end_span = ByteSpan { start: 33, end: 34 }; let found_comment = map .range((Included(range_start_span), Included(range_end_span))) .last() .unwrap(); assert_eq!(found_comment.1.span.as_str(), "// Single-line comment."); } #[test] fn test_comment_span_map_standalone_next_to_item() { let input = r#" // Single-line comment. let var = 256; // This is a comment. struct Foo { /* multi- * line- * comment */ bar: i32, } "#; let map = CommentMap::from_src(input.into()).unwrap(); assert!(!map.is_empty()); let range_start_span = ByteSpan { start: 40, end: 54 }; let range_end_span = ByteSpan { start: 100, end: 115, }; let found_comment = map .range((Included(range_start_span), Included(range_end_span))) .last() .unwrap(); assert_eq!(found_comment.1.span.as_str(), "// This is a comment."); } #[test] fn test_comment_span_map_standalone_inside_block() { let input = r#" // Single-line comment. let var = 256; // This is a comment. struct Foo { /* multi- * line- * comment */ bar: i32, } "#; let map = CommentMap::from_src(input.into()).unwrap(); assert!(!map.is_empty()); let range_start_span = ByteSpan { start: 110, end: 116, }; let range_end_span = ByteSpan { start: 200, end: 201, }; let found_comment = map .range((Included(range_start_span), Included(range_end_span))) .last() .unwrap(); assert_eq!( found_comment.1.span.as_str(), "/* multi-\n * line-\n * comment */" ); } #[test] fn test_comment_map_range_from_start() { let range_start_span = ByteSpan { start: 0, end: 0 }; let range_end_span = ByteSpan { start: 8, end: 16 }; let input = r#"// test contract;"#; let map = CommentMap::from_src(input.into()).unwrap(); assert!(!map.is_empty()); let found_comments = map.comments_in_range(&range_start_span, &range_end_span); assert_eq!(found_comments[0].1.span.as_str(), "// test"); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/map/byte_span.rs
swayfmt/src/utils/map/byte_span.rs
use std::{cmp::Ordering, ops::Range}; use sway_ast::{ attribute::Annotated, brackets::{Parens, SquareBrackets}, keywords::{ AddToken, ColonToken, CommaToken, ForToken, ForwardSlashToken, RightArrowToken, SemicolonToken, }, Braces, TypeField, }; use sway_parse::Parse; use sway_types::{Ident, Span, Spanned}; /// This represents the beginning of the file and if during searching we found STARTING_BYTE_SPAN, a custom logic is needed. /// Because if there are comments in between at the beginning before program kind, we will be searching between {start: 0, end:0} to {start:0, end:x}. /// Searching in that range would never return a comment since the way we order ByteSpans ensures that encapsulating spans are always coming later than the smaller ones. pub(crate) const STARTING_BYTE_SPAN: ByteSpan = ByteSpan { start: 0, end: 0 }; /// A stripped down version of sway-types::src::Span #[derive(Eq, PartialEq, Debug, Clone, Default)] pub struct ByteSpan { // The byte position in the string of the start of the span. pub start: usize, // The byte position in the string of the end of the span. pub end: usize, } impl From<Span> for ByteSpan { /// Takes `start` and `end` from `sway::types::Span` and constructs a `ByteSpan` fn from(span: Span) -> Self { ByteSpan { start: span.start(), end: span.end(), } } } impl ByteSpan { pub fn len(&self) -> usize { self.end - self.start } /// Checks that the ByteSpan referenced by Self is encapsulated by a given Range<usize>. /// This range is inclusive to account for the start and end of the file. pub fn contained_within(&self, range: &Range<usize>) -> bool { range.start <= self.start && self.end <= range.end } } impl Ord for ByteSpan { fn cmp(&self, other: &Self) -> Ordering { // If the starting position is the same encapsulating span (i.e, wider one) should come // first. match self.start.cmp(&other.start) { Ordering::Equal => other.end.cmp(&self.end), ord => ord, } } } impl PartialOrd for ByteSpan { fn partial_cmp(&self, other: &ByteSpan) -> Option<Ordering> { Some(self.cmp(other)) } } /// While searching for a structure we need the possible places that structure can be placed inside the code /// `leaf_spans` collects all field spans so that we can check in between them. pub trait LeafSpans { fn leaf_spans(&self) -> Vec<ByteSpan>; } impl<T> LeafSpans for Braces<T> where T: LeafSpans + Clone, { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); let mut opening_brace_span = ByteSpan::from(self.span()); opening_brace_span.end = opening_brace_span.start + 1; // Add opening brace's ByteSpan collected_spans.push(opening_brace_span); // Add T's collected ByteSpan collected_spans.append(&mut self.clone().into_inner().leaf_spans()); let mut closing_brace_span = ByteSpan::from(self.span()); closing_brace_span.start = closing_brace_span.end - 1; // Add closing brace's ByteSpan collected_spans.push(closing_brace_span); collected_spans } } impl<T> LeafSpans for Parens<T> where T: LeafSpans + Clone, { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); let mut opening_paren_span = ByteSpan::from(self.span()); opening_paren_span.end = opening_paren_span.start + 1; // Add opening paren's span collected_spans.push(opening_paren_span); // Add T's collected ByteSpan collected_spans.append(&mut self.clone().into_inner().leaf_spans()); let mut closing_paren_span = ByteSpan::from(self.span()); closing_paren_span.start = closing_paren_span.end - 1; // Add closing paren's ByteSpan collected_spans.push(closing_paren_span); collected_spans } } impl<T> LeafSpans for SquareBrackets<T> where T: LeafSpans + Clone, { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); let mut opening_bracket_span = ByteSpan::from(self.span()); opening_bracket_span.end = opening_bracket_span.start + 1; // Add opening bracket's span collected_spans.push(opening_bracket_span); // Add T's collected ByteSpan collected_spans.append(&mut self.clone().into_inner().leaf_spans()); let mut closing_bracket_span = ByteSpan::from(self.span()); closing_bracket_span.start = closing_bracket_span.end - 1; // Add closing bracket's ByteSpan collected_spans.push(closing_bracket_span); collected_spans } } impl<T, P> LeafSpans for (T, P) where T: LeafSpans, P: LeafSpans, { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = self.0.leaf_spans(); collected_spans.append(&mut self.1.leaf_spans()); collected_spans } } impl<T> LeafSpans for Vec<T> where T: LeafSpans, { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); for t in self { collected_spans.append(&mut t.leaf_spans()); } collected_spans } } impl<T> LeafSpans for Annotated<T> where T: LeafSpans + Parse, { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = self.attributes.leaf_spans(); collected_spans.append(&mut self.value.leaf_spans()); collected_spans } } impl LeafSpans for Ident { fn leaf_spans(&self) -> Vec<ByteSpan> { vec![ByteSpan::from(self.span())] } } impl LeafSpans for CommaToken { fn leaf_spans(&self) -> Vec<ByteSpan> { vec![(ByteSpan::from(self.span()))] } } impl LeafSpans for TypeField { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); } collected_spans.push(ByteSpan::from(self.name.span())); collected_spans.push(ByteSpan::from(self.colon_token.span())); collected_spans.append(&mut self.ty.leaf_spans()); collected_spans } } impl LeafSpans for AddToken { fn leaf_spans(&self) -> Vec<ByteSpan> { vec![ByteSpan::from(self.span())] } } impl LeafSpans for SemicolonToken { fn leaf_spans(&self) -> Vec<ByteSpan> { vec![ByteSpan::from(self.span())] } } impl LeafSpans for ColonToken { fn leaf_spans(&self) -> Vec<ByteSpan> { vec![ByteSpan::from(self.span())] } } impl LeafSpans for RightArrowToken { fn leaf_spans(&self) -> Vec<ByteSpan> { vec![ByteSpan::from(self.span())] } } impl LeafSpans for ForToken { fn leaf_spans(&self) -> Vec<ByteSpan> { vec![ByteSpan::from(self.span())] } } impl LeafSpans for ForwardSlashToken { fn leaf_spans(&self) -> Vec<ByteSpan> { vec![ByteSpan::from(self.span())] } } #[cfg(test)] mod tests { use super::ByteSpan; #[test] fn test_byte_span_ordering() { let first_span = ByteSpan { start: 2, end: 6 }; let second_span = ByteSpan { start: 2, end: 4 }; let third_span = ByteSpan { start: 4, end: 7 }; let mut vec = [second_span.clone(), third_span.clone(), first_span.clone()]; vec.sort(); assert_eq!(vec[0], first_span); assert_eq!(vec[1], second_span); assert_eq!(vec[2], third_span); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/map/mod.rs
swayfmt/src/utils/map/mod.rs
pub(crate) mod byte_span; pub(crate) mod comments; pub(crate) mod newline; pub(crate) mod newline_style;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/map/newline.rs
swayfmt/src/utils/map/newline.rs
use anyhow::Result; use ropey::{str_utils::byte_to_char_idx, Rope}; use std::{collections::BTreeMap, fmt::Display, sync::Arc}; use sway_ast::Module; use sway_types::span::Source; use crate::{ constants::NEW_LINE, formatter::{FormattedCode, Formatter}, parse::parse_file, utils::map::byte_span::{ByteSpan, LeafSpans}, FormatterError, }; /// Represents a series of consecutive newlines #[derive(Debug, Clone, PartialEq)] struct NewlineSequence { sequence_length: usize, } impl Display for NewlineSequence { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", (0..self.sequence_length - 1) .map(|_| NEW_LINE) .collect::<String>() ) } } type NewlineMap = BTreeMap<ByteSpan, NewlineSequence>; /// Checks if there is a new line at the current position of the rope #[inline] fn is_new_line_in_rope(rope: &Rope, index: usize) -> bool { for (p, new_line) in NEW_LINE.chars().enumerate() { if rope.get_char(index + p) != Some(new_line) { return false; } } true } /// Search for newline sequences in the unformatted code and collect ByteSpan -> NewlineSequence for the input source fn newline_map_from_src(unformatted_input: &str) -> Result<NewlineMap, FormatterError> { let mut newline_map = BTreeMap::new(); // Iterate over the unformatted source code to find NewlineSequences let mut input_iter = unformatted_input.chars().peekable(); let mut current_sequence_length = 0; let mut in_sequence = false; let mut sequence_start = 0; let mut bytes_offset = 0; while let Some(char) = input_iter.next() { // Keep of byte offset for each char, it is used for indexing the // unformatted input (to replace the newline sequences with correct // amount of newlines). The code downstream deal with a vector of bytes // and not utf-8 chars. let char_index = bytes_offset; bytes_offset += char.len_utf8(); let next_char = input_iter.peek(); let is_new_line = unformatted_input .get(char_index..char_index + NEW_LINE.len()) .map(|c| c == NEW_LINE) .unwrap_or(false); let is_new_line_next = unformatted_input .get(char_index + 1..char_index + 1 + NEW_LINE.len()) .map(|c| c == NEW_LINE) .unwrap_or(false); if matches!(char, ';' | '}') && is_new_line_next { if !in_sequence { sequence_start = char_index + NEW_LINE.len(); in_sequence = true; } } else if is_new_line && in_sequence { current_sequence_length += 1; } if (Some(&'}') == next_char || Some(&'(') == next_char) && in_sequence { // If we are in a sequence and find `}`, abort the sequence current_sequence_length = 0; in_sequence = false; } if next_char == Some(&' ') || next_char == Some(&'\t') { continue; } if !is_new_line_next && current_sequence_length > 0 && in_sequence { // Next char is not a newline so this is the end of the sequence let byte_span = ByteSpan { start: sequence_start, end: char_index, }; let newline_sequence = NewlineSequence { sequence_length: current_sequence_length, }; newline_map.insert(byte_span, newline_sequence); current_sequence_length = 0; in_sequence = false; } } Ok(newline_map) } /// Handle newlines by first creating a NewlineMap which is used for fast searching extra newlines. /// Traverses items for finding a newline sequence in unformatted input and placing it in correct place in formatted output. pub fn handle_newlines( unformatted_input: Arc<str>, unformatted_module: &Module, formatted_input: Source, formatted_code: &mut FormattedCode, formatter: &Formatter, ) -> Result<(), FormatterError> { // Get newline threshold from config let newline_threshold = formatter.config.whitespace.newline_threshold; // Collect ByteSpan -> NewlineSequence mapping from unformatted input. // // We remove the extra whitespace the beginning of a file before creating a map of newlines. // This is to avoid conflicts with logic that determine comment formatting, and ensure // formatting the code a second time will still produce the same result. let newline_map = newline_map_from_src(&unformatted_input)?; // After the formatting existing items should be the same (type of the item) but their spans will be changed since we applied formatting to them. let formatted_module = parse_file(formatted_input, formatter.experimental)?.value; // Actually find & insert the newline sequences add_newlines( newline_map, unformatted_module, &formatted_module, formatted_code, unformatted_input, newline_threshold, &formatter.removed_spans, )?; Ok(()) } #[inline] /// Tiny function that safely calculates the offset where the offset is a i64 /// (it may be negative). If the offset is a negative number and the result of /// doing the offset would have panic (because usize cannot be negative) the /// unmodified base would be returned fn calculate_offset(base: usize, offset: i64) -> usize { offset .checked_add(base as i64) .unwrap_or(base as i64) .try_into() .unwrap_or(base) } /// Adds the newlines from newline_map to correct places in the formatted code. This requires us /// both the unformatted and formatted code's modules as they will have different spans for their /// visitable positions. While traversing the unformatted module, `add_newlines` searches for newline sequences. If there is a newline sequence found /// it places the sequence to the correct place at formatted_code. /// /// This requires both the unformatted_code itself and the parsed version of it, because /// unformatted_code is used for context lookups and unformatted_module is required for actual /// traversal. fn add_newlines( newline_map: NewlineMap, unformatted_module: &Module, formatted_module: &Module, formatted_code: &mut FormattedCode, unformatted_code: Arc<str>, newline_threshold: usize, removed_spans: &[(usize, usize)], ) -> Result<(), FormatterError> { let mut unformatted_newline_spans = unformatted_module.leaf_spans(); let mut formatted_newline_spans = formatted_module.leaf_spans(); // Adding end of file to both spans so that last newline sequence(s) after an item would also be // found & included unformatted_newline_spans.push(ByteSpan { start: unformatted_code.len(), end: unformatted_code.len(), }); formatted_newline_spans.push(ByteSpan { start: formatted_code.len(), end: formatted_code.len(), }); // Since we are adding newline sequences into the formatted code, in the next iteration the spans we find for the formatted code needs to be offsetted // as the total length of newline sequences we added in previous iterations. let mut offset = 0; // We will definitely have a span in the collected span since for a source code to be parsed there should be some tokens present. let mut previous_unformatted_newline_span = unformatted_newline_spans .first() .ok_or(FormatterError::NewlineSequenceError)?; let mut previous_formatted_newline_span = formatted_newline_spans .first() .ok_or(FormatterError::NewlineSequenceError)?; // Check if AST structure changed during formatting (e.g., braces removed from imports) if !removed_spans.is_empty() { // When AST structure changed, directly map newline positions from unformatted to formatted newline_map.iter().try_fold( 0_i64, |mut offset, (newline_span, newline_sequence)| -> Result<i64, FormatterError> { let formatted_pos = map_unformatted_to_formatted_position(newline_span.end, removed_spans); offset += insert_after_span( calculate_offset(formatted_pos, offset), newline_sequence.clone(), formatted_code, newline_threshold, )?; Ok(offset) }, )?; return Ok(()); } for (unformatted_newline_span, formatted_newline_span) in unformatted_newline_spans .iter() .skip(1) .zip(formatted_newline_spans.iter().skip(1)) { if previous_unformatted_newline_span.end < unformatted_newline_span.start { // At its core, the spaces between leaf spans are nothing more than just whitespace characters, // and sometimes comments, since they are not considered valid AST nodes. We are interested in // these spaces (with comments, if any) let whitespaces_with_comments = &unformatted_code [previous_unformatted_newline_span.end..unformatted_newline_span.start]; let mut whitespaces_with_comments_it = whitespaces_with_comments.char_indices().peekable(); let start = previous_unformatted_newline_span.end; let mut comment_found = false; // Here, we will try to insert newlines that occur before comments. while let Some((idx, character)) = whitespaces_with_comments_it.next() { if character == '/' { if let Some((_, '/') | (_, '*')) = whitespaces_with_comments_it.peek() { comment_found = true; // Insert newlines that occur before the first comment here if let Some(newline_sequence) = first_newline_sequence_in_span( &ByteSpan { start, end: start + idx, }, &newline_map, ) { offset += insert_after_span( calculate_offset(previous_formatted_newline_span.end, offset), newline_sequence, formatted_code, newline_threshold, )?; break; } } } // If there are no comments found in the sequence of whitespaces, there is no point // in trying to find newline sequences from the back. So we simply take the entire // sequence, insert newlines at the start and we're done with this iteration of the for loop. if idx == whitespaces_with_comments.len() - 1 && !comment_found { if let Some(newline_sequence) = first_newline_sequence_in_span( &ByteSpan { start, end: unformatted_newline_span.start, }, &newline_map, ) { offset += insert_after_span( calculate_offset(previous_formatted_newline_span.end, offset), newline_sequence, formatted_code, newline_threshold, )?; } } } // If we found some comment(s), we are also interested in inserting // newline sequences that happen after the last comment. // // This can be a single comment or multiple comments. if comment_found { let mut whitespaces_with_comments_rev_it = whitespaces_with_comments.char_indices().rev().peekable(); let mut end_of_last_comment = whitespaces_with_comments.len(); // Find point of insertion of newline sequences for (idx, character) in whitespaces_with_comments_rev_it.by_ref() { if !character.is_whitespace() { end_of_last_comment = idx + 1; break; } } let mut prev_character = None; while let Some((_, character)) = whitespaces_with_comments_rev_it.next() { if character == '/' { // Comments either start with '//' or end with '*/' let next_character = whitespaces_with_comments_rev_it.peek().map(|(_, c)| *c); if next_character == Some('/') || prev_character == Some('*') { if let Some(newline_sequence) = first_newline_sequence_in_span( &ByteSpan { start: start + end_of_last_comment, end: unformatted_newline_span.start, }, &newline_map, ) { offset += insert_after_span( calculate_offset( previous_formatted_newline_span.end + end_of_last_comment, offset, ), newline_sequence, formatted_code, newline_threshold, )?; } break; } } prev_character = Some(character); } } } previous_unformatted_newline_span = unformatted_newline_span; previous_formatted_newline_span = formatted_newline_span; } Ok(()) } fn format_newline_sequence(newline_sequence: &NewlineSequence, threshold: usize) -> String { if newline_sequence.sequence_length > threshold { (0..threshold).map(|_| NEW_LINE).collect::<String>() } else { newline_sequence.to_string() } } #[inline] fn is_alphanumeric(c: char) -> bool { c.is_alphanumeric() || c == '_' || c == '.' } /// Inserts a `NewlineSequence` at position `at` and returns the length of `NewlineSequence` inserted. /// The return value is used to calculate the new `at` in a later point. fn insert_after_span( at: usize, newline_sequence: NewlineSequence, formatted_code: &mut FormattedCode, threshold: usize, ) -> Result<i64, FormatterError> { let sequence_string = format_newline_sequence(&newline_sequence, threshold); let mut len = sequence_string.len() as i64; let mut src_rope = Rope::from_str(formatted_code); let at = byte_to_char_idx(formatted_code, at); // Remove the previous sequence_length, that will be replaced in the next statement let mut remove_until = at; for i in at..at + newline_sequence.sequence_length { if !is_new_line_in_rope(&src_rope, i) { break; } remove_until = i; } let removed = if remove_until > at { src_rope .try_remove(at..remove_until) .map_err(|_| FormatterError::NewlineSequenceError)?; let removed = (remove_until - at) as i64; len -= removed; removed } else { 0 }; // Do never insert the newline sequence between two alphanumeric characters let is_token = src_rope .get_char(at) .map(is_alphanumeric) .unwrap_or_default() && src_rope .get_char(at + 1) .map(is_alphanumeric) .unwrap_or_default(); if !is_token { src_rope .try_insert(at, &sequence_string) .map_err(|_| FormatterError::NewlineSequenceError)?; } else { len = -removed; } formatted_code.clear(); formatted_code.push_str(&src_rope.to_string()); Ok(len) } /// Returns the first newline sequence contained in a span. /// This is inclusive at the start, and exclusive at the end, i.e. /// the bounds are [span.start, span.end). fn first_newline_sequence_in_span( span: &ByteSpan, newline_map: &NewlineMap, ) -> Option<NewlineSequence> { for (range, sequence) in newline_map.iter() { if span.start <= range.start && range.end < span.end { return Some(sequence.clone()); } } None } /// Maps an unformatted byte position to the corresponding formatted byte position /// by accounting for removed spans during formatting. /// /// For example, if we removed 2 bytes at position 22 (e.g., '{' and '}'), /// then position 40 in unformatted maps to position 38 in formatted. fn map_unformatted_to_formatted_position( unformatted_pos: usize, removed_spans: &[(usize, usize)], ) -> usize { // Sum all bytes removed before this position let total_removed = removed_spans .iter() .filter(|(removed_pos, _)| *removed_pos < unformatted_pos) .map(|(_, removed_count)| removed_count) .sum::<usize>(); unformatted_pos.saturating_sub(total_removed) } #[cfg(test)] mod tests { use crate::utils::map::{byte_span::ByteSpan, newline::first_newline_sequence_in_span}; use super::{newline_map_from_src, NewlineMap, NewlineSequence}; #[test] fn test_newline_map() { let raw_src = r#"script; fn main() { let number: u64 = 10; let number2: u64 = 20; let number3: u64 = 30; }"#; let newline_map = newline_map_from_src(raw_src.trim_start()).unwrap(); let newline_sequence_lengths = Vec::from_iter( newline_map .iter() .map(|map_item| map_item.1.sequence_length), ); let correct_newline_sequence_lengths = vec![2, 2, 3]; assert_eq!(newline_sequence_lengths, correct_newline_sequence_lengths); } #[test] fn test_newline_map_with_whitespaces() { let raw_src = r#"script; fuel_coin.mint { gas: default_gas } (11);"#; let newline_map = newline_map_from_src(raw_src.trim_start()).unwrap(); let newline_sequence_lengths = Vec::from_iter( newline_map .iter() .map(|map_item| map_item.1.sequence_length), ); let correct_newline_sequence_lengths = vec![1]; assert_eq!(newline_sequence_lengths, correct_newline_sequence_lengths); } #[test] fn test_newline_range_simple() { let mut newline_map = NewlineMap::new(); let newline_sequence = NewlineSequence { sequence_length: 2 }; newline_map.insert(ByteSpan { start: 9, end: 10 }, newline_sequence.clone()); assert_eq!( newline_sequence, first_newline_sequence_in_span(&ByteSpan { start: 8, end: 11 }, &newline_map).unwrap() ); assert_eq!( newline_sequence, first_newline_sequence_in_span(&ByteSpan { start: 9, end: 11 }, &newline_map).unwrap() ); assert!( first_newline_sequence_in_span(&ByteSpan { start: 9, end: 10 }, &newline_map).is_none() ); assert!( first_newline_sequence_in_span(&ByteSpan { start: 9, end: 9 }, &newline_map).is_none() ); assert!( first_newline_sequence_in_span(&ByteSpan { start: 8, end: 8 }, &newline_map).is_none() ); } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/map/newline_style.rs
swayfmt/src/utils/map/newline_style.rs
//! Functions and tests that determine and apply the user defined [NewlineStyle]. use crate::{ config::whitespace::{NewlineStyle, NewlineSystemType}, constants::{CARRIAGE_RETURN, LINE_FEED, UNIX_NEWLINE, WINDOWS_NEWLINE}, FormatterError, }; use std::fmt::Write; /// Apply this newline style to the formatted text. When the style is set /// to `Auto`, the `raw_input_text` is used to detect the existing line /// endings. /// /// If the style is set to `Auto` and `raw_input_text` contains no /// newlines, the `Native` style will be used. pub(crate) fn apply_newline_style( newline_style: NewlineStyle, formatted_text: &mut String, raw_input_text: &str, ) -> Result<(), FormatterError> { *formatted_text = match NewlineSystemType::get_newline_style(newline_style, raw_input_text) { NewlineSystemType::Windows => convert_to_windows_newlines(formatted_text)?, NewlineSystemType::Unix => convert_to_unix_newlines(formatted_text), }; Ok(()) } fn convert_to_windows_newlines(formatted_text: &String) -> Result<String, FormatterError> { let mut transformed = String::with_capacity(2 * formatted_text.capacity()); let mut chars = formatted_text.chars().peekable(); while let Some(current_char) = chars.next() { let next_char = chars.peek(); match current_char { LINE_FEED => write!(transformed, "{WINDOWS_NEWLINE}")?, CARRIAGE_RETURN if next_char == Some(&LINE_FEED) => {} current_char => write!(transformed, "{current_char}")?, } } Ok(transformed) } fn convert_to_unix_newlines(formatted_text: &str) -> String { formatted_text.replace(WINDOWS_NEWLINE, UNIX_NEWLINE) } #[cfg(test)] mod tests { use super::*; #[test] fn auto_detects_unix_newlines() { assert_eq!( NewlineSystemType::Unix, NewlineSystemType::auto_detect_newline_style("One\nTwo\nThree") ); } #[test] fn auto_detects_windows_newlines() { assert_eq!( NewlineSystemType::Windows, NewlineSystemType::auto_detect_newline_style("One\r\nTwo\r\nThree") ); } #[test] fn auto_detects_windows_newlines_with_multibyte_char_on_first_line() { assert_eq!( NewlineSystemType::Windows, NewlineSystemType::auto_detect_newline_style("A 🎢 of a first line\r\nTwo\r\nThree") ); } #[test] fn falls_back_to_native_newlines_if_no_newlines_are_found() { let expected_newline_style = if cfg!(windows) { NewlineSystemType::Windows } else { NewlineSystemType::Unix }; assert_eq!( expected_newline_style, NewlineSystemType::auto_detect_newline_style("One Two Three") ); } #[test] fn auto_detects_and_applies_unix_newlines() -> Result<(), FormatterError> { let formatted_text = "One\nTwo\nThree"; let raw_input_text = "One\nTwo\nThree"; let mut out = String::from(formatted_text); apply_newline_style(NewlineStyle::Auto, &mut out, raw_input_text)?; assert_eq!("One\nTwo\nThree", &out, "auto should detect 'lf'"); Ok(()) } #[test] fn auto_detects_and_applies_windows_newlines() -> Result<(), FormatterError> { let formatted_text = "One\nTwo\nThree"; let raw_input_text = "One\r\nTwo\r\nThree"; let mut out = String::from(formatted_text); apply_newline_style(NewlineStyle::Auto, &mut out, raw_input_text)?; assert_eq!("One\r\nTwo\r\nThree", &out, "auto should detect 'crlf'"); Ok(()) } #[test] fn auto_detects_and_applies_native_newlines() -> Result<(), FormatterError> { let formatted_text = "One\nTwo\nThree"; let raw_input_text = "One Two Three"; let mut out = String::from(formatted_text); apply_newline_style(NewlineStyle::Auto, &mut out, raw_input_text)?; if cfg!(windows) { assert_eq!( "One\r\nTwo\r\nThree", &out, "auto-native-windows should detect 'crlf'" ); } else { assert_eq!( "One\nTwo\nThree", &out, "auto-native-unix should detect 'lf'" ); } Ok(()) } #[test] fn applies_unix_newlines() -> Result<(), FormatterError> { test_newlines_are_applied_correctly( "One\r\nTwo\nThree", "One\nTwo\nThree", NewlineStyle::Unix, )?; Ok(()) } #[test] fn applying_unix_newlines_changes_nothing_for_unix_newlines() -> Result<(), FormatterError> { let formatted_text = "One\nTwo\nThree"; test_newlines_are_applied_correctly(formatted_text, formatted_text, NewlineStyle::Unix)?; Ok(()) } #[test] fn applies_unix_newlines_to_string_with_unix_and_windows_newlines() -> Result<(), FormatterError> { test_newlines_are_applied_correctly( "One\r\nTwo\r\nThree\nFour", "One\nTwo\nThree\nFour", NewlineStyle::Unix, )?; Ok(()) } #[test] fn applies_windows_newlines_to_string_with_unix_and_windows_newlines( ) -> Result<(), FormatterError> { test_newlines_are_applied_correctly( "One\nTwo\nThree\r\nFour", "One\r\nTwo\r\nThree\r\nFour", NewlineStyle::Windows, )?; Ok(()) } #[test] fn applying_windows_newlines_changes_nothing_for_windows_newlines() -> Result<(), FormatterError> { let formatted_text = "One\r\nTwo\r\nThree"; test_newlines_are_applied_correctly(formatted_text, formatted_text, NewlineStyle::Windows)?; Ok(()) } #[test] fn keeps_carriage_returns_when_applying_windows_newlines_to_str_with_unix_newlines( ) -> Result<(), FormatterError> { test_newlines_are_applied_correctly( "One\nTwo\nThree\rDrei", "One\r\nTwo\r\nThree\rDrei", NewlineStyle::Windows, )?; Ok(()) } #[test] fn keeps_carriage_returns_when_applying_unix_newlines_to_str_with_unix_newlines( ) -> Result<(), FormatterError> { test_newlines_are_applied_correctly( "One\nTwo\nThree\rDrei", "One\nTwo\nThree\rDrei", NewlineStyle::Unix, )?; Ok(()) } #[test] fn keeps_carriage_returns_when_applying_windows_newlines_to_str_with_windows_newlines( ) -> Result<(), FormatterError> { test_newlines_are_applied_correctly( "One\r\nTwo\r\nThree\rDrei", "One\r\nTwo\r\nThree\rDrei", NewlineStyle::Windows, )?; Ok(()) } #[test] fn keeps_carriage_returns_when_applying_unix_newlines_to_str_with_windows_newlines( ) -> Result<(), FormatterError> { test_newlines_are_applied_correctly( "One\r\nTwo\r\nThree\rDrei", "One\nTwo\nThree\rDrei", NewlineStyle::Unix, )?; Ok(()) } fn test_newlines_are_applied_correctly( input: &str, expected: &str, newline_style: NewlineStyle, ) -> Result<(), FormatterError> { let mut out = String::from(input); apply_newline_style(newline_style, &mut out, input)?; assert_eq!(expected, &out); Ok(()) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/attribute.rs
swayfmt/src/utils/language/attribute.rs
use crate::{ comments::write_comments, constants::NEW_LINE, formatter::*, utils::{ map::byte_span::{ByteSpan, LeafSpans}, {Parenthesis, SquareBracket}, }, }; use std::fmt::Write; use sway_ast::{ attribute::{Annotated, Attribute, AttributeArg, AttributeDecl, AttributeHashKind}, keywords::{HashBangToken, HashToken, Token}, CommaToken, }; use sway_types::{ast::Delimiter, Spanned}; impl<T: Format + Spanned + std::fmt::Debug> Format for Annotated<T> { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // format each `Attribute` let mut start = None; for attr in &self.attributes { if let Some(start) = start { // Write any comments that may have been defined in between the // attributes and the value write_comments(formatted_code, start..attr.span().start(), formatter)?; if !formatted_code.ends_with(NEW_LINE) { write!(formatted_code, "{NEW_LINE}")?; } } formatter.write_indent_into_buffer(formatted_code)?; attr.format(formatted_code, formatter)?; start = Some(attr.span().end()); } if let Some(start) = start { // Write any comments that may have been defined in between the // attributes and the value write_comments(formatted_code, start..self.value.span().start(), formatter)?; if !formatted_code.ends_with(NEW_LINE) { write!(formatted_code, "{NEW_LINE}")?; } } // format `ItemKind` formatter.write_indent_into_buffer(formatted_code)?; self.value.format(formatted_code, formatter)?; Ok(()) } } impl Format for AttributeArg { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(formatted_code, "{}", self.name.as_str())?; if let Some(value) = &self.value { write!(formatted_code, " = ")?; value.format(formatted_code, formatter)?; } Ok(()) } } impl LeafSpans for AttributeArg { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); collected_spans.push(ByteSpan::from(self.name.span())); if let Some(value) = &self.value { collected_spans.push(ByteSpan::from(value.span())); } collected_spans } } impl Format for AttributeDecl { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { let (doc_comment_attrs, regular_attrs): (Vec<_>, _) = self .attribute .get() .into_iter() .partition(|a| a.is_doc_comment()); // invariant: doc comment attributes are singleton lists if let Some(attr) = doc_comment_attrs.into_iter().next() { if let Some(Some(doc_comment)) = attr .args .as_ref() .map(|args| args.inner.final_value_opt.as_ref()) { match self.hash_kind { AttributeHashKind::Inner(_) => writeln!( formatted_code, "//!{}", doc_comment.name.as_str().trim_end() )?, AttributeHashKind::Outer(_) => writeln!( formatted_code, "///{}", doc_comment.name.as_str().trim_end() )?, } } return Ok(()); } // invariant: attribute lists cannot be empty // `#` match &self.hash_kind { AttributeHashKind::Inner(_hash_bang_token) => { write!(formatted_code, "{}", HashBangToken::AS_STR)?; } AttributeHashKind::Outer(_hash_token) => { write!(formatted_code, "{}", HashToken::AS_STR)?; } }; // `[` Self::open_square_bracket(formatted_code, formatter)?; let mut regular_attrs = regular_attrs.iter().peekable(); while let Some(attr) = regular_attrs.next() { formatter.with_shape( formatter.shape.with_default_code_line(), |formatter| -> Result<(), FormatterError> { // name e.g. `storage` write!(formatted_code, "{}", attr.name.as_str())?; if let Some(args) = &attr.args { // `(` Self::open_parenthesis(formatted_code, formatter)?; // format and add args e.g. `read, write` args.get().format(formatted_code, formatter)?; // ')' Self::close_parenthesis(formatted_code, formatter)?; }; Ok(()) }, )?; // do not put a separator after the last attribute if regular_attrs.peek().is_some() { write!(formatted_code, "{} ", CommaToken::AS_STR)?; } } // `]\n` Self::close_square_bracket(formatted_code, formatter)?; Ok(()) } } impl SquareBracket for AttributeDecl { fn open_square_bracket( line: &mut String, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Bracket.as_open_char())?; Ok(()) } fn close_square_bracket( line: &mut String, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { writeln!(line, "{}", Delimiter::Bracket.as_close_char())?; Ok(()) } } impl Parenthesis for AttributeDecl { fn open_parenthesis( line: &mut String, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_open_char())?; Ok(()) } fn close_parenthesis( line: &mut String, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_close_char())?; Ok(()) } } impl LeafSpans for AttributeDecl { fn leaf_spans(&self) -> Vec<ByteSpan> { let hash_type_token_span = match &self.hash_kind { AttributeHashKind::Inner(hash_bang_token) => hash_bang_token.span(), AttributeHashKind::Outer(hash_token) => hash_token.span(), }; let mut collected_spans = vec![ByteSpan::from(hash_type_token_span)]; collected_spans.append(&mut self.attribute.leaf_spans()); collected_spans } } impl LeafSpans for Attribute { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.name.span())]; if let Some(args) = &self.args { collected_spans.append(&mut args.leaf_spans()); } collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/path.rs
swayfmt/src/utils/language/path.rs
use crate::{ formatter::*, utils::{ map::byte_span::{ByteSpan, LeafSpans}, {close_angle_bracket, open_angle_bracket}, }, }; use std::{fmt::Write, vec}; use sway_ast::{ keywords::{AsToken, Keyword, Token}, DoubleColonToken, PathExpr, PathExprSegment, PathType, PathTypeSegment, QualifiedPathRoot, }; use sway_types::Spanned; impl Format for PathExpr { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { if let Some((qualified_path_root, _double_colon_token)) = &self.root_opt { if let Some(root) = &qualified_path_root { open_angle_bracket(formatted_code)?; root.clone() .into_inner() .format(formatted_code, formatter)?; close_angle_bracket(formatted_code)?; } write!(formatted_code, "{}", DoubleColonToken::AS_STR)?; } self.prefix.format(formatted_code, formatter)?; for (_double_colon_token, path_expr_segment) in self.suffix.iter() { write!(formatted_code, "{}", DoubleColonToken::AS_STR)?; path_expr_segment.format(formatted_code, formatter)?; } Ok(()) } } impl Format for PathExprSegment { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // name self.name.format(formatted_code, formatter)?; // generics `::<args>` if let Some((_double_colon_token, generic_args)) = &self.generics_opt { write!(formatted_code, "{}", DoubleColonToken::AS_STR)?; generic_args.format(formatted_code, formatter)?; } Ok(()) } } impl Format for QualifiedPathRoot { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { self.ty.format(formatted_code, formatter)?; let (_as_token, path_type) = &self.as_trait; write!(formatted_code, " {} ", AsToken::AS_STR)?; path_type.format(formatted_code, formatter)?; Ok(()) } } impl Format for PathType { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { if let Some((root_opt, _double_colon_token)) = &self.root_opt { if let Some(qualified_path_root) = &root_opt { open_angle_bracket(formatted_code)?; qualified_path_root .clone() .into_inner() .format(formatted_code, formatter)?; close_angle_bracket(formatted_code)?; } write!(formatted_code, "{}", DoubleColonToken::AS_STR)?; } self.prefix.format(formatted_code, formatter)?; for (_double_colon_token, path_type_segment) in self.suffix.iter() { write!(formatted_code, "{}", DoubleColonToken::AS_STR)?; path_type_segment.format(formatted_code, formatter)?; } Ok(()) } } impl Format for PathTypeSegment { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // name write!(formatted_code, "{}", self.name.as_str())?; // generics `::<args>` if let Some((double_colon_opt, generic_args)) = &self.generics_opt { if double_colon_opt.is_some() { write!(formatted_code, "{}", DoubleColonToken::AS_STR)?; } generic_args.format(formatted_code, formatter)?; } Ok(()) } } impl LeafSpans for PathExpr { fn leaf_spans(&self) -> Vec<ByteSpan> { vec![ByteSpan::from(self.span())] } } impl LeafSpans for PathType { fn leaf_spans(&self) -> Vec<ByteSpan> { vec![ByteSpan::from(self.span())] } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/pattern.rs
swayfmt/src/utils/language/pattern.rs
use crate::{ formatter::{ shape::{ExprKind, LineStyle}, *, }, utils::{ map::byte_span::{ByteSpan, LeafSpans}, {CurlyBrace, Parenthesis}, }, }; use std::fmt::Write; use sway_ast::{ keywords::{ColonToken, DoubleDotToken, Keyword, MutToken, RefToken, Token, UnderscoreToken}, Braces, CommaToken, ExprTupleDescriptor, PathExpr, Pattern, PatternStructField, Punctuated, }; use sway_types::{ast::Delimiter, Spanned}; impl Format for Pattern { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { Self::Or { lhs, pipe_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; formatted_code.push_str(" | "); rhs.format(formatted_code, formatter)?; } Self::Wildcard { underscore_token: _, } => formatted_code.push_str(UnderscoreToken::AS_STR), Self::Var { reference, mutable, name, } => { if reference.is_some() { write!(formatted_code, "{} ", RefToken::AS_STR)?; } if mutable.is_some() { write!(formatted_code, "{} ", MutToken::AS_STR)?; } name.format(formatted_code, formatter)?; } Self::AmbiguousSingleIdent(ident) => { ident.format(formatted_code, formatter)?; } Self::Literal(lit) => lit.format(formatted_code, formatter)?, Self::Constant(path) => path.format(formatted_code, formatter)?, Self::Constructor { path, args } => { // TODO: add a check for width of whether to be normal or multiline formatter.with_shape( formatter.shape.with_default_code_line(), |formatter| -> Result<(), FormatterError> { path.format(formatted_code, formatter)?; Self::open_parenthesis(formatted_code, formatter)?; args.get().format(formatted_code, formatter)?; Self::close_parenthesis(formatted_code, formatter)?; Ok(()) }, )?; } Self::Struct { path, fields } => { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::default(), ExprKind::Struct), |formatter| -> Result<(), FormatterError> { // get the length in chars of the code_line in a single line format, // this include the path let mut buf = FormattedCode::new(); let mut temp_formatter = Formatter::default(); temp_formatter .shape .code_line .update_line_style(LineStyle::Inline); format_pattern_struct(path, fields, &mut buf, &mut temp_formatter)?; // get the largest field size and the size of the body let (field_width, body_width) = get_field_width(fields.get(), &mut formatter.clone())?; // changes to the actual formatter let expr_width = buf.chars().count(); formatter.shape.code_line.update_width(expr_width); formatter.shape.get_line_style( Some(field_width), Some(body_width), &formatter.config, ); format_pattern_struct(path, fields, formatted_code, formatter)?; Ok(()) }, )?; } Self::Tuple(args) => { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::default(), ExprKind::Collection), |formatter| -> Result<(), FormatterError> { // get the length in chars of the code_line in a normal line format let mut buf = FormattedCode::new(); let mut temp_formatter = Formatter::default(); let tuple_descriptor = args.get(); tuple_descriptor.format(&mut buf, &mut temp_formatter)?; let body_width = buf.chars().count(); formatter.shape.code_line.update_width(body_width); formatter .shape .get_line_style(None, Some(body_width), &formatter.config); ExprTupleDescriptor::open_parenthesis(formatted_code, formatter)?; tuple_descriptor.format(formatted_code, formatter)?; ExprTupleDescriptor::close_parenthesis(formatted_code, formatter)?; Ok(()) }, )?; } Self::Error(..) => { return Err(FormatterError::SyntaxError); } } Ok(()) } } // Currently these just push their respective chars, we may need to change this impl Parenthesis for Pattern { fn open_parenthesis( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_open_char())?; Ok(()) } fn close_parenthesis( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_close_char())?; Ok(()) } } impl CurlyBrace for Pattern { fn open_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Add opening brace to the same line write!(line, " {}", Delimiter::Brace.as_open_char())?; formatter.indent(); Ok(()) } fn close_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Unindent by one block formatter.unindent(); match formatter.shape.code_line.line_style { LineStyle::Inline => write!(line, "{}", Delimiter::Brace.as_close_char())?, _ => write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?, } Ok(()) } } impl Format for PatternStructField { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { Self::Rest { token: _ } => { write!(formatted_code, "{}", DoubleDotToken::AS_STR)?; } Self::Field { field_name, pattern_opt, } => { write!(formatted_code, "{}", field_name.as_str())?; if let Some((_colon_token, pattern)) = pattern_opt { write!(formatted_code, "{} ", ColonToken::AS_STR)?; pattern.format(formatted_code, formatter)?; } } } Ok(()) } } fn get_field_width( fields: &Punctuated<PatternStructField, CommaToken>, formatter: &mut Formatter, ) -> Result<(usize, usize), FormatterError> { let mut largest_field: usize = 0; let mut body_width: usize = 3; // this is taking into account the opening brace, the following space and the ending brace. for (field, _comma_token) in &fields.value_separator_pairs { let mut field_str = FormattedCode::new(); field.format(&mut field_str, formatter)?; let mut field_length = field_str.chars().count(); field_length += CommaToken::AS_STR.chars().count(); body_width += &field_length + 1; // accounting for the following space if field_length > largest_field { largest_field = field_length; } } if let Some(final_value) = &fields.final_value_opt { let mut field_str = FormattedCode::new(); final_value.format(&mut field_str, formatter)?; let field_length = field_str.chars().count(); body_width += &field_length + 1; // accounting for the following space if field_length > largest_field { largest_field = field_length; } } Ok((largest_field, body_width)) } fn format_pattern_struct( path: &PathExpr, fields: &Braces<Punctuated<PatternStructField, CommaToken>>, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { path.format(formatted_code, formatter)?; Pattern::open_curly_brace(formatted_code, formatter)?; let fields = &fields.get(); match formatter.shape.code_line.line_style { LineStyle::Inline => fields.format(formatted_code, formatter)?, // TODO: add field alignment _ => fields.format(formatted_code, formatter)?, } Pattern::close_curly_brace(formatted_code, formatter)?; Ok(()) } impl LeafSpans for Pattern { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); match self { Pattern::Wildcard { underscore_token } => { collected_spans.push(ByteSpan::from(underscore_token.span())); } Pattern::Or { lhs, pipe_token, rhs, } => { collected_spans.append(&mut lhs.leaf_spans()); collected_spans.push(ByteSpan::from(pipe_token.span())); collected_spans.append(&mut rhs.leaf_spans()); } Pattern::Var { reference, mutable, name, } => { if let Some(reference) = reference { collected_spans.push(ByteSpan::from(reference.span())); } if let Some(mutable) = mutable { collected_spans.push(ByteSpan::from(mutable.span())); } collected_spans.push(ByteSpan::from(name.span())); } Pattern::AmbiguousSingleIdent(ident) => { collected_spans.push(ByteSpan::from(ident.span())); } Pattern::Literal(literal) => { collected_spans.append(&mut literal.leaf_spans()); } Pattern::Constant(constant) => { collected_spans.append(&mut constant.leaf_spans()); } Pattern::Constructor { path, args } => { collected_spans.append(&mut path.leaf_spans()); collected_spans.append(&mut args.leaf_spans()); } Pattern::Struct { path, fields } => { collected_spans.append(&mut path.leaf_spans()); collected_spans.append(&mut fields.leaf_spans()); } Pattern::Tuple(tuple) => { collected_spans.append(&mut tuple.leaf_spans()); } Pattern::Error(spans, _) => { let mut leaf_spans = spans.iter().map(|s| ByteSpan::from(s.clone())).collect(); collected_spans.append(&mut leaf_spans) } } collected_spans } } impl LeafSpans for PatternStructField { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); match self { PatternStructField::Rest { token } => { collected_spans.push(ByteSpan::from(token.span())); } PatternStructField::Field { field_name, pattern_opt, } => { collected_spans.push(ByteSpan::from(field_name.span())); if let Some(pattern) = pattern_opt { collected_spans.push(ByteSpan::from(pattern.0.span())); collected_spans.append(&mut pattern.1.leaf_spans()); } } } collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/where_clause.rs
swayfmt/src/utils/language/where_clause.rs
use crate::{ formatter::*, utils::map::byte_span::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_ast::{ keywords::{ColonToken, Keyword, Token, WhereToken}, CommaToken, WhereBound, WhereClause, }; use sway_types::Spanned; impl Format for WhereClause { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { writeln!( formatted_code, "{}{}", formatter.indent_to_str()?, WhereToken::AS_STR, )?; formatter.indent(); // We should add a multiline field to `Shape` // so we can reduce this code block to: // // ```rust,ignore // self.bounds.format(formatted_code, formatter)?; // ``` // let value_pairs = self.bounds.value_separator_pairs.clone(); for (bound, _comma_token) in value_pairs.iter() { // `WhereBound` bound.format(formatted_code, formatter)?; // `CommaToken` writeln!(formatted_code, "{}", CommaToken::AS_STR)?; } if let Some(final_value) = &self.bounds.final_value_opt { final_value.format(formatted_code, formatter)?; writeln!(formatted_code, "{}", CommaToken::AS_STR)?; } // reset indent formatter.unindent(); Ok(()) } } impl Format for WhereBound { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!( formatted_code, "{}{}{} ", formatter.indent_to_str()?, self.ty_name.as_str(), ColonToken::AS_STR, )?; self.bounds.format(formatted_code, formatter)?; Ok(()) } } impl LeafSpans for WhereBound { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = self.ty_name.leaf_spans(); collected_spans.append(&mut self.colon_token.leaf_spans()); collected_spans.append(&mut self.bounds.leaf_spans()); collected_spans } } impl LeafSpans for WhereClause { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.where_token.span())]; collected_spans.append(&mut self.bounds.leaf_spans()); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/punctuated.rs
swayfmt/src/utils/language/punctuated.rs
use crate::{ constants::RAW_MODIFIER, formatter::{shape::LineStyle, *}, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::fmt::Write; use sway_ast::{ keywords::{ColonToken, CommaToken, EqToken, InToken, Keyword, Token}, punctuated::Punctuated, ConfigurableField, ItemStorage, PubToken, StorageEntry, StorageField, TypeField, }; use sway_types::{ast::PunctKind, Ident, Spanned}; use self::shape::ExprKind; use super::expr::should_write_multiline; impl<T, P> Format for Punctuated<T, P> where T: Format, P: Format, { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { if !self.is_empty() { match formatter.shape.code_line.line_style { LineStyle::Normal => { write!( formatted_code, "{}", format_generic_pair( &self.value_separator_pairs, &self.final_value_opt, formatter )? )?; } LineStyle::Inline => { write!( formatted_code, " {} ", format_generic_pair( &self.value_separator_pairs, &self.final_value_opt, formatter )? )?; } LineStyle::Multiline => { if !formatted_code.ends_with('\n') { writeln!(formatted_code)?; } if !self.is_empty() { formatter.write_indent_into_buffer(formatted_code)?; } let mut is_value_too_long = false; let value_separator_pairs = formatter.with_shape( formatter.shape.with_default_code_line(), |formatter| -> Result<Vec<(String, String)>, FormatterError> { self.value_separator_pairs .iter() .map(|(type_field, comma_token)| { let mut field = FormattedCode::new(); let mut comma = FormattedCode::new(); type_field.format(&mut field, formatter)?; comma_token.format(&mut comma, formatter)?; if field.len() > formatter.shape.width_heuristics.short_array_element_width { is_value_too_long = true; } Ok(( field.trim_start().to_owned(), comma.trim_start().to_owned(), )) }) .collect() }, )?; let mut iter = value_separator_pairs.iter().peekable(); while let Some((type_field, comma_token)) = iter.next() { write!(formatted_code, "{type_field}{comma_token}")?; if iter.peek().is_none() && self.final_value_opt.is_none() { break; } if is_value_too_long || should_write_multiline(formatted_code, formatter) { writeln!(formatted_code)?; formatter.write_indent_into_buffer(formatted_code)?; } else { write!(formatted_code, " ")?; } } if let Some(final_value) = &self.final_value_opt { final_value.format(formatted_code, formatter)?; write!(formatted_code, "{}", PunctKind::Comma.as_char())?; } if !formatted_code.ends_with('\n') { writeln!(formatted_code)?; } } } } Ok(()) } } fn format_generic_pair<T, P>( value_separator_pairs: &[(T, P)], final_value_opt: &Option<Box<T>>, formatter: &mut Formatter, ) -> Result<FormattedCode, FormatterError> where T: Format, P: Format, { let len = value_separator_pairs.len(); let mut ts: Vec<String> = Vec::with_capacity(len); let mut ps: Vec<String> = Vec::with_capacity(len); for (t, p) in value_separator_pairs.iter() { let mut t_buf = FormattedCode::new(); t.format(&mut t_buf, formatter)?; ts.push(t_buf); let mut p_buf = FormattedCode::new(); p.format(&mut p_buf, formatter)?; ps.push(p_buf); } if let Some(final_value) = final_value_opt { let mut buf = FormattedCode::new(); final_value.format(&mut buf, formatter)?; ts.push(buf); } else { // reduce the number of punct by 1 // this is safe since the number of // separator pairs is always equal ps.truncate(ts.len() - 1); } for (t, p) in ts.iter_mut().zip(ps.iter()) { write!(t, "{p}")?; } Ok(ts.join(" ")) } impl<T, P> LeafSpans for Punctuated<T, P> where T: LeafSpans + Clone, P: LeafSpans + Clone, { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); let value_pairs = &self.value_separator_pairs; for pair in value_pairs.iter() { let p_comment_spans = pair.1.leaf_spans(); // Since we do not want to have comments between T and P we are extending the ByteSpans coming from T with spans coming from P // Since formatter can insert a trailing comma after a field, comments next to a field can be falsely inserted between the comma and the field // So we shouldn't allow inserting comments (or searching for one) between T and P as in Punctuated scenario this can/will result in formatting that breaks the build process let mut comment_spans = pair .0 .leaf_spans() .iter_mut() .map(|comment_map| { // Since the length of P' ByteSpan is same for each pair we are using the first one's length for all of the pairs. // This assumption always holds because for each pair P is formatted to same str so the length is going to be the same. // For example when P is CommaToken, the length of P is always 1. comment_map.end += p_comment_spans[0].len(); comment_map.clone() }) .collect(); collected_spans.append(&mut comment_spans) } if let Some(final_value) = &self.final_value_opt { collected_spans.append(&mut final_value.leaf_spans()); } collected_spans } } impl Format for Ident { fn format( &self, formatted_code: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self.is_raw_ident() { true => write!(formatted_code, "{}{}", RAW_MODIFIER, self.as_str())?, false => write!(formatted_code, "{}", self.as_str())?, } Ok(()) } } impl Format for TypeField { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // If there is a visibility token add it to the formatted_code with a ` ` after it. if self.visibility.is_some() { write!(formatted_code, "{} ", PubToken::AS_STR)?; } write!( formatted_code, "{}{} ", self.name.as_raw_ident_str(), ColonToken::AS_STR, )?; self.ty.format(formatted_code, formatter)?; Ok(()) } } impl Format for ConfigurableField { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.with_shape( formatter.shape.with_default_code_line(), |formatter| -> Result<(), FormatterError> { write!( formatted_code, "{}{} ", self.name.as_str(), ColonToken::AS_STR, )?; self.ty.format(formatted_code, formatter)?; write!(formatted_code, " {} ", EqToken::AS_STR)?; Ok(()) }, )?; self.initializer.format(formatted_code, formatter)?; Ok(()) } } impl Format for StorageField { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.with_shape( formatter.shape.with_default_code_line(), |formatter| -> Result<(), FormatterError> { write!(formatted_code, "{}", self.name.as_str())?; if self.in_token.is_some() { write!(formatted_code, " {} ", InToken::AS_STR)?; } if let Some(key_expr) = &self.key_expr { key_expr.format(formatted_code, formatter)?; } write!(formatted_code, "{} ", ColonToken::AS_STR)?; self.ty.format(formatted_code, formatter)?; write!(formatted_code, " {} ", EqToken::AS_STR)?; Ok(()) }, )?; self.initializer.format(formatted_code, formatter)?; Ok(()) } } impl Format for StorageEntry { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { if let Some(field) = &self.field { field.format(formatted_code, formatter)?; } else if let Some(namespace) = &self.namespace { self.name.format(formatted_code, formatter)?; ItemStorage::open_curly_brace(formatted_code, formatter)?; formatter.shape.code_line.update_expr_new_line(true); formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Multiline, ExprKind::Struct), |formatter| -> Result<(), FormatterError> { namespace .clone() .into_inner() .format(formatted_code, formatter)?; Ok(()) }, )?; ItemStorage::close_curly_brace(formatted_code, formatter)?; } Ok(()) } } impl<T: Format + Spanned + std::fmt::Debug> Format for Box<T> { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { (**self).format(formatted_code, formatter)?; Ok(()) } } impl Format for CommaToken { fn format( &self, formatted_code: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(formatted_code, "{}", CommaToken::AS_STR)?; Ok(()) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/generics.rs
swayfmt/src/utils/language/generics.rs
use crate::{ formatter::*, utils::{close_angle_bracket, colon, open_angle_bracket}, }; use sway_ast::{ generics::GenericParam, keywords::{ConstToken, Keyword}, GenericArgs, GenericParams, }; impl Format for GenericParam { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { GenericParam::Trait { ident } => ident.format(formatted_code, formatter), GenericParam::Const { ident, ty } => { use std::fmt::Write; write!(formatted_code, "{} ", ConstToken::AS_STR)?; let _ = ident.format(formatted_code, formatter); let _ = colon(formatted_code); write!(formatted_code, " ")?; ty.format(formatted_code, formatter) } } } } impl Format for GenericParams { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { let params = self.parameters.clone().into_inner(); formatter.with_shape( formatter.shape.with_default_code_line(), |formatter| -> Result<(), FormatterError> { // `<` open_angle_bracket(formatted_code)?; // format and add parameters params.format(formatted_code, formatter)?; // `>` close_angle_bracket(formatted_code)?; Ok(()) }, )?; Ok(()) } } impl Format for GenericArgs { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { let params = self.parameters.clone().into_inner(); formatter.with_shape( formatter.shape.with_default_code_line(), |formatter| -> Result<(), FormatterError> { // `<` open_angle_bracket(formatted_code)?; // format and add parameters params.format(formatted_code, formatter)?; // `>` close_angle_bracket(formatted_code)?; Ok(()) }, )?; Ok(()) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/literal.rs
swayfmt/src/utils/language/literal.rs
use crate::{ formatter::*, utils::map::byte_span::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_ast::{literal::LitBoolType, LitIntType, Literal}; impl Format for Literal { fn format( &self, formatted_code: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { Self::String(lit_string) => write!(formatted_code, "\"{}\"", lit_string.parsed)?, Self::Char(lit_char) => write!(formatted_code, "\'{}\'", lit_char.parsed)?, Self::Int(lit_int) => { // It is tricky to support formatting of `LitInt` for an arbitrary `LitInt` // that is potentially not backed by source code, but constructed in-memory. // // E.g., a constructed `LitInt` representing 1000 can have only the numeric value // (LitInt::parsed) specified, in which case we can simply output the value. // If it has the type specified (LitInt::ty_opt), we can output the type next to the // value, e.g., 1000u16. // But a `LitInt` backed by code can have an arbitrary representation that includes // underscores. E.g., 1_00_00__u16. In that case we need to preserve the original // representation. // // The taken approach is the following. If the length of the `LitInt::span` is zero, // we assume that it is not backed by source code and render the canonical representation, // 1000u16 in the above example. Otherwise, we assume that it is backed by source code // and use the actual spans to obtain the strings. if lit_int.span.is_empty() { // Format `u256` and `b256` as hex literals. if lit_int.is_generated_b256 || matches!(&lit_int.ty_opt, Some((LitIntType::U256, _))) { write!(formatted_code, "0x{:064x}", lit_int.parsed)?; } else { write!(formatted_code, "{}", lit_int.parsed)?; } if let Some((int_type, _)) = &lit_int.ty_opt { let int_type = match int_type { LitIntType::U8 => "_u8", LitIntType::U16 => "_u16", LitIntType::U32 => "_u32", LitIntType::U64 => "_u64", LitIntType::U256 => { if lit_int.is_generated_b256 { "" } else { "_u256" } } LitIntType::I8 => "_i8", LitIntType::I16 => "_i16", LitIntType::I32 => "_i32", LitIntType::I64 => "_i64", }; write!(formatted_code, "{int_type}")?; } } else { write!(formatted_code, "{}", lit_int.span.as_str())?; if let Some((_, ty_span)) = &lit_int.ty_opt { write!(formatted_code, "{}", ty_span.as_str())?; } } } Self::Bool(lit_bool) => write!( formatted_code, "{}", match lit_bool.kind { LitBoolType::True => "true", LitBoolType::False => "false", } )?, } Ok(()) } } impl LeafSpans for Literal { fn leaf_spans(&self) -> Vec<ByteSpan> { match self { Literal::String(str_lit) => vec![ByteSpan::from(str_lit.span.clone())], Literal::Char(chr_lit) => vec![ByteSpan::from(chr_lit.span.clone())], Literal::Int(int_lit) => vec![ByteSpan::from(int_lit.span.clone())], Literal::Bool(bool_lit) => vec![ByteSpan::from(bool_lit.span.clone())], } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/mod.rs
swayfmt/src/utils/language/mod.rs
pub(crate) mod attribute; pub(crate) mod expr; pub(crate) mod generics; pub(crate) mod literal; pub(crate) mod path; pub(crate) mod pattern; pub(crate) mod punctuated; pub(crate) mod statement; pub(crate) mod ty; pub(crate) mod where_clause;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/statement.rs
swayfmt/src/utils/language/statement.rs
use crate::{ formatter::{shape::LineStyle, *}, utils::map::byte_span::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_ast::{ keywords::{ColonToken, EqToken, Keyword, LetToken, SemicolonToken, Token}, Expr, Parens, Punctuated, Statement, StatementLet, }; use sway_types::{Span, Spanned}; impl Format for Statement { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // later we need to decide if a statement is long enough to go on next line format_statement(self, formatted_code, formatter)?; Ok(()) } } /// Remove arguments from the expression if the expression is a method call if /// the method is a simple two path call (foo.bar()). This is needed because in /// method calls of two parts they are never broke into multiple lines. /// Arguments however can be broken into multiple lines, and that is handled /// by `write_function_call_arguments` fn remove_arguments_from_expr(expr: Expr) -> Expr { match expr { Expr::MethodCall { target, dot_token, path_seg, contract_args_opt, args, } => { let is_simple_call = matches!(*target, Expr::Path(_)); let target = remove_arguments_from_expr(*target); Expr::MethodCall { target: Box::new(target), dot_token, path_seg, contract_args_opt, args: if is_simple_call { Parens::new( Punctuated { value_separator_pairs: vec![], final_value_opt: None, }, Span::dummy(), ) } else { args }, } } Expr::FieldProjection { target, dot_token, name, } => { let target = remove_arguments_from_expr(*target); Expr::FieldProjection { target: Box::new(target), dot_token, name, } } _ => expr, } } fn format_statement( statement: &Statement, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match statement { Statement::Let(let_stmt) => let_stmt.format(formatted_code, formatter)?, Statement::Item(item) => item.format(formatted_code, formatter)?, Statement::Expr { expr, semicolon_token_opt, } => { let mut temp_expr = FormattedCode::new(); remove_arguments_from_expr(expr.clone()).format(&mut temp_expr, formatter)?; if temp_expr.len() > formatter.shape.width_heuristics.chain_width { let update_expr_new_line = if !matches!( expr, Expr::MethodCall { .. } | Expr::FuncApp { func: _, args: _ } | Expr::If(_) | Expr::While { while_token: _, condition: _, block: _ } ) { // Method calls, If, While should not tamper with the // expr_new_line because that would be inherited for all // statements. That should be applied at the lowest level // possible (ideally at the expression level) formatter.shape.code_line.expr_new_line } else if formatter.shape.code_line.expr_new_line { // already enabled true } else { formatter.shape.code_line.update_expr_new_line(true); false }; // reformat the expression adding a break expr.format(formatted_code, formatter)?; formatter .shape .code_line .update_expr_new_line(update_expr_new_line); } else { expr.format(formatted_code, formatter)?; } if semicolon_token_opt.is_some() { if formatter.shape.code_line.line_style == LineStyle::Inline { write!(formatted_code, "{}", SemicolonToken::AS_STR)?; } else { writeln!(formatted_code, "{}", SemicolonToken::AS_STR)?; } } } Statement::Error(_, _) => { return Err(FormatterError::SyntaxError); } } Ok(()) } impl Format for StatementLet { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // `let ` write!(formatted_code, "{} ", LetToken::AS_STR)?; // pattern self.pattern.format(formatted_code, formatter)?; // `: Ty` if let Some((_colon_token, ty)) = &self.ty_opt { write!(formatted_code, "{} ", ColonToken::AS_STR)?; ty.format(formatted_code, formatter)?; } // ` = ` write!(formatted_code, " {} ", EqToken::AS_STR)?; // expr self.expr.format(formatted_code, formatter)?; if formatter.shape.code_line.line_style == LineStyle::Inline { // `;` write!(formatted_code, "{}", SemicolonToken::AS_STR)?; } else { // `;\n` writeln!(formatted_code, "{}", SemicolonToken::AS_STR)?; } Ok(()) } } impl LeafSpans for Statement { fn leaf_spans(&self) -> Vec<ByteSpan> { match self { Statement::Let(statement_let) => statement_let.leaf_spans(), Statement::Item(item) => item.leaf_spans(), Statement::Expr { expr, semicolon_token_opt, } => { let mut collected_spans = expr.leaf_spans(); if let Some(semicolon_token) = semicolon_token_opt { collected_spans.push(ByteSpan::from(semicolon_token.span())); } collected_spans } Statement::Error(spans, _) => { vec![sway_types::Span::join_all(spans.iter().cloned()).into()] } } } } impl LeafSpans for StatementLet { fn leaf_spans(&self) -> Vec<ByteSpan> { // Add let token's ByteSpan let mut collected_spans = vec![ByteSpan::from(self.let_token.span())]; // Add pattern's ByteSpan collected_spans.append(&mut self.pattern.leaf_spans()); // Add ty's ByteSpan if it exists if let Some(ty) = &self.ty_opt { collected_spans.push(ByteSpan::from(ty.0.span())); collected_spans.append(&mut ty.1.leaf_spans()); } // Add eq token's ByteSpan collected_spans.push(ByteSpan::from(self.eq_token.span())); // Add Expr's ByteSpan collected_spans.append(&mut self.expr.leaf_spans()); collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/ty.rs
swayfmt/src/utils/language/ty.rs
use crate::{ formatter::*, utils::map::byte_span::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_ast::{ brackets::SquareBrackets, expr::Expr, keywords::{ AmpersandToken, BangToken, Keyword, MutToken, PtrToken, SemicolonToken, SliceToken, StrToken, Token, UnderscoreToken, }, ty::{Ty, TyArrayDescriptor, TyTupleDescriptor}, CommaToken, }; use sway_types::{ast::Delimiter, Spanned}; impl Format for Ty { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { Self::Array(arr_descriptor) => { write!(formatted_code, "{}", Delimiter::Bracket.as_open_char())?; arr_descriptor.get().format(formatted_code, formatter)?; write!(formatted_code, "{}", Delimiter::Bracket.as_close_char())?; Ok(()) } Self::Infer { underscore_token: _, } => format_infer(formatted_code), Self::Path(path_ty) => path_ty.format(formatted_code, formatter), Self::StringSlice(_) => { write!(formatted_code, "{}", StrToken::AS_STR)?; Ok(()) } Self::StringArray { str_token: _, length, } => format_str(formatted_code, formatter, length.clone()), Self::Tuple(tup_descriptor) => { write!(formatted_code, "{}", Delimiter::Parenthesis.as_open_char())?; tup_descriptor.get().format(formatted_code, formatter)?; write!(formatted_code, "{}", Delimiter::Parenthesis.as_close_char())?; Ok(()) } Self::Ptr { ptr_token: _, ty } => format_ptr(formatted_code, formatter, ty.clone()), Self::Slice { slice_token, ty } => { format_slice(formatted_code, formatter, slice_token, ty.clone()) } Self::Ref { ampersand_token: _, mut_token, ty, } => format_ref(formatted_code, formatter, mut_token, ty), Self::Never { bang_token: _ } => { write!(formatted_code, "{}", BangToken::AS_STR)?; Ok(()) } Self::Expr(expr) => expr.format(formatted_code, formatter), } } } /// Simply inserts a `_` token to the `formatted_code`. fn format_infer(formatted_code: &mut FormattedCode) -> Result<(), FormatterError> { formatted_code.push_str(UnderscoreToken::AS_STR); Ok(()) } impl Format for TyArrayDescriptor { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { self.ty.format(formatted_code, formatter)?; write!(formatted_code, "{} ", SemicolonToken::AS_STR)?; self.length.format(formatted_code, formatter)?; Ok(()) } } fn format_str( formatted_code: &mut FormattedCode, formatter: &mut Formatter, length: SquareBrackets<Box<Expr>>, ) -> Result<(), FormatterError> { write!(formatted_code, "{}", StrToken::AS_STR)?; write!(formatted_code, "{}", Delimiter::Bracket.as_open_char())?; length.into_inner().format(formatted_code, formatter)?; write!(formatted_code, "{}", Delimiter::Bracket.as_close_char())?; Ok(()) } fn format_ptr( formatted_code: &mut FormattedCode, formatter: &mut Formatter, ty: SquareBrackets<Box<Ty>>, ) -> Result<(), FormatterError> { write!(formatted_code, "{}", PtrToken::AS_STR)?; write!(formatted_code, "{}", Delimiter::Bracket.as_open_char())?; ty.into_inner().format(formatted_code, formatter)?; write!(formatted_code, "{}", Delimiter::Bracket.as_close_char())?; Ok(()) } fn format_slice( formatted_code: &mut FormattedCode, formatter: &mut Formatter, slice_token: &Option<SliceToken>, ty: SquareBrackets<Box<Ty>>, ) -> Result<(), FormatterError> { if slice_token.is_some() { write!(formatted_code, "{}", SliceToken::AS_STR)?; } write!(formatted_code, "{}", Delimiter::Bracket.as_open_char())?; ty.into_inner().format(formatted_code, formatter)?; write!(formatted_code, "{}", Delimiter::Bracket.as_close_char())?; Ok(()) } fn format_ref( formatted_code: &mut FormattedCode, formatter: &mut Formatter, mut_token: &Option<MutToken>, ty: &Ty, ) -> Result<(), FormatterError> { // TODO: Currently, the parser does not support declaring // references on references without spaces between // ampersands. E.g., `&&&T` is not supported and must // be written as `& & &T`. // See: https://github.com/FuelLabs/sway/issues/6808 // Until this issue is fixed, we need this workaround // in case of referenced type `ty` being itself a // reference. if !matches!(ty, Ty::Ref { .. }) { // TODO: Keep this code once the issue is fixed. write!( formatted_code, "{}{}", AmpersandToken::AS_STR, if mut_token.is_some() { format!("{} ", MutToken::AS_STR) } else { "".to_string() }, )?; ty.format(formatted_code, formatter)?; } else { // TODO: This is the workaround if `ty` is a reference. write!( formatted_code, "{}{}{}", AmpersandToken::AS_STR, if mut_token.is_some() { format!("{} ", MutToken::AS_STR) } else { "".to_string() }, // If we have the `mut`, we will also // get a space after it, so the next `&` // will be separated. Otherwise, insert space. if mut_token.is_some() { "".to_string() } else { " ".to_string() }, )?; ty.format(formatted_code, formatter)?; } Ok(()) } impl Format for TyTupleDescriptor { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { if let TyTupleDescriptor::Cons { head, comma_token: _, tail, } = self { formatter.with_shape( formatter.shape.with_default_code_line(), |formatter| -> Result<(), FormatterError> { head.format(formatted_code, formatter)?; write!(formatted_code, "{} ", CommaToken::AS_STR)?; tail.format(formatted_code, formatter)?; Ok(()) }, )?; } Ok(()) } } impl<T: LeafSpans + Clone> LeafSpans for Box<T> { fn leaf_spans(&self) -> Vec<ByteSpan> { (**self).leaf_spans() } } impl LeafSpans for Ty { fn leaf_spans(&self) -> Vec<ByteSpan> { match self { Ty::Path(path) => path.leaf_spans(), Ty::Tuple(tuple) => tuple.leaf_spans(), Ty::Array(array) => array.leaf_spans(), Ty::StringSlice(str_token) => vec![ByteSpan::from(str_token.span())], Ty::StringArray { str_token, length } => { let mut collected_spans = vec![ByteSpan::from(str_token.span())]; collected_spans.append(&mut length.leaf_spans()); collected_spans } Ty::Infer { underscore_token } => vec![ByteSpan::from(underscore_token.span())], Ty::Ptr { ptr_token, ty } => { let mut collected_spans = vec![ByteSpan::from(ptr_token.span())]; collected_spans.append(&mut ty.leaf_spans()); collected_spans } Ty::Slice { slice_token, ty } => { let mut collected_spans = if let Some(slice_token) = slice_token { vec![ByteSpan::from(slice_token.span())] } else { vec![] }; collected_spans.append(&mut ty.leaf_spans()); collected_spans } Ty::Ref { ampersand_token, mut_token, ty, } => { let mut collected_spans = vec![ByteSpan::from(ampersand_token.span())]; if let Some(mut_token) = mut_token { collected_spans.push(ByteSpan::from(mut_token.span())); } collected_spans.append(&mut ty.leaf_spans()); collected_spans } Ty::Never { bang_token } => vec![ByteSpan::from(bang_token.span())], Ty::Expr(expr) => expr.leaf_spans(), } } } impl LeafSpans for TyTupleDescriptor { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); if let TyTupleDescriptor::Cons { head, comma_token, tail, } = self { collected_spans.append(&mut head.leaf_spans()); collected_spans.push(ByteSpan::from(comma_token.span())); collected_spans.append(&mut tail.leaf_spans()); } collected_spans } } impl LeafSpans for TyArrayDescriptor { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.ty.leaf_spans()); collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans.append(&mut self.length.leaf_spans()); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/expr/tests.rs
swayfmt/src/utils/language/expr/tests.rs
//! Specific tests for the expression module use forc_tracing::{println_green, println_red}; use paste::paste; use prettydiff::{basic::DiffOp, diff_lines}; use test_macros::fmt_test_expr; fmt_test_expr!( literal "5", extra_whitespace " 5 " ); fmt_test_expr!( path_foo_bar "foo::bar::baz::quux::quuz", intermediate_whitespace "foo :: bar :: baz :: quux :: quuz"); fmt_test_expr!( field_proj_foobar "foo.bar.baz.quux", intermediate_whitespace "foo . bar . baz . quux"); fmt_test_expr!( abi_cast "abi(MyAbi, 0x1111111111111111111111111111111111111111111111111111111111111111)", intermediate_whitespace " abi ( MyAbi , 0x1111111111111111111111111111111111111111111111111111111111111111 ) " ); fmt_test_expr!( basic_func_app "foo()", intermediate_whitespace " foo ( ) " ); fmt_test_expr!( nested_args_func_app "foo(a_struct { hello: \"hi\" }, a_var, foo.bar.baz.quux)", intermediate_whitespace "foo(a_struct { hello : \"hi\" }, a_var , foo . bar . baz . quux)" ); fmt_test_expr!( multiline_tuple "(\n \"reallyreallylongstring\",\n \"yetanotherreallyreallyreallylongstring\",\n \"okaynowthatsjustaridiculouslylongstringrightthere\",\n)", intermediate_whitespace "(\"reallyreallylongstring\", \"yetanotherreallyreallyreallylongstring\", \"okaynowthatsjustaridiculouslylongstringrightthere\")" ); fmt_test_expr!( nested_tuple "( ( 0x0000000000000000000000000000000000000000000000000000000000, 0x0000000000000000000000000000000000000000000000000000000000, ), ( 0x0000000000000000000000000000000000000000000000000000000000, 0x0000000000000000000000000000000000000000000000000000000000, ), )", intermediate_whitespace " ( ( 0x0000000000000000000000000000000000000000000000000000000000 , 0x0000000000000000000000000000000000000000000000000000000000 , ) , ( 0x0000000000000000000000000000000000000000000000000000000000 , 0x0000000000000000000000000000000000000000000000000000000000 , ) , )" ); fmt_test_expr!( multiline_match_stmt "match foo {\n Foo::foo => {}\n Foo::bar => {}\n}", intermediate_whitespace " match \n foo { \n\n Foo :: foo => { }\n Foo :: bar => { } \n}\n" ); fmt_test_expr!( if_else_block "if foo {\n foo();\n} else if bar { bar(); } else { baz(); }", intermediate_whitespace " if foo { \n foo( ) ; \n } else if bar { \n bar( ) ; \n } else { \n baz(\n) ; \n }\n\n" ); fmt_test_expr!( long_conditional_stmt "if really_long_var_name > other_really_long_var || really_long_var_name <= 0 && other_really_long_var != 0 { foo(); } else { bar(); }", intermediate_whitespace " if really_long_var_name > other_really_long_var || really_long_var_name <= 0 && other_really_long_var != 0 { foo(); }else{bar();}" ); fmt_test_expr!( if_else_inline_1 "if foo { break; } else { continue; }", intermediate_whitespace "if foo { \n break; \n} else {\n continue; \n}"); fmt_test_expr!( if_else_inline_2 "if foo { let x = 1; } else { bar(y); }" , intermediate_whitespace " if foo { let x = 1; } else { bar(y) ; } "); fmt_test_expr!( if_else_multiline "if foo { let really_long_variable = 1; } else { bar(y); }", intermediate_whitespace " if foo { let really_long_variable = 1; } else { bar(y) ; } "); fmt_test_expr!( small_if_let "if let Result::Ok(x) = x { 100 } else { 1 }", intermediate_whitespace "if let Result :: Ok( x ) = x { 100 } else { 1 }" ); fmt_test_expr!( match_nested_conditional "match foo { Foo::foo => { if really_long_var > other_really_long_var { foo(); } else if really_really_long_var_name > really_really_really_really_long_var_name111111111111 { bar(); } else { baz(); } } }", intermediate_whitespace " match foo { Foo::foo => { if really_long_var > other_really_long_var { foo(); } else if really_really_long_var_name > really_really_really_really_long_var_name111111111111 { bar(); } else { baz() ; } } }" ); fmt_test_expr!( match_branch_kind "match foo { Foo::foo => { foo(); bar(); } Foo::bar => { baz(); quux(); } }", intermediate_whitespace "match foo \n{\n\n Foo::foo => {\n foo() ; \n bar( ); \n } \n Foo::\nbar => {\n baz();\n quux();\n }\n\n\n}" ); fmt_test_expr!( match_branch_kind_tuple_long "match (foo, bar) { ( SomeVeryVeryLongFoo::SomeLongFoo(some_foo), SomeVeryVeryLongBar::SomeLongBar(some_bar), ) => { foo(); } ( SomeVeryVeryLongFoo::OtherLongFoo(other_foo), SomeVeryVeryLongBar::OtherLongBar(other_bar), ) => { bar(); } _ => { revert(0) } }", intermediate_whitespace "match (foo, bar) { ( SomeVeryVeryLongFoo::SomeLongFoo(some_foo), \n \n SomeVeryVeryLongBar::SomeLongBar(some_bar)) => \n \n{ \n foo(); } (SomeVeryVeryLongFoo::OtherLongFoo(other_foo), SomeVeryVeryLongBar::OtherLongBar(other_bar) \n ) => { bar(); \n } _ \n=> { \n revert(0) } }" ); fmt_test_expr!( basic_array "[1, 2, 3, 4, 5]", intermediate_whitespace " \n [ 1 , 2 , 3 , 4 , 5 ] \n" ); fmt_test_expr!( long_array "[ \"hello_there_this_is_a_very_long_string\", \"and_yet_another_very_long_string_just_because\", \"would_you_look_at_that_another_long_string\", ]", intermediate_whitespace " [ \"hello_there_this_is_a_very_long_string\", \"and_yet_another_very_long_string_just_because\"\n, \"would_you_look_at_that_another_long_string\", ] \n" ); fmt_test_expr!( nested_array "[ [ 0x0000000000000000000000000000000000000000000000000000000000, 0x0000000000000000000000000000000000000000000000000000000000, ], [ 0x0000000000000000000000000000000000000000000000000000000000, 0x0000000000000000000000000000000000000000000000000000000000, ], ]", intermediate_whitespace " [ [ 0x0000000000000000000000000000000000000000000000000000000000 , 0x0000000000000000000000000000000000000000000000000000000000 , ] , [ 0x0000000000000000000000000000000000000000000000000000000000 , 0x0000000000000000000000000000000000000000000000000000000000 , ] , ]" ); fmt_test_expr!(basic_while_loop "while i == true { let i = 42; }", intermediate_whitespace "while i==true{ let i = 42; }"); fmt_test_expr!(scoped_block "{ let i = 42; }", intermediate_whitespace "{ let i = 42; }"); fmt_test_expr!(basic_for_loop "for iter in [0, 1, 7, 8, 15] { let i = 42; }", intermediate_whitespace "for iter in [0, 1, 7, 8, 15]{ let i = 42; }" );
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/expr/struct_field.rs
swayfmt/src/utils/language/expr/struct_field.rs
use crate::{ formatter::{ shape::{ExprKind, LineStyle}, *, }, utils::{ language::expr::should_write_multiline, map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::fmt::Write; use sway_ast::{ keywords::{ColonToken, Token}, ExprStructField, }; use sway_types::{ast::Delimiter, Spanned}; impl Format for ExprStructField { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(formatted_code, "{}", self.field_name.as_raw_ident_str())?; if let Some((_colon_token, expr)) = &self.expr_opt { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Inline, ExprKind::Struct), |formatter| -> Result<(), FormatterError> { let mut expr_str = FormattedCode::new(); expr.format(&mut expr_str, formatter)?; let expr_str = if should_write_multiline(&expr_str, formatter) { let mut expr_str = FormattedCode::new(); formatter.shape.code_line.update_expr_new_line(true); expr.format(&mut expr_str, formatter)?; expr_str } else { expr_str }; write!(formatted_code, "{} {}", ColonToken::AS_STR, expr_str)?; Ok(()) }, )?; } Ok(()) } } impl CurlyBrace for ExprStructField { fn open_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Add opening brace to the same line write!(line, " {}", Delimiter::Brace.as_open_char())?; formatter.indent(); Ok(()) } fn close_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Unindent by one block formatter.unindent(); match formatter.shape.code_line.line_style { LineStyle::Inline => write!(line, "{}", Delimiter::Brace.as_close_char())?, _ => write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?, } Ok(()) } } impl LeafSpans for ExprStructField { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.field_name.span())]; if let Some((colon_token, expr)) = &self.expr_opt { collected_spans.push(ByteSpan::from(colon_token.span())); collected_spans.append(&mut expr.leaf_spans()); } collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/expr/collections.rs
swayfmt/src/utils/language/expr/collections.rs
use crate::{ formatter::{shape::LineStyle, *}, utils::{ map::byte_span::{ByteSpan, LeafSpans}, {Parenthesis, SquareBracket}, }, }; use std::fmt::Write; use sway_ast::{ keywords::{SemicolonToken, Token}, CommaToken, ExprArrayDescriptor, ExprTupleDescriptor, }; use sway_types::{ast::Delimiter, Spanned}; impl Format for ExprTupleDescriptor { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { Self::open_parenthesis(formatted_code, formatter)?; match self { Self::Nil => {} Self::Cons { head, comma_token: _, tail, } => match formatter.shape.code_line.line_style { LineStyle::Multiline => { write!(formatted_code, "{}", formatter.indent_to_str()?)?; head.format(formatted_code, formatter)?; write!(formatted_code, "{}", CommaToken::AS_STR)?; tail.format(formatted_code, formatter)?; } _ => { head.format(formatted_code, formatter)?; write!(formatted_code, "{} ", CommaToken::AS_STR)?; tail.format(formatted_code, formatter)?; } }, } Self::close_parenthesis(formatted_code, formatter)?; Ok(()) } } impl Parenthesis for ExprTupleDescriptor { fn open_parenthesis( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match formatter.shape.code_line.line_style { LineStyle::Multiline => { formatter.indent(); writeln!(line, "{}", Delimiter::Parenthesis.as_open_char())?; } _ => write!(line, "{}", Delimiter::Parenthesis.as_open_char())?, } Ok(()) } fn close_parenthesis( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match formatter.shape.code_line.line_style { LineStyle::Multiline => { formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Parenthesis.as_close_char() )?; } _ => write!(line, "{}", Delimiter::Parenthesis.as_close_char())?, } Ok(()) } } impl Format for ExprArrayDescriptor { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { Self::open_square_bracket(formatted_code, formatter)?; match self { Self::Sequence(punct_expr) => { punct_expr.format(formatted_code, formatter)?; } Self::Repeat { value, semicolon_token: _, length, } => { value.format(formatted_code, formatter)?; write!(formatted_code, "{} ", SemicolonToken::AS_STR)?; length.format(formatted_code, formatter)?; } } Self::close_square_bracket(formatted_code, formatter)?; Ok(()) } } impl SquareBracket for ExprArrayDescriptor { fn open_square_bracket( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match formatter.shape.code_line.line_style { LineStyle::Multiline => { formatter.indent(); write!(line, "{}", Delimiter::Bracket.as_open_char())?; } _ => write!(line, "{}", Delimiter::Bracket.as_open_char())?, } Ok(()) } fn close_square_bracket( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match formatter.shape.code_line.line_style { LineStyle::Multiline => { formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Bracket.as_close_char() )?; } _ => write!(line, "{}", Delimiter::Bracket.as_close_char())?, } Ok(()) } } impl LeafSpans for ExprTupleDescriptor { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); if let ExprTupleDescriptor::Cons { head, comma_token, tail, } = self { collected_spans.append(&mut head.leaf_spans()); collected_spans.push(ByteSpan::from(comma_token.span())); collected_spans.append(&mut tail.leaf_spans()); } collected_spans } } impl LeafSpans for ExprArrayDescriptor { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); if let ExprArrayDescriptor::Repeat { value, semicolon_token, length, } = self { collected_spans.append(&mut value.leaf_spans()); collected_spans.push(ByteSpan::from(semicolon_token.span())); collected_spans.append(&mut length.leaf_spans()); } collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/expr/asm_block.rs
swayfmt/src/utils/language/expr/asm_block.rs
use crate::{ comments::rewrite_with_comments, formatter::{shape::LineStyle, *}, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, Parenthesis, }, }; use std::fmt::Write; use sway_ast::{ expr::asm::{AsmBlock, AsmBlockContents, AsmFinalExpr, AsmRegisterDeclaration}, keywords::{AsmToken, ColonToken, Keyword, SemicolonToken, Token}, Instruction, }; use sway_types::{ast::Delimiter, Spanned}; impl Format for AsmBlock { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Required for comment formatting let start_len = formatted_code.len(); formatter.with_shape(formatter.shape, |formatter| -> Result<(), FormatterError> { let contents = self.contents.get(); if contents.instructions.is_empty() && contents.final_expr_opt.is_some() { formatter .shape .code_line .update_line_style(LineStyle::Inline) } else { formatter .shape .code_line .update_line_style(LineStyle::Multiline) } format_asm_block(self, formatted_code, formatter)?; Ok(()) })?; rewrite_with_comments::<AsmBlock>( formatter, self.span(), self.leaf_spans(), formatted_code, start_len, )?; Ok(()) } } fn format_asm_block( asm_block: &AsmBlock, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(formatted_code, "{}", AsmToken::AS_STR)?; formatter.with_shape( formatter.shape.with_default_code_line(), |formatter| -> Result<(), FormatterError> { formatter .shape .code_line .update_line_style(LineStyle::Normal); let mut inline_arguments = FormattedCode::new(); asm_block .registers .get() .format(&mut inline_arguments, formatter)?; formatter.shape.code_line.update_expr_new_line(false); formatter .shape .code_line .update_expr_kind(shape::ExprKind::Function); if inline_arguments.len() > formatter.shape.width_heuristics.fn_call_width { formatter .shape .code_line .update_line_style(LineStyle::Multiline); AsmBlock::open_parenthesis(formatted_code, formatter)?; formatter.indent(); asm_block .registers .get() .format(formatted_code, formatter)?; formatter.unindent(); write!(formatted_code, "{}", formatter.indent_to_str()?)?; AsmBlock::close_parenthesis(formatted_code, formatter)?; } else { AsmBlock::open_parenthesis(formatted_code, formatter)?; write!(formatted_code, "{inline_arguments}")?; AsmBlock::close_parenthesis(formatted_code, formatter)?; } formatter .shape .code_line .update_line_style(LineStyle::Multiline); AsmBlock::open_curly_brace(formatted_code, formatter)?; asm_block.contents.get().format(formatted_code, formatter)?; AsmBlock::close_curly_brace(formatted_code, formatter)?; Ok(()) }, )?; Ok(()) } impl Parenthesis for AsmBlock { fn open_parenthesis( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_open_char())?; Ok(()) } fn close_parenthesis( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_close_char())?; Ok(()) } } impl CurlyBrace for AsmBlock { fn open_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.indent(); match formatter.shape.code_line.line_style { LineStyle::Inline => { write!(line, " {} ", Delimiter::Brace.as_open_char())?; } _ => { writeln!(line, " {}", Delimiter::Brace.as_open_char())?; } } Ok(()) } fn close_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.unindent(); match formatter.shape.code_line.line_style { LineStyle::Inline => { write!(line, " {}", Delimiter::Brace.as_close_char())?; } _ => { write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; } } Ok(()) } } impl Format for AsmRegisterDeclaration { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { self.register.format(formatted_code, formatter)?; if let Some((_colon_token, expr)) = &self.value_opt { write!(formatted_code, "{} ", ColonToken::AS_STR)?; expr.format(formatted_code, formatter)?; } Ok(()) } } impl Format for Instruction { fn format( &self, formatted_code: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(formatted_code, "{}", self.op_code_as_str())?; for arg in self.register_arg_idents() { write!(formatted_code, " {}", arg.as_str())? } for imm in self.immediate_idents() { write!(formatted_code, " {}", imm.as_str())? } Ok(()) } } impl Format for AsmBlockContents { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { for (instruction, _semicolon_token) in self.instructions.iter() { write!(formatted_code, "{}", formatter.indent_to_str()?)?; instruction.format(formatted_code, formatter)?; writeln!(formatted_code, "{}", SemicolonToken::AS_STR)? } if let Some(final_expr) = &self.final_expr_opt { if formatter.shape.code_line.line_style == LineStyle::Multiline { write!(formatted_code, "{}", formatter.indent_to_str()?)?; final_expr.format(formatted_code, formatter)?; writeln!(formatted_code)?; } else { final_expr.format(formatted_code, formatter)?; } } Ok(()) } } impl Format for AsmFinalExpr { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { self.register.format(formatted_code, formatter)?; if let Some((_colon_token, ty)) = &self.ty_opt { write!(formatted_code, "{} ", ColonToken::AS_STR)?; ty.format(formatted_code, formatter)?; } Ok(()) } } impl LeafSpans for AsmBlock { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.asm_token.span())]; collected_spans.append(&mut self.registers.leaf_spans()); collected_spans.append(&mut self.contents.leaf_spans()); collected_spans } } impl LeafSpans for AsmRegisterDeclaration { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.register.span())]; if let Some(value) = &self.value_opt { collected_spans.append(&mut value.leaf_spans()); } collected_spans } } impl LeafSpans for AsmBlockContents { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); for instruction in &self.instructions { collected_spans.append(&mut instruction.leaf_spans()); } if let Some(final_expr) = &self.final_expr_opt { collected_spans.append(&mut final_expr.leaf_spans()); } collected_spans } } impl LeafSpans for Instruction { fn leaf_spans(&self) -> Vec<ByteSpan> { // Visit instructions as a whole unit, meaning we cannot insert comments inside an instruction. vec![ByteSpan::from(self.span())] } } impl LeafSpans for AsmFinalExpr { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.register.span())]; if let Some(ty) = &self.ty_opt { collected_spans.append(&mut ty.leaf_spans()); } collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/expr/mod.rs
swayfmt/src/utils/language/expr/mod.rs
use crate::{ formatter::{ shape::{ExprKind, LineStyle}, *, }, utils::{ map::byte_span::{ByteSpan, LeafSpans}, {CurlyBrace, Parenthesis, SquareBracket}, }, }; use std::fmt::Write; use sway_ast::{ brackets::Parens, keywords::*, punctuated::Punctuated, Braces, CodeBlockContents, Expr, ExprStructField, IfExpr, MatchBranch, PathExpr, PathExprSegment, }; use sway_types::{ast::Delimiter, Spanned}; pub(crate) mod abi_cast; pub(crate) mod asm_block; pub(crate) mod assignable; pub(crate) mod code_block; pub(crate) mod collections; pub(crate) mod conditional; pub(crate) mod struct_field; #[cfg(test)] mod tests; #[inline] fn two_parts_expr( lhs: &Expr, operator: &str, rhs: &Expr, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { let mut rhs_code = FormattedCode::new(); rhs.format(&mut rhs_code, formatter)?; if !formatter.shape.code_line.expr_new_line && rhs_code.len() > formatter.shape.width_heuristics.collection_width { // Right hand side is too long to fit in a single line, and // the current expr is not being rendered multiline at the // expr level, then add an indentation to the following // expression and generate the code formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Multiline, ExprKind::Undetermined), |formatter| -> Result<(), FormatterError> { formatter.shape.code_line.update_expr_new_line(true); lhs.format(formatted_code, formatter)?; formatter.indent(); write!( formatted_code, "\n{}{} ", formatter.indent_to_str()?, operator, )?; rhs.format(formatted_code, formatter)?; formatter.unindent(); Ok(()) }, )?; } else { lhs.format(formatted_code, formatter)?; match formatter.shape.code_line.line_style { LineStyle::Multiline => { write!( formatted_code, "\n{}{} ", formatter.indent_to_str()?, operator, )?; } _ => { write!(formatted_code, " {operator} ")?; } } write!(formatted_code, "{rhs_code}")?; } Ok(()) } impl Format for Expr { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { Self::Error(_, _) => { return Err(FormatterError::SyntaxError); } Self::Path(path) => path.format(formatted_code, formatter)?, Self::Literal(lit) => lit.format(formatted_code, formatter)?, Self::AbiCast { abi_token: _, args } => { write!(formatted_code, "{}", AbiToken::AS_STR)?; args.get().format(formatted_code, formatter)?; } Self::Struct { path, fields } => { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::default(), ExprKind::Struct), |formatter| -> Result<(), FormatterError> { // get the length in chars of the code_line in a single line format, // this include the path let mut buf = FormattedCode::new(); let mut temp_formatter = Formatter::default(); temp_formatter .shape .code_line .update_line_style(LineStyle::Inline); format_expr_struct(path, fields, &mut buf, &mut temp_formatter)?; // get the largest field size and the size of the body let (field_width, body_width) = get_field_width(fields.get(), &mut formatter.clone())?; formatter.shape.code_line.update_expr_new_line(true); // changes to the actual formatter let expr_width = buf.chars().count(); formatter.shape.code_line.update_width(expr_width); formatter.shape.get_line_style( Some(field_width), Some(body_width), &formatter.config, ); format_expr_struct(path, fields, formatted_code, formatter)?; Ok(()) }, )?; } Self::Tuple(tuple_descriptor) => { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::default(), ExprKind::Collection), |formatter| -> Result<(), FormatterError> { // get the length in chars of the code_line in a normal line format let mut buf = FormattedCode::new(); let mut temp_formatter = Formatter::default(); let tuple_descriptor = tuple_descriptor.get(); tuple_descriptor.format(&mut buf, &mut temp_formatter)?; let body_width = buf.chars().count(); formatter.shape.code_line.update_width(body_width); formatter .shape .get_line_style(None, Some(body_width), &formatter.config); tuple_descriptor.format(formatted_code, formatter)?; Ok(()) }, )?; } Self::Parens(expr) => { if formatter.shape.code_line.expr_new_line { formatter.indent(); } Self::open_parenthesis(formatted_code, formatter)?; expr.get().format(formatted_code, formatter)?; Self::close_parenthesis(formatted_code, formatter)?; if formatter.shape.code_line.expr_new_line { formatter.unindent(); } } Self::Block(code_block) => { if !code_block.get().statements.is_empty() || code_block.get().final_expr_opt.is_some() { CodeBlockContents::open_curly_brace(formatted_code, formatter)?; code_block.get().format(formatted_code, formatter)?; CodeBlockContents::close_curly_brace(formatted_code, formatter)?; } else { write!(formatted_code, "{{}}")?; } } Self::Array(array_descriptor) => { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::default(), ExprKind::Collection), |formatter| -> Result<(), FormatterError> { // get the length in chars of the code_line in a normal line format let mut buf = FormattedCode::new(); let mut temp_formatter = Formatter::default(); let array_descriptor = array_descriptor.get(); array_descriptor.format(&mut buf, &mut temp_formatter)?; let body_width = buf.chars().count(); formatter.shape.code_line.add_width(body_width); formatter .shape .get_line_style(None, Some(body_width), &formatter.config); if formatter.shape.code_line.line_style == LineStyle::Multiline { // Expr needs to be split into multiple lines array_descriptor.format(formatted_code, formatter)?; } else { // Expr fits in a single line write!(formatted_code, "{buf}")?; } Ok(()) }, )?; } Self::Asm(asm_block) => asm_block.format(formatted_code, formatter)?, Self::Return { return_token: _, expr_opt, } => { write!(formatted_code, "{}", ReturnToken::AS_STR)?; if let Some(expr) = &expr_opt { write!(formatted_code, " ")?; expr.format(formatted_code, formatter)?; } } Self::Panic { panic_token: _, expr_opt, } => { write!(formatted_code, "{}", PanicToken::AS_STR)?; if let Some(expr) = &expr_opt { write!(formatted_code, " ")?; expr.format(formatted_code, formatter)?; } } Self::If(if_expr) => if_expr.format(formatted_code, formatter)?, Self::Match { match_token: _, value, branches, } => { write!(formatted_code, "{} ", MatchToken::AS_STR)?; value.format(formatted_code, formatter)?; write!(formatted_code, " ")?; if !branches.get().is_empty() { MatchBranch::open_curly_brace(formatted_code, formatter)?; let branches = branches.get(); for match_branch in branches.iter() { write!(formatted_code, "{}", formatter.indent_to_str()?)?; match_branch.format(formatted_code, formatter)?; writeln!(formatted_code)?; } MatchBranch::close_curly_brace(formatted_code, formatter)?; } else { write!(formatted_code, "{{}}")?; } } Self::While { while_token: _, condition, block, } => { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Normal, ExprKind::Function), |formatter| -> Result<(), FormatterError> { write!(formatted_code, "{} ", WhileToken::AS_STR)?; condition.format(formatted_code, formatter)?; IfExpr::open_curly_brace(formatted_code, formatter)?; block.get().format(formatted_code, formatter)?; IfExpr::close_curly_brace(formatted_code, formatter)?; Ok(()) }, )?; } Self::For { for_token: _, in_token: _, value_pattern, iterator, block, } => { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Normal, ExprKind::Function), |formatter| -> Result<(), FormatterError> { write!(formatted_code, "{} ", ForToken::AS_STR)?; value_pattern.format(formatted_code, formatter)?; write!(formatted_code, " {} ", InToken::AS_STR)?; iterator.format(formatted_code, formatter)?; IfExpr::open_curly_brace(formatted_code, formatter)?; block.get().format(formatted_code, formatter)?; IfExpr::close_curly_brace(formatted_code, formatter)?; Ok(()) }, )?; } Self::FuncApp { func, args } => { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Normal, ExprKind::Function), |formatter| -> Result<(), FormatterError> { // don't indent unless on new line if formatted_code.ends_with('\n') { write!(formatted_code, "{}", formatter.indent_to_str()?)?; } func.format(formatted_code, formatter)?; Self::open_parenthesis(formatted_code, formatter)?; let (_, args_str) = write_function_call_arguments(args.get(), formatter)?; write!(formatted_code, "{args_str}")?; Self::close_parenthesis(formatted_code, formatter)?; Ok(()) }, )?; } Self::Index { target, arg } => { target.format(formatted_code, formatter)?; Self::open_square_bracket(formatted_code, formatter)?; arg.get().format(formatted_code, formatter)?; Self::close_square_bracket(formatted_code, formatter)?; } Self::MethodCall { target, dot_token, path_seg, contract_args_opt, args, } => { formatter.with_shape( formatter.shape.with_default_code_line(), |formatter| -> Result<(), FormatterError> { // get the length in chars of the code_line in a single line format let mut buf = FormattedCode::new(); let mut temp_formatter = Formatter::default(); temp_formatter .shape .code_line .update_line_style(LineStyle::Inline); let (function_call_length, args_inline) = format_method_call( target, dot_token, path_seg, contract_args_opt, args, &mut buf, &mut temp_formatter, )?; // get the largest field size let (field_width, body_width) = if args_inline { (function_call_length, function_call_length) } else if let Some(contract_args) = &contract_args_opt { get_field_width(contract_args.get(), &mut formatter.clone())? } else { (0, 0) }; // changes to the actual formatter let expr_width = buf.chars().count(); formatter.shape.code_line.add_width(expr_width); formatter.shape.code_line.update_expr_kind(ExprKind::Struct); formatter.shape.get_line_style( Some(field_width), Some(body_width), &formatter.config, ); let _ = format_method_call( target, dot_token, path_seg, contract_args_opt, args, formatted_code, formatter, )?; Ok(()) }, )?; } Self::FieldProjection { target, dot_token: _, name, } => { let prev_length = formatted_code.len(); target.format(formatted_code, formatter)?; let diff = formatted_code.len() - prev_length; if diff > 5 && formatter.shape.code_line.expr_new_line { // The next next expression should be added onto a new line. // The only exception is the previous element has fewer than // 5 characters, in which case we can add the dot onto the // same line (for example self.x will be rendered in the // same line) formatter.indent(); write!( formatted_code, "\n{}{}", formatter.indent_to_str()?, DotToken::AS_STR, )?; name.format(formatted_code, formatter)?; formatter.unindent(); } else { write!(formatted_code, "{}", DotToken::AS_STR)?; name.format(formatted_code, formatter)?; } } Self::TupleFieldProjection { target, dot_token: _, field, field_span: _, } => { target.format(formatted_code, formatter)?; write!(formatted_code, "{}{}", DotToken::AS_STR, field)?; } Self::Ref { ampersand_token: _, mut_token, expr, } => { // TODO: Currently, the parser does not support taking // references on references without spaces between // ampersands. E.g., `&&&x` is not supported and must // be written as `& & &x`. // See: https://github.com/FuelLabs/sway/issues/6808 // Until this issue is fixed, we need this workaround // in case of referenced expression `expr` being itself a // reference. if !matches!(expr.as_ref(), Self::Ref { .. }) { // TODO: Keep this code once the issue is fixed. write!(formatted_code, "{}", AmpersandToken::AS_STR)?; if mut_token.is_some() { write!(formatted_code, "{} ", MutToken::AS_STR)?; } expr.format(formatted_code, formatter)?; } else { // TODO: This is the workaround if `expr` is a reference. write!(formatted_code, "{}", AmpersandToken::AS_STR)?; // If we have the `mut`, we will also // get a space after it, so the next `&` // will be separated. Otherwise, insert space. if mut_token.is_some() { write!(formatted_code, "{} ", MutToken::AS_STR)?; } else { write!(formatted_code, " ")?; } expr.format(formatted_code, formatter)?; } } Self::Deref { star_token: _, expr, } => { write!(formatted_code, "{}", StarToken::AS_STR)?; expr.format(formatted_code, formatter)?; } Self::Not { bang_token: _, expr, } => { write!(formatted_code, "{}", BangToken::AS_STR)?; expr.format(formatted_code, formatter)?; } Self::Pow { lhs, double_star_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", DoubleStarToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::Mul { lhs, star_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", StarToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::Div { lhs, forward_slash_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", ForwardSlashToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::Modulo { lhs, percent_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", PercentToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::Add { lhs, add_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", AddToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::Sub { lhs, sub_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", SubToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::Shl { lhs, shl_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", ShlToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::Shr { lhs, shr_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", ShrToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::BitAnd { lhs, ampersand_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; match formatter.shape.code_line.line_style { LineStyle::Multiline => { write!( formatted_code, "\n{}{} ", formatter.indent_to_str()?, AmpersandToken::AS_STR, )?; } _ => { write!(formatted_code, " {} ", AmpersandToken::AS_STR)?; } } rhs.format(formatted_code, formatter)?; } Self::BitXor { lhs, caret_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; match formatter.shape.code_line.line_style { LineStyle::Multiline => { write!( formatted_code, "\n{}{} ", formatter.indent_to_str()?, CaretToken::AS_STR, )?; } _ => { write!(formatted_code, " {} ", CaretToken::AS_STR)?; } } rhs.format(formatted_code, formatter)?; } Self::BitOr { lhs, pipe_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; match formatter.shape.code_line.line_style { LineStyle::Multiline => { write!( formatted_code, "\n{}{} ", formatter.indent_to_str()?, PipeToken::AS_STR, )?; } _ => { write!(formatted_code, " {} ", PipeToken::AS_STR)?; } } rhs.format(formatted_code, formatter)?; } Self::Equal { lhs, double_eq_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", DoubleEqToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::NotEqual { lhs, bang_eq_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", BangEqToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::LessThan { lhs, less_than_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", LessThanToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::GreaterThan { lhs, greater_than_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", GreaterThanToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::LessThanEq { lhs, less_than_eq_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", LessThanEqToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::GreaterThanEq { lhs, greater_than_eq_token: _, rhs, } => { lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", GreaterThanEqToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } Self::LogicalAnd { lhs, double_ampersand_token: _, rhs, } => { two_parts_expr( lhs, DoubleAmpersandToken::AS_STR, rhs, formatted_code, formatter, )?; } Self::LogicalOr { lhs, double_pipe_token: _, rhs, } => { two_parts_expr(lhs, DoublePipeToken::AS_STR, rhs, formatted_code, formatter)?; } Self::Reassignment { assignable, reassignment_op, expr, } => { assignable.format(formatted_code, formatter)?; reassignment_op.format(formatted_code, formatter)?; expr.format(formatted_code, formatter)?; } Self::Break { break_token: _ } => { write!(formatted_code, "{}", BreakToken::AS_STR)?; } Self::Continue { continue_token: _ } => { write!(formatted_code, "{}", ContinueToken::AS_STR)?; } } Ok(()) } } impl Parenthesis for Expr { fn open_parenthesis( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_open_char())?; Ok(()) } fn close_parenthesis( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_close_char())?; Ok(()) } } impl SquareBracket for Expr { fn open_square_bracket( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Bracket.as_open_char())?; Ok(()) } fn close_square_bracket( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Bracket.as_close_char())?; Ok(()) } } pub(super) fn debug_expr( buf: FormattedCode, field_width: Option<usize>, body_width: Option<usize>, expr_width: usize, formatter: &Formatter, ) { println!( "DEBUG:\nline: {buf}\nfield: {:?}, body: {:?}, expr: {expr_width}, Shape::width: {}", field_width, body_width, formatter.shape.code_line.width ); println!("{:?}", formatter.shape.code_line); println!("{:?}\n", formatter.shape.width_heuristics); } fn format_expr_struct( path: &PathExpr, fields: &Braces<Punctuated<ExprStructField, CommaToken>>, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { path.format(formatted_code, formatter)?; ExprStructField::open_curly_brace(formatted_code, formatter)?; let fields = &fields.get(); match formatter.shape.code_line.line_style { LineStyle::Inline => fields.format(formatted_code, formatter)?, // TODO: add field alignment _ => fields.format(formatted_code, formatter)?, } ExprStructField::close_curly_brace(formatted_code, formatter)?; Ok(()) } /// Checks if the current generated code is too long to fit into a single line /// or it should be broken into multiple lines. The logic to break the /// expression into multiple line is handled inside each struct. /// /// Alternatively, if `expr_new_line` is set to true this function always will /// return true #[inline] pub fn should_write_multiline(code: &str, formatter: &Formatter) -> bool { if formatter.shape.code_line.expr_new_line { true } else { let max_per_line = formatter.shape.width_heuristics.collection_width; for (i, c) in code.chars().rev().enumerate() { if c == '\n' { return i > max_per_line; } } false } } /// Whether this expression can be inlined if it is the sole argument of a /// function/method call #[inline] fn same_line_if_only_argument(expr: &Expr) -> bool { matches!( expr, Expr::Struct { path: _, fields: _ } | Expr::Tuple(_) | Expr::Array(_) | Expr::Parens(_) | Expr::Not { bang_token: _, expr: _ } | Expr::Path(_) | Expr::FuncApp { func: _, args: _ } | Expr::Match { match_token: _, value: _, branches: _ } ) } #[inline] pub(crate) fn is_single_argument_and_can_be_inline<P>( args: &Punctuated<Expr, P>, formatter: &mut Formatter, ) -> bool where P: Format + std::fmt::Debug, { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Normal, ExprKind::Function), |formatter| -> bool { let mut buf = FormattedCode::new(); if args.value_separator_pairs.len() == 1 && args.final_value_opt.is_none() { if same_line_if_only_argument(&args.value_separator_pairs[0].0) { return true; } let _ = args.value_separator_pairs[0].0.format(&mut buf, formatter); } else if args.value_separator_pairs.is_empty() && args.final_value_opt.is_some() { if let Some(final_value) = &args.final_value_opt { if same_line_if_only_argument(final_value) { return true; } let _ = (**final_value).format(&mut buf, formatter); } } else { return false; } buf.len() < formatter.shape.width_heuristics.collection_width }, ) } /// Writes the `(args)` of a function call. This is a common abstraction for
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
true
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/expr/abi_cast.rs
swayfmt/src/utils/language/expr/abi_cast.rs
use crate::{ formatter::*, utils::{ map::byte_span::{ByteSpan, LeafSpans}, Parenthesis, }, }; use std::fmt::Write; use sway_ast::{keywords::Token, AbiCastArgs, CommaToken}; use sway_types::{ast::Delimiter, Spanned}; impl Format for AbiCastArgs { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { Self::open_parenthesis(formatted_code, formatter)?; self.name.format(formatted_code, formatter)?; write!(formatted_code, "{} ", CommaToken::AS_STR)?; self.address.format(formatted_code, formatter)?; Self::close_parenthesis(formatted_code, formatter)?; Ok(()) } } impl Parenthesis for AbiCastArgs { fn open_parenthesis( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_open_char())?; Ok(()) } fn close_parenthesis( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_close_char())?; Ok(()) } } impl LeafSpans for AbiCastArgs { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.name.span())]; collected_spans.push(ByteSpan::from(self.comma_token.span())); collected_spans.append(&mut self.address.leaf_spans()); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/expr/conditional.rs
swayfmt/src/utils/language/expr/conditional.rs
use crate::{ comments::write_comments, formatter::{ shape::{ExprKind, LineStyle}, *, }, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::{fmt::Write, ops::Range}; use sway_ast::{ expr::LoopControlFlow, keywords::{ElseToken, EqToken, FatRightArrowToken, IfToken, Keyword, LetToken, Token}, CommaToken, IfCondition, IfExpr, MatchBranch, MatchBranchKind, }; use sway_types::{ast::Delimiter, Spanned}; impl Format for IfExpr { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::default(), ExprKind::Conditional), |formatter| -> Result<(), FormatterError> { let range: Range<usize> = self.span().into(); let comments = formatter.comments_context.map.comments_between(&range); // check if the entire expression could fit into a single line let full_width_line_style = if comments.peekable().peek().is_some() { LineStyle::Multiline } else { get_full_width_line_style(self, formatter)? }; if full_width_line_style == LineStyle::Inline && self.else_opt.is_some() { formatter .shape .code_line .update_line_style(full_width_line_style); format_if_expr(self, formatted_code, formatter)?; } else { // if it can't then we must format one expression at a time let if_cond_width = get_if_condition_width(self)?; formatter .shape .get_line_style(None, Some(if_cond_width), &formatter.config); if formatter.shape.code_line.line_style == LineStyle::Inline { formatter .shape .code_line .update_line_style(LineStyle::Normal) } format_if_condition(self, formatted_code, formatter)?; format_then_block(self, formatted_code, formatter)?; if self.else_opt.is_some() { format_else_opt(self, formatted_code, formatter)?; } } Ok(()) }, )?; Ok(()) } } fn get_full_width_line_style( if_expr: &IfExpr, formatter: &mut Formatter, ) -> Result<LineStyle, FormatterError> { let mut temp_formatter = Formatter::default(); let line_style = temp_formatter.with_shape( temp_formatter .shape .with_code_line_from(LineStyle::Inline, ExprKind::Conditional), |temp_formatter| -> Result<LineStyle, FormatterError> { let mut if_expr_str = FormattedCode::new(); format_if_expr(if_expr, &mut if_expr_str, temp_formatter)?; let if_expr_width = if_expr_str.chars().count(); temp_formatter.shape.code_line.update_width(if_expr_width); formatter.shape.code_line.update_width(if_expr_width); temp_formatter .shape .get_line_style(None, None, &temp_formatter.config); Ok(temp_formatter.shape.code_line.line_style) }, )?; Ok(line_style) } fn get_if_condition_width(if_expr: &IfExpr) -> Result<usize, FormatterError> { let mut temp_formatter = Formatter::default(); temp_formatter .shape .code_line .update_expr_kind(ExprKind::Conditional); let mut if_cond_str = FormattedCode::new(); format_if_condition(if_expr, &mut if_cond_str, &mut temp_formatter)?; write!(if_cond_str, " {{")?; let condition_width = if_cond_str.chars().count(); Ok(condition_width) } fn format_if_expr( if_expr: &IfExpr, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { format_if_condition(if_expr, formatted_code, formatter)?; format_then_block(if_expr, formatted_code, formatter)?; format_else_opt(if_expr, formatted_code, formatter)?; Ok(()) } fn format_if_condition( if_expr: &IfExpr, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(formatted_code, "{} ", IfToken::AS_STR)?; if formatter.shape.code_line.line_style == LineStyle::Multiline { formatter.indent(); if_expr.condition.format(formatted_code, formatter)?; formatter.unindent(); } else { if_expr.condition.format(formatted_code, formatter)?; } Ok(()) } fn format_then_block( if_expr: &IfExpr, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { IfExpr::open_curly_brace(formatted_code, formatter)?; if !if_expr.then_block.get().statements.is_empty() || if_expr.then_block.get().final_expr_opt.is_some() { if_expr.then_block.get().format(formatted_code, formatter)?; } else { let comments = write_comments( formatted_code, if_expr.then_block.span().start()..if_expr.then_block.span().end(), formatter, )?; if !comments { formatter.shape.block_unindent(&formatter.config); } } if if_expr.else_opt.is_none() { IfExpr::close_curly_brace(formatted_code, formatter)?; } Ok(()) } fn format_else_opt( if_expr: &IfExpr, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { if let Some((else_token, control_flow)) = &if_expr.else_opt { let mut else_if_str = FormattedCode::new(); IfExpr::close_curly_brace(&mut else_if_str, formatter)?; let comments_written = write_comments( &mut else_if_str, if_expr.then_block.span().end()..else_token.span().start(), formatter, )?; if comments_written { write!(else_if_str, "{}", formatter.indent_to_str()?)?; } else { write!(else_if_str, " ")?; } write!(else_if_str, "{}", ElseToken::AS_STR)?; match &control_flow { LoopControlFlow::Continue(if_expr) => { write!(else_if_str, " ")?; if_expr.format(&mut else_if_str, formatter)? } LoopControlFlow::Break(code_block_contents) => { IfExpr::open_curly_brace(&mut else_if_str, formatter)?; code_block_contents .get() .format(&mut else_if_str, formatter)?; IfExpr::close_curly_brace(&mut else_if_str, formatter)?; } } write!(formatted_code, "{else_if_str}")?; } Ok(()) } impl CurlyBrace for IfExpr { fn open_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { let open_brace = Delimiter::Brace.as_open_char(); match formatter.shape.code_line.line_style { LineStyle::Multiline => { formatter.shape.code_line.reset_width(); write!(line, "\n{}{open_brace}", formatter.indent_to_str()?)?; formatter .shape .code_line .update_line_style(LineStyle::Normal); } _ => { write!(line, " {open_brace}")?; } } formatter.indent(); Ok(()) } fn close_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.unindent(); match formatter.shape.code_line.line_style { LineStyle::Inline => { write!(line, "{}", Delimiter::Brace.as_close_char())?; } _ => { write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; } } Ok(()) } } impl Format for IfCondition { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { Self::Expr(expr) => { expr.format(formatted_code, formatter)?; } Self::Let { let_token: _, lhs, eq_token: _, rhs, } => { write!(formatted_code, "{} ", LetToken::AS_STR)?; lhs.format(formatted_code, formatter)?; write!(formatted_code, " {} ", EqToken::AS_STR)?; rhs.format(formatted_code, formatter)?; } } Ok(()) } } impl Format for MatchBranch { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { self.pattern.format(formatted_code, formatter)?; write!(formatted_code, " {} ", FatRightArrowToken::AS_STR)?; self.kind.format(formatted_code, formatter)?; Ok(()) } } impl CurlyBrace for MatchBranch { fn open_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.indent(); writeln!(line, "{}", Delimiter::Brace.as_open_char())?; Ok(()) } fn close_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; Ok(()) } } // Later we should add logic to handle transforming `Block` -> `Expr` and vice versa. impl Format for MatchBranchKind { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { Self::Block { block, comma_token_opt, } => { Self::open_curly_brace(formatted_code, formatter)?; let block = block.get(); if block.statements.is_empty() && block.final_expr_opt.is_none() { // even if there is no code block we still want to unindent // before the closing brace formatter.unindent(); } else { block.format(formatted_code, formatter)?; // we handle this here to avoid needless indents formatter.unindent(); write!(formatted_code, "{}", formatter.indent_to_str()?)?; } Self::close_curly_brace(formatted_code, formatter)?; if comma_token_opt.is_some() { write!(formatted_code, "{}", CommaToken::AS_STR)?; } } Self::Expr { expr, comma_token: _, } => { expr.format(formatted_code, formatter)?; write!(formatted_code, "{}", CommaToken::AS_STR)?; } } Ok(()) } } impl CurlyBrace for MatchBranchKind { fn open_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.indent(); write!(line, "{}", Delimiter::Brace.as_open_char())?; Ok(()) } fn close_curly_brace( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Brace.as_close_char())?; Ok(()) } } impl LeafSpans for IfExpr { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.if_token.span())]; collected_spans.append(&mut self.condition.leaf_spans()); collected_spans.append(&mut self.then_block.leaf_spans()); if let Some(else_block) = &self.else_opt { collected_spans.push(ByteSpan::from(else_block.0.span())); let mut else_body_spans = match &else_block.1 { LoopControlFlow::Continue(if_expr) => if_expr.leaf_spans(), LoopControlFlow::Break(else_body) => else_body.leaf_spans(), }; collected_spans.append(&mut else_body_spans); } collected_spans } } impl LeafSpans for IfCondition { fn leaf_spans(&self) -> Vec<ByteSpan> { match self { IfCondition::Expr(expr) => expr.leaf_spans(), IfCondition::Let { let_token, lhs, eq_token, rhs, } => { let mut collected_spans = vec![ByteSpan::from(let_token.span())]; collected_spans.append(&mut lhs.leaf_spans()); collected_spans.push(ByteSpan::from(eq_token.span())); collected_spans.append(&mut rhs.leaf_spans()); collected_spans } } } } impl LeafSpans for MatchBranch { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.pattern.leaf_spans()); collected_spans.push(ByteSpan::from(self.fat_right_arrow_token.span())); collected_spans.append(&mut self.kind.leaf_spans()); collected_spans } } impl LeafSpans for MatchBranchKind { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); match self { MatchBranchKind::Block { block, comma_token_opt, } => { collected_spans.append(&mut block.leaf_spans()); if let Some(comma_token) = comma_token_opt { collected_spans.push(ByteSpan::from(comma_token.span())); } } MatchBranchKind::Expr { expr, comma_token } => { collected_spans.append(&mut expr.leaf_spans()); collected_spans.push(ByteSpan::from(comma_token.span())); } }; collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/expr/assignable.rs
swayfmt/src/utils/language/expr/assignable.rs
use crate::{ formatter::*, utils::{ map::byte_span::{ByteSpan, LeafSpans}, SquareBracket, }, }; use std::fmt::Write; use sway_ast::{ assignable::ElementAccess, expr::ReassignmentOp, keywords::{DotToken, StarToken, Token}, Assignable, Expr, }; use sway_types::Spanned; impl Format for ElementAccess { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { ElementAccess::Var(name) => { name.format(formatted_code, formatter)?; } ElementAccess::Index { target, arg } => { target.format(formatted_code, formatter)?; Expr::open_square_bracket(formatted_code, formatter)?; arg.get().format(formatted_code, formatter)?; Expr::close_square_bracket(formatted_code, formatter)?; } ElementAccess::FieldProjection { target, dot_token: _, name, } => { target.format(formatted_code, formatter)?; write!(formatted_code, "{}", DotToken::AS_STR)?; name.format(formatted_code, formatter)?; } ElementAccess::TupleFieldProjection { target, dot_token: _, field, field_span: _, } => { target.format(formatted_code, formatter)?; write!(formatted_code, "{}{}", DotToken::AS_STR, field)?; } ElementAccess::Deref { target, star_token: _, is_root_element: root_element, } => { if *root_element { write!(formatted_code, "(")?; } write!(formatted_code, "{}", StarToken::AS_STR)?; target.format(formatted_code, formatter)?; if *root_element { write!(formatted_code, ")")?; } } } Ok(()) } } impl Format for Assignable { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { Assignable::ElementAccess(element_access) => { element_access.format(formatted_code, formatter)? } Assignable::Deref { star_token: _, expr, } => { write!(formatted_code, "{}", StarToken::AS_STR)?; expr.format(formatted_code, formatter)?; } } Ok(()) } } impl Format for ReassignmentOp { fn format( &self, formatted_code: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(formatted_code, " {} ", self.variant.as_str())?; Ok(()) } } impl LeafSpans for ElementAccess { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); match self { ElementAccess::Var(var) => collected_spans.push(ByteSpan::from(var.span())), ElementAccess::Index { target, arg } => { collected_spans.append(&mut target.leaf_spans()); collected_spans.append(&mut arg.leaf_spans()); } ElementAccess::FieldProjection { target, dot_token, name, } => { collected_spans.append(&mut target.leaf_spans()); collected_spans.push(ByteSpan::from(dot_token.span())); collected_spans.push(ByteSpan::from(name.span())); } ElementAccess::TupleFieldProjection { target, dot_token, field: _field, field_span, } => { collected_spans.append(&mut target.leaf_spans()); collected_spans.push(ByteSpan::from(dot_token.span())); collected_spans.push(ByteSpan::from(field_span.clone())); } ElementAccess::Deref { target, star_token, is_root_element: _, } => { collected_spans.push(ByteSpan::from(star_token.span())); collected_spans.append(&mut target.leaf_spans()); } }; collected_spans } } impl LeafSpans for Assignable { fn leaf_spans(&self) -> Vec<ByteSpan> { match self { Assignable::ElementAccess(element_access) => element_access.leaf_spans(), Assignable::Deref { star_token, expr } => { let mut collected_spans = Vec::new(); collected_spans.push(ByteSpan::from(star_token.span())); collected_spans.append(&mut expr.leaf_spans()); collected_spans } } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/utils/language/expr/code_block.rs
swayfmt/src/utils/language/expr/code_block.rs
use crate::{ comments::write_comments, formatter::{shape::LineStyle, *}, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::fmt::Write; use sway_ast::CodeBlockContents; use sway_types::{ast::Delimiter, Spanned}; impl Format for CodeBlockContents { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { if !self.statements.is_empty() || self.final_expr_opt.is_some() { match formatter.shape.code_line.line_style { LineStyle::Inline => { write!(formatted_code, " ")?; for statement in self.statements.iter() { statement.format(formatted_code, formatter)?; } if let Some(final_expr) = &self.final_expr_opt { final_expr.format(formatted_code, formatter)?; } write!(formatted_code, " ")?; } _ => { writeln!(formatted_code)?; for statement in self.statements.iter() { write!(formatted_code, "{}", formatter.indent_to_str()?)?; statement.format(formatted_code, formatter)?; if !formatted_code.ends_with('\n') { writeln!(formatted_code)?; } } if let Some(final_expr) = &self.final_expr_opt { write!(formatted_code, "{}", formatter.indent_to_str()?)?; final_expr.format(formatted_code, formatter)?; writeln!(formatted_code)?; } } } } else { let comments: bool = write_comments( formatted_code, self.span().start()..self.span().end(), formatter, )?; if !comments { formatter.shape.block_unindent(&formatter.config); } } Ok(()) } } impl CurlyBrace for CodeBlockContents { fn open_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.indent(); // Add opening brace to the same line write!(line, "{}", Delimiter::Brace.as_open_char())?; Ok(()) } fn close_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Unindent by one block formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; Ok(()) } } impl LeafSpans for CodeBlockContents { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_span = Vec::new(); for statement in self.statements.iter() { collected_span.append(&mut statement.leaf_spans()); } if let Some(expr) = &self.final_expr_opt { collected_span.append(&mut expr.leaf_spans()); } collected_span } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_trait_type.rs
swayfmt/src/items/item_trait_type.rs
use crate::{ comments::rewrite_with_comments, formatter::*, utils::map::byte_span::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_ast::{ keywords::{EqToken, Keyword, SemicolonToken, Token, TypeToken}, TraitType, }; use sway_types::Spanned; impl Format for TraitType { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Required for comment formatting let start_len = formatted_code.len(); // Add the type token write!(formatted_code, "{} ", TypeToken::AS_STR)?; // Add name of the type self.name.format(formatted_code, formatter)?; // Check if ` = ` exists if self.eq_token_opt.is_some() { write!(formatted_code, " {} ", EqToken::AS_STR)?; } // Check if ty exists if let Some(ty) = &self.ty_opt { ty.format(formatted_code, formatter)?; } write!(formatted_code, "{}", SemicolonToken::AS_STR)?; rewrite_with_comments::<TraitType>( formatter, self.span(), self.leaf_spans(), formatted_code, start_len, )?; Ok(()) } } impl LeafSpans for TraitType { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); collected_spans.push(ByteSpan::from(self.type_token.span())); collected_spans.push(ByteSpan::from(self.name.span())); if let Some(eq_token) = &self.eq_token_opt { collected_spans.push(ByteSpan::from(eq_token.span())); } if let Some(ty) = &self.ty_opt { collected_spans.append(&mut ty.leaf_spans()); } collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_type_alias.rs
swayfmt/src/items/item_type_alias.rs
use crate::{ comments::rewrite_with_comments, formatter::*, utils::map::byte_span::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_ast::{ keywords::{EqToken, Keyword, SemicolonToken, Token, TypeToken}, ItemTypeAlias, PubToken, }; use sway_types::Spanned; impl Format for ItemTypeAlias { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Required for comment formatting let start_len = formatted_code.len(); // Check if visibility token exists if so add it. if self.visibility.is_some() { write!(formatted_code, "{} ", PubToken::AS_STR)?; } // Add the `type` token write!(formatted_code, "{} ", TypeToken::AS_STR)?; // Add name of the type alias self.name.format(formatted_code, formatter)?; // Add the `=` token write!(formatted_code, " {} ", EqToken::AS_STR)?; // Format and add `ty` self.ty.format(formatted_code, formatter)?; // Add the `;` token write!(formatted_code, "{}", SemicolonToken::AS_STR)?; rewrite_with_comments::<ItemTypeAlias>( formatter, self.span(), self.leaf_spans(), formatted_code, start_len, )?; Ok(()) } } impl LeafSpans for ItemTypeAlias { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); } collected_spans.push(ByteSpan::from(self.type_token.span())); collected_spans.push(ByteSpan::from(self.name.span())); collected_spans.push(ByteSpan::from(self.eq_token.span())); collected_spans.append(&mut self.ty.leaf_spans()); collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_const.rs
swayfmt/src/items/item_const.rs
use crate::{ comments::rewrite_with_comments, formatter::*, utils::map::byte_span::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_ast::{ keywords::{ColonToken, ConstToken, EqToken, Keyword, SemicolonToken, Token}, ItemConst, PubToken, }; use sway_types::Spanned; impl Format for ItemConst { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Required for comment formatting let start_len = formatted_code.len(); // Check if pub token exists, if so add it. if self.pub_token.is_some() { write!(formatted_code, "{} ", PubToken::AS_STR)?; } // Add the const token write!(formatted_code, "{} ", ConstToken::AS_STR)?; // Add name of the const self.name.format(formatted_code, formatter)?; // Check if ty exists if let Some((_colon_token, ty)) = &self.ty_opt { // Add colon write!(formatted_code, "{} ", ColonToken::AS_STR)?; ty.format(formatted_code, formatter)?; } // Check if ` = ` exists if self.eq_token_opt.is_some() { write!(formatted_code, " {} ", EqToken::AS_STR)?; } // Check if expression exists if let Some(expr) = &self.expr_opt { expr.format(formatted_code, formatter)?; } write!(formatted_code, "{}", SemicolonToken::AS_STR)?; rewrite_with_comments::<ItemConst>( formatter, self.span(), self.leaf_spans(), formatted_code, start_len, )?; Ok(()) } } impl LeafSpans for ItemConst { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.pub_token { collected_spans.push(ByteSpan::from(visibility.span())); } collected_spans.push(ByteSpan::from(self.const_token.span())); collected_spans.push(ByteSpan::from(self.name.span())); if let Some(ty) = &self.ty_opt { collected_spans.append(&mut ty.leaf_spans()); } if let Some(eq_token) = &self.eq_token_opt { collected_spans.push(ByteSpan::from(eq_token.span())); } if let Some(expr) = &self.expr_opt { collected_spans.append(&mut expr.leaf_spans()); } collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/mod.rs
swayfmt/src/items/mod.rs
mod item_abi; mod item_configurable; mod item_const; mod item_enum; mod item_fn; mod item_impl; mod item_storage; mod item_struct; mod item_trait; mod item_trait_type; mod item_type_alias; mod item_use;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_impl/tests.rs
swayfmt/src/items/item_impl/tests.rs
use forc_tracing::{println_green, println_red}; use paste::paste; use prettydiff::{basic::DiffOp, diff_lines}; use test_macros::fmt_test_item; fmt_test_item!( impl_with_nested_items "impl AuthTesting for Contract { fn returns_msg_sender(expected_id: ContractId) -> bool { let result: Result<Identity, AuthError> = msg_sender(); let mut ret = false; if result.is_err() { ret = false; } let unwrapped = result.unwrap(); match unwrapped { Identity::ContractId(v) => { ret = true } _ => { ret = false } } ret } }", intermediate_whitespace "impl AuthTesting for Contract { fn returns_msg_sender(expected_id: ContractId) -> bool { let result: Result<Identity, AuthError> = msg_sender(); let mut ret = false; if result.is_err() { ret = false; } let unwrapped = result.unwrap(); match unwrapped { Identity::ContractId(v) => {ret = true} _ => {ret = false} } ret } }" ); fmt_test_item!( normal_with_generics "impl<T> Option<T> { fn some(value: T) -> Self { Option::Some::<T>(value) } fn none() -> Self { None::<T>(()) } fn to_result(self) -> Result<T> { if let Option::Some(value) = self { Result::<T>::ok(value) } else { Result::<T>::err(99u8) } } }", intermediate_whitespace "impl<T> Option<T> { fn some(value: T) -> Self { Option::Some::<T>(value) } fn none() -> Self { None::<T>(()) } fn to_result(self) -> Result<T> { if let Option::Some(value) = self { Result::<T>::ok(value) } else { Result::<T>::err(99u8) } } }" ); fmt_test_item!( impl_empty_fn_args "impl TestContract for Contract { fn return_configurables() -> (u8, bool, [u32; 3], str[4], StructWithGeneric<u8>, EnumWithGeneric<bool>) { (U8, BOOL, ARRAY, STR_4, STRUCT, ENUM) } }", intermediate_whitespace "impl TestContract for Contract { fn return_configurables( ) -> ( u8, bool, [u32; 3], str[4], StructWithGeneric<u8>, EnumWithGeneric<bool> ) { ( U8, BOOL, ARRAY, STR_4 , STRUCT, ENUM ) } } " ); fmt_test_item!( impl_empty_fn_comment "impl MyAbi for Contract { fn foo() { // ... logic ... } }", intermediate_whitespace "impl MyAbi for Contract { fn foo( ) { // ... logic ... } }" ); fmt_test_item!(impl_contains_const "impl ConstantId for Struct { const ID: u32 = 5; }", intermediate_whitespace "impl ConstantId for Struct { const ID: u32=5; }" ); fmt_test_item!(impl_for_struct_where_clause "impl MyStructWithWhere<T, A> where T: Something, A: Something, { fn do() {} }", intermediate_whitespace "impl MyStructWithWhere<T, A> where T: Something, A: Something { fn do() {} }" ); fmt_test_item!(impl_trait_for_struct_where_clause "impl MyTrait<T, A> for MyStructWithWhere<T, A> where T: Something, A: Something, { fn do() {} }", intermediate_whitespace "impl MyTrait<T, A> for MyStructWithWhere<T, A> where T: Something, A: Something { fn do() {} }" );
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_impl/mod.rs
swayfmt/src/items/item_impl/mod.rs
use crate::{ comments::{has_comments_in_formatter, rewrite_with_comments, write_comments}, constants::NEW_LINE, formatter::*, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::fmt::Write; use sway_ast::{ keywords::{ForToken, ImplToken, Keyword}, ItemImpl, ItemImplItem, }; use sway_types::{ast::Delimiter, Spanned}; #[cfg(test)] mod tests; impl Format for ItemImpl { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Required for comment formatting let start_len = formatted_code.len(); write!(formatted_code, "{}", ImplToken::AS_STR)?; if let Some(generic_params) = &self.generic_params_opt { generic_params.format(formatted_code, formatter)?; } write!(formatted_code, " ")?; if let Some((path_type, _for_token)) = &self.trait_opt { path_type.format(formatted_code, formatter)?; write!(formatted_code, " {} ", ForToken::AS_STR)?; } self.ty.format(formatted_code, formatter)?; if let Some(where_clause) = &self.where_clause_opt { writeln!(formatted_code)?; where_clause.format(formatted_code, formatter)?; formatter.shape.code_line.update_where_clause(true); } let contents = self.contents.get(); if contents.is_empty() { let range = self.span().into(); Self::open_curly_brace(formatted_code, formatter)?; if has_comments_in_formatter(formatter, &range) { formatter.indent(); write_comments(formatted_code, range, formatter)?; } Self::close_curly_brace(formatted_code, formatter)?; } else { Self::open_curly_brace(formatted_code, formatter)?; formatter.indent(); write!(formatted_code, "{NEW_LINE}")?; for item in contents.iter() { item.format(formatted_code, formatter)?; write!(formatted_code, "{NEW_LINE}")?; } Self::close_curly_brace(formatted_code, formatter)?; } rewrite_with_comments::<ItemImpl>( formatter, self.span(), self.leaf_spans(), formatted_code, start_len, )?; Ok(()) } } impl Format for ItemImplItem { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { ItemImplItem::Fn(fn_decl) => fn_decl.format(formatted_code, formatter), ItemImplItem::Const(const_decl) => const_decl.format(formatted_code, formatter), ItemImplItem::Type(type_decl) => type_decl.format(formatted_code, formatter), } } } impl CurlyBrace for ItemImpl { fn open_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { let open_brace = Delimiter::Brace.as_open_char(); match formatter.shape.code_line.has_where_clause { true => { write!(line, "{open_brace}")?; formatter.shape.code_line.update_where_clause(false); } false => { write!(line, " {open_brace}")?; } } Ok(()) } fn close_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; Ok(()) } } impl LeafSpans for ItemImplItem { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![]; match self { ItemImplItem::Fn(fn_decl) => collected_spans.append(&mut fn_decl.leaf_spans()), ItemImplItem::Const(const_decl) => collected_spans.append(&mut const_decl.leaf_spans()), ItemImplItem::Type(type_decl) => collected_spans.append(&mut type_decl.leaf_spans()), } collected_spans } } impl LeafSpans for ItemImpl { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.impl_token.span())]; if let Some(generic) = &self.generic_params_opt { collected_spans.push(ByteSpan::from(generic.parameters.span())); } if let Some(trait_tuple) = &self.trait_opt { collected_spans.append(&mut trait_tuple.leaf_spans()); } collected_spans.append(&mut self.ty.leaf_spans()); if let Some(where_clause) = &self.where_clause_opt { collected_spans.append(&mut where_clause.leaf_spans()); } collected_spans.append(&mut self.contents.leaf_spans()); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_struct/tests.rs
swayfmt/src/items/item_struct/tests.rs
use forc_tracing::{println_green, println_red}; use paste::paste; use prettydiff::{basic::DiffOp, diff_lines}; use test_macros::fmt_test_item; fmt_test_item!( annotated_struct "pub struct Annotated { #[storage(write)] foo: u32, #[storage(read)] bar: String, }", intermediate_whitespace "pub struct Annotated{ #[ storage(write )]\n foo : u32, #[ storage(read ) ] bar : String, }" ); fmt_test_item!( struct_with_where_clause "pub struct HasWhereClause<T, A> where T: Something, A: Something, { t: T, a: A, }", intermediate_whitespace "pub struct HasWhereClause < T, A > where T: Something, A : Something, { t : T, a : A, } " );
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_struct/mod.rs
swayfmt/src/items/item_struct/mod.rs
use crate::{ comments::{rewrite_with_comments, write_comments}, config::user_def::FieldAlignment, formatter::{ shape::{ExprKind, LineStyle}, *, }, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::fmt::Write; use sway_ast::{ keywords::{ColonToken, Keyword, StructToken, Token}, CommaToken, ItemStruct, PubToken, }; use sway_types::{ast::Delimiter, Spanned}; #[cfg(test)] mod tests; impl Format for ItemStruct { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Multiline, ExprKind::default()), |formatter| -> Result<(), FormatterError> { // Required for comment formatting let start_len = formatted_code.len(); // If there is a visibility token add it to the formatted_code with a ` ` after it. if self.visibility.is_some() { write!(formatted_code, "{} ", PubToken::AS_STR)?; } // Add struct token and name write!(formatted_code, "{} ", StructToken::AS_STR)?; self.name.format(formatted_code, formatter)?; // Format `GenericParams`, if any if let Some(generics) = &self.generics { generics.format(formatted_code, formatter)?; } if let Some(where_clause) = &self.where_clause_opt { writeln!(formatted_code)?; where_clause.format(formatted_code, formatter)?; formatter.shape.code_line.update_where_clause(true); } let fields = self.fields.get(); // Handle opening brace Self::open_curly_brace(formatted_code, formatter)?; if fields.is_empty() { write_comments(formatted_code, self.span().into(), formatter)?; } formatter.shape.code_line.update_expr_new_line(true); // Determine alignment tactic match formatter.config.structures.field_alignment { FieldAlignment::AlignFields(struct_field_align_threshold) => { writeln!(formatted_code)?; let type_fields = &fields .value_separator_pairs .iter() // TODO: Handle annotations instead of stripping them. // See: https://github.com/FuelLabs/sway/issues/6802 .map(|(type_field, _comma_token)| &type_field.value) .collect::<Vec<_>>(); // In first iteration we are going to be collecting the lengths of the struct fields. // We need to include the `pub` keyword in the length, if the field is public, // together with one space character between the `pub` and the name. let fields_lengths: Vec<usize> = type_fields .iter() .map(|type_field| { type_field .visibility .as_ref() .map_or(0, |_pub_token| PubToken::AS_STR.len() + 1) + type_field.name.as_str().len() }) .collect(); // Find the maximum length that is still smaller than the align threshold. let mut max_valid_field_length = 0; fields_lengths.iter().for_each(|length| { if *length > max_valid_field_length && *length < struct_field_align_threshold { max_valid_field_length = *length; } }); for (var_index, type_field) in type_fields.iter().enumerate() { write!(formatted_code, "{}", formatter.indent_to_str()?)?; // If there is a visibility token add it to the formatted_code with a ` ` after it. if type_field.visibility.is_some() { write!(formatted_code, "{} ", PubToken::AS_STR)?; } // Add name type_field.name.format(formatted_code, formatter)?; let current_field_length = fields_lengths[var_index]; if current_field_length < max_valid_field_length { // We need to add alignment between : and ty // max_valid_variant_length: the length of the variant that we are taking as a reference to align // current_variant_length: the length of the current variant that we are trying to format let mut required_alignment = max_valid_field_length - current_field_length; while required_alignment != 0 { write!(formatted_code, " ")?; required_alignment -= 1; } } // Add `:`, ty & `CommaToken` write!(formatted_code, " {} ", ColonToken::AS_STR)?; type_field.ty.format(formatted_code, formatter)?; writeln!(formatted_code, "{}", CommaToken::AS_STR)?; } if let Some(final_value) = &fields.final_value_opt { final_value.format(formatted_code, formatter)?; writeln!(formatted_code)?; } } FieldAlignment::Off => { fields.format(formatted_code, formatter)?; } } // Handle closing brace Self::close_curly_brace(formatted_code, formatter)?; rewrite_with_comments::<ItemStruct>( formatter, self.span(), self.leaf_spans(), formatted_code, start_len, )?; Ok(()) }, )?; Ok(()) } } impl CurlyBrace for ItemStruct { fn open_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.indent(); let open_brace = Delimiter::Brace.as_open_char(); match formatter.shape.code_line.has_where_clause { true => { write!(line, "{open_brace}")?; formatter.shape.code_line.update_where_clause(false); } false => { write!(line, " {open_brace}")?; } } Ok(()) } fn close_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // If shape is becoming left-most aligned or - indent just have the default shape formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; Ok(()) } } impl LeafSpans for ItemStruct { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); } collected_spans.push(ByteSpan::from(self.struct_token.span())); collected_spans.push(ByteSpan::from(self.name.span())); if let Some(generics) = &self.generics { collected_spans.push(ByteSpan::from(generics.parameters.span())) } collected_spans.append(&mut self.fields.leaf_spans()); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_use/tests.rs
swayfmt/src/items/item_use/tests.rs
use forc_tracing::{println_green, println_red}; use paste::paste; use prettydiff::{basic::DiffOp, diff_lines}; use test_macros::fmt_test_item; fmt_test_item!(multiline "use foo::{ quux, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, };", out_of_order "use foo::{yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, quux, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx};" ); fmt_test_item!(multiline_with_trailing_comma "use foo::{ quux, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, };", out_of_order "use foo::{yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, quux, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,};" ); fmt_test_item!(multiline_nested "use foo::{ Quux::{ a, b, C, }, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, };", out_of_order "use foo::{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, Quux::{b, a, C}, yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx};" ); fmt_test_item!(multiline_nested_with_trailing_comma "use foo::{ Quux::{ a, b, C, }, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, };", out_of_order "use foo::{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, Quux::{b, a, C,}, yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,};" ); fmt_test_item!(single_line_sort "use foo::{bar, baz, Quux::{a, b, C}};", out_of_order "use foo::{baz, Quux::{b, a, C}, bar};" ); fmt_test_item!(single_line_sort_with_trailing_comma "use foo::{bar, baz, Quux::{a, b, C}};", out_of_order "use foo::{baz, Quux::{b, a, C,}, bar,};" ); fmt_test_item!(single_import_without_braces "use std::tx::tx_id;", braced_single_import "use std::tx::{tx_id};" ); fmt_test_item!(single_import_without_braces_with_trailing_comma "use std::tx::tx_id;", braced_single_import "use std::tx::{tx_id,};" ); fmt_test_item!(single_import_multiline_with_braces "use std::tx::{ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, };", braced_single_import "use std::tx::{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx};" ); fmt_test_item!(single_import_multiline_with_braces_with_trailing_comma "use std::tx::{ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, };", braced_single_import "use std::tx::{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,};" ); #[test] fn single_import_with_braces_preserves_following_item() { // Regression test for: https://github.com/FuelLabs/sway/issues/7434 use crate::Formatter; use indoc::indoc; let unformatted = indoc! {r#" contract; use utils::{IssuanceParams}; pub struct BridgeRegisteredEvent { pub bridge_name: String, pub bridge_id: b256, } "#}; let expected = indoc! {r#" contract; use utils::IssuanceParams; pub struct BridgeRegisteredEvent { pub bridge_name: String, pub bridge_id: b256, } "#}; let mut formatter = Formatter::default(); let first_formatted = Formatter::format(&mut formatter, unformatted.into()).unwrap(); // The critical assertion: "pub struct BridgeRegisteredEvent" should stay on one line assert!( !first_formatted.contains("pub struct\n"), "Bug regression: struct name was split from 'pub struct' keyword" ); assert_eq!(first_formatted, expected); // Ensure idempotency let second_formatted = Formatter::format(&mut formatter, first_formatted.as_str().into()).unwrap(); assert_eq!(second_formatted, first_formatted); }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_use/mod.rs
swayfmt/src/items/item_use/mod.rs
use crate::{ formatter::{ shape::{ExprKind, LineStyle}, *, }, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::fmt::Write; use sway_ast::{ keywords::{AsToken, Keyword, SemicolonToken, StarToken, Token, UseToken}, CommaToken, DoubleColonToken, ItemUse, PubToken, UseTree, }; use sway_types::{ast::Delimiter, Spanned}; #[cfg(test)] mod tests; impl Format for ItemUse { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Multiline, ExprKind::Import), |formatter| -> Result<(), FormatterError> { // get the length in chars of the code_line in a single line format, // this include the path let mut buf = FormattedCode::new(); let mut temp_formatter = formatter.clone(); temp_formatter .shape .code_line .update_line_style(LineStyle::Normal); format_use_stmt(self, &mut buf, &mut temp_formatter)?; let expr_width = buf.chars().count(); formatter.shape.code_line.add_width(expr_width); formatter .shape .get_line_style(None, None, &formatter.config); format_use_stmt(self, formatted_code, formatter)?; Ok(()) }, )?; Ok(()) } } impl Format for UseTree { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { Self::Group { imports } => { // check for only one import if imports.inner.value_separator_pairs.is_empty() && !formatter.shape.code_line.line_style.is_multiline() { // we can have: path::{single_import} // Record that we're removing the opening and closing braces // Format: (byte_position, bytes_removed) let open_brace_pos = imports.span().start(); let close_brace_pos = imports.span().end() - 1; formatter.removed_spans.push((open_brace_pos, 1)); // Remove '{' formatter.removed_spans.push((close_brace_pos, 1)); // Remove '}' if let Some(single_import) = &imports.inner.final_value_opt { single_import.format(formatted_code, formatter)?; } } else if imports.inner.value_separator_pairs.len() == 1 && imports.inner.has_trailing_punctuation() && !formatter.shape.code_line.line_style.is_multiline() { // but we can also have: path::{single_import,} // note that in the case of multiline we want to keep the trailing comma let open_brace_pos = imports.span().start(); let close_brace_pos = imports.span().end() - 1; formatter.removed_spans.push((open_brace_pos, 1)); // Remove '{' // Also removing the trailing comma (1 byte) before the '}' formatter.removed_spans.push((close_brace_pos - 1, 1)); // Remove ',' formatter.removed_spans.push((close_brace_pos, 1)); // Remove '}' let single_import = &imports .inner .value_separator_pairs .first() .expect("the `if` condition ensures the existence of the first element") .0; single_import.format(formatted_code, formatter)?; } else { Self::open_curly_brace(formatted_code, formatter)?; // sort group imports let imports = imports.get(); let value_pairs = &imports.value_separator_pairs; // track how many commas we have, to simplify checking for trailing element or trailing comma let mut commas: Vec<()> = Vec::new(); let mut ord_vec: Vec<String> = value_pairs .iter() .map( |(use_tree, _comma_token)| -> Result<FormattedCode, FormatterError> { let mut buf = FormattedCode::new(); use_tree.format(&mut buf, formatter)?; commas.push(()); // we have a comma token Ok(buf) }, ) .collect::<Result<_, _>>()?; if let Some(final_value) = &imports.final_value_opt { let mut buf = FormattedCode::new(); final_value.format(&mut buf, formatter)?; ord_vec.push(buf); } ord_vec.sort_by(|a, b| { if a == b { std::cmp::Ordering::Equal } else if a == "self" || b == "*" { std::cmp::Ordering::Less } else if b == "self" || a == "*" { std::cmp::Ordering::Greater } else { a.to_lowercase().cmp(&b.to_lowercase()) } }); // zip will take only the parts of `ord_vec` before the last comma for (use_tree, _) in ord_vec.iter_mut().zip(commas.iter()) { write!(use_tree, "{}", CommaToken::AS_STR)?; } match formatter.shape.code_line.line_style { LineStyle::Multiline => { if imports.final_value_opt.is_some() { if let Some(last) = ord_vec.iter_mut().last() { write!(last, "{}", CommaToken::AS_STR)?; } } writeln!( formatted_code, "{}{}", formatter.indent_to_str()?, ord_vec.join(&format!("\n{}", formatter.indent_to_str()?)), )?; } _ => { if imports.has_trailing_punctuation() { // remove the trailing punctuation write!( formatted_code, "{}", ord_vec.join(" ").trim_end_matches(',') )?; } else { write!(formatted_code, "{}", ord_vec.join(" "))?; } } } Self::close_curly_brace(formatted_code, formatter)?; } } Self::Name { name } => write!(formatted_code, "{}", name.as_str())?, Self::Rename { name, as_token: _, alias, } => { write!( formatted_code, "{} {} {}", name.as_str(), AsToken::AS_STR, alias.as_str(), )?; } Self::Glob { star_token: _ } => { write!(formatted_code, "{}", StarToken::AS_STR)?; } Self::Path { prefix, double_colon_token: _, suffix, } => { write!( formatted_code, "{}{}", prefix.as_str(), DoubleColonToken::AS_STR, )?; suffix.format(formatted_code, formatter)?; } Self::Error { .. } => { return Err(FormatterError::SyntaxError); } } Ok(()) } } impl CurlyBrace for UseTree { fn open_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match formatter.shape.code_line.line_style { LineStyle::Multiline => { formatter.indent(); writeln!(line, "{}", Delimiter::Brace.as_open_char())?; } _ => write!(line, "{}", Delimiter::Brace.as_open_char())?, } Ok(()) } fn close_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match formatter.shape.code_line.line_style { LineStyle::Multiline => { formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; } _ => write!(line, "{}", Delimiter::Brace.as_close_char())?, } Ok(()) } } fn format_use_stmt( item_use: &ItemUse, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { if item_use.visibility.is_some() { write!(formatted_code, "{} ", PubToken::AS_STR)?; } write!(formatted_code, "{} ", UseToken::AS_STR)?; if item_use.root_import.is_some() { write!(formatted_code, "{}", DoubleColonToken::AS_STR)?; } item_use.tree.format(formatted_code, formatter)?; write!(formatted_code, "{}", SemicolonToken::AS_STR)?; Ok(()) } impl LeafSpans for ItemUse { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); } collected_spans.push(ByteSpan::from(self.use_token.span())); if let Some(root_import) = &self.root_import { collected_spans.push(ByteSpan::from(root_import.span())); } collected_spans.append(&mut self.tree.leaf_spans()); collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } } impl LeafSpans for UseTree { fn leaf_spans(&self) -> Vec<ByteSpan> { match self { UseTree::Group { imports } => imports.leaf_spans(), UseTree::Name { name } => vec![ByteSpan::from(name.span())], UseTree::Rename { name, as_token, alias, } => vec![ ByteSpan::from(name.span()), ByteSpan::from(as_token.span()), ByteSpan::from(alias.span()), ], UseTree::Glob { star_token } => vec![ByteSpan::from(star_token.span())], UseTree::Path { prefix, double_colon_token, suffix, } => { let mut collected_spans = vec![ByteSpan::from(prefix.span())]; collected_spans.push(ByteSpan::from(double_colon_token.span())); collected_spans.append(&mut suffix.leaf_spans()); collected_spans } UseTree::Error { spans } => spans.iter().map(|s| ByteSpan::from(s.clone())).collect(), } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_enum/tests.rs
swayfmt/src/items/item_enum/tests.rs
use forc_tracing::{println_green, println_red}; use paste::paste; use prettydiff::{basic::DiffOp, diff_lines}; use test_macros::fmt_test_item; fmt_test_item!( annotated_enum "pub enum Annotated { #[storage(write)] foo: (), #[storage(read)] bar: (), }", intermediate_whitespace "pub enum Annotated{ #[ storage(write )]\n foo : (), #[ storage(read ) ] bar : (), }" );
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_enum/mod.rs
swayfmt/src/items/item_enum/mod.rs
use crate::{ comments::rewrite_with_comments, config::user_def::FieldAlignment, formatter::{ shape::{ExprKind, LineStyle}, *, }, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::fmt::Write; use sway_ast::{ keywords::{ColonToken, EnumToken, Keyword, Token}, CommaToken, ItemEnum, PubToken, }; use sway_types::{ast::Delimiter, Spanned}; #[cfg(test)] mod tests; impl Format for ItemEnum { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Multiline, ExprKind::default()), |formatter| -> Result<(), FormatterError> { // Required for comment formatting let start_len = formatted_code.len(); // If there is a visibility token add it to the formatted_code with a ` ` after it. if self.visibility.is_some() { write!(formatted_code, "{} ", PubToken::AS_STR)?; } // Add enum token and name write!(formatted_code, "{} ", EnumToken::AS_STR)?; self.name.format(formatted_code, formatter)?; // Format `GenericParams`, if any if let Some(generics) = &self.generics { generics.format(formatted_code, formatter)?; } let fields = self.fields.get(); formatter.shape.code_line.update_expr_new_line(true); // Handle opening brace Self::open_curly_brace(formatted_code, formatter)?; // Determine alignment tactic match formatter.config.structures.field_alignment { FieldAlignment::AlignFields(enum_variant_align_threshold) => { writeln!(formatted_code)?; let type_fields = &fields .value_separator_pairs .iter() // TODO: Handle annotations instead of stripping them. // See: https://github.com/FuelLabs/sway/issues/6802 .map(|(type_field, _comma_token)| &type_field.value) .collect::<Vec<_>>(); // In first iteration we are going to be collecting the lengths of the enum variants. let variants_lengths: Vec<usize> = type_fields .iter() .map(|type_field| type_field.name.as_str().len()) .collect(); // Find the maximum length that is still smaller than the align threshold. let mut max_valid_variant_length = 0; variants_lengths.iter().for_each(|length| { if *length > max_valid_variant_length && *length < enum_variant_align_threshold { max_valid_variant_length = *length; } }); for (var_index, type_field) in type_fields.iter().enumerate() { write!(formatted_code, "{}", formatter.indent_to_str()?)?; // Add name type_field.name.format(formatted_code, formatter)?; let current_variant_length = variants_lengths[var_index]; if current_variant_length < max_valid_variant_length { // We need to add alignment between : and ty // max_valid_variant_length: the length of the variant that we are taking as a reference to align // current_variant_length: the length of the current variant that we are trying to format let mut required_alignment = max_valid_variant_length - current_variant_length; while required_alignment != 0 { write!(formatted_code, " ")?; required_alignment -= 1; } } // Add `:`, ty & `CommaToken` write!(formatted_code, " {} ", ColonToken::AS_STR)?; type_field.ty.format(formatted_code, formatter)?; writeln!(formatted_code, "{}", CommaToken::AS_STR)?; } if let Some(final_value) = &fields.final_value_opt { final_value.format(formatted_code, formatter)?; writeln!(formatted_code)?; } } FieldAlignment::Off => fields.format(formatted_code, formatter)?, } // Handle closing brace Self::close_curly_brace(formatted_code, formatter)?; rewrite_with_comments::<ItemEnum>( formatter, self.span(), self.leaf_spans(), formatted_code, start_len, )?; Ok(()) }, )?; Ok(()) } } impl CurlyBrace for ItemEnum { fn open_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { let open_brace = Delimiter::Brace.as_open_char(); // Add opening brace to the same line write!(line, " {open_brace}")?; formatter.indent(); Ok(()) } fn close_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // If shape is becoming left-most aligned or - indent just have the default shape formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; Ok(()) } } impl LeafSpans for ItemEnum { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); } collected_spans.push(ByteSpan::from(self.enum_token.span())); collected_spans.push(ByteSpan::from(self.name.span())); if let Some(generics) = &self.generics { collected_spans.push(ByteSpan::from(generics.parameters.span())) } collected_spans.append(&mut self.fields.leaf_spans()); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_trait/tests.rs
swayfmt/src/items/item_trait/tests.rs
use forc_tracing::{println_green, println_red}; use paste::paste; use prettydiff::{basic::DiffOp, diff_lines}; use test_macros::fmt_test_item; fmt_test_item!( trait_annotated_fn "pub trait MyTrait { #[storage(read, write)] fn foo(self); }", intermediate_whitespace " pub trait MyTrait { #[storage( read , write) ] fn foo(self); } " ); fmt_test_item!( trait_vertically_annotated_fn "pub trait MyTrait { #[storage(read)] #[storage(write)] fn foo(self); }", intermediate_whitespace " pub trait MyTrait { #[storage( read ) ] #[ storage( write)] fn foo(self); } " ); fmt_test_item!( trait_commented_annotated_fn "pub trait MyTrait { /// Doc /// Comment #[storage(read, write)] fn foo(self); }", intermediate_whitespace " pub trait MyTrait { /// Doc /// Comment #[storage( read , write) ] fn foo(self); } " ); fmt_test_item!( trait_commented_fn "pub trait MyTrait { /// Comment fn foo(self); }", intermediate_whitespace " pub trait MyTrait { /// Comment fn foo(self); } " ); fmt_test_item!(trait_contains_const "trait ConstantId { const ID: u32 = 1; }", intermediate_whitespace "trait ConstantId { const ID: u32 = 1; }"); fmt_test_item!( trait_normal_comment_two_fns "pub trait MyTrait { // Before A fn a(self); // Before b fn b(self); }", intermediate_whitespace " pub trait MyTrait { // Before A fn a(self); // Before b fn b(self); } " ); fmt_test_item!(trait_multiline_method "trait MyComplexTrait { fn complex_function( arg1: MyStruct<[b256; 3], u8>, arg2: [MyStruct<u64, bool>; 4], arg3: (str[5], bool), arg4: MyOtherStruct, ) -> str[6]; }", intermediate_whitespace "trait MyComplexTrait { fn complex_function( arg1: MyStruct<[b256; 3], u8> , arg2: [MyStruct <u64, bool>; 4], arg3: ( str[5], bool ), arg4: MyOtherStruct) -> str[6] ; }"); fmt_test_item!(trait_with_where_clause "trait TraitWithWhere<T, A> where T: Something, A: Something, { fn my_fn(); }", intermediate_whitespace "trait TraitWithWhere<T, A> where T: Something, A: Something { fn my_fn(); }");
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_trait/mod.rs
swayfmt/src/items/item_trait/mod.rs
use crate::{ comments::{rewrite_with_comments, write_comments}, constants::NEW_LINE, formatter::*, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::fmt::Write; use sway_ast::{ keywords::{AddToken, ColonToken, Keyword, Token, TraitToken}, ItemTrait, ItemTraitItem, PubToken, Traits, }; use sway_types::{ast::Delimiter, Spanned}; #[cfg(test)] mod tests; impl Format for ItemTrait { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Required for comment formatting let start_len = formatted_code.len(); // `pub ` if self.visibility.is_some() { write!(formatted_code, "{} ", PubToken::AS_STR)?; } // `trait name` write!( formatted_code, "{} {}", TraitToken::AS_STR, self.name.as_str(), )?; // `<T>` if let Some(generics) = &self.generics { generics.format(formatted_code, formatter)?; } // `: super_trait + super_trait` if let Some((_colon_token, traits)) = &self.super_traits { write!(formatted_code, "{} ", ColonToken::AS_STR)?; traits.format(formatted_code, formatter)?; } // `where` if let Some(where_clause) = &self.where_clause_opt { writeln!(formatted_code)?; where_clause.format(formatted_code, formatter)?; } else { write!(formatted_code, " ")?; } Self::open_curly_brace(formatted_code, formatter)?; let trait_items = self.trait_items.get(); if trait_items.is_empty() { write_comments(formatted_code, self.trait_items.span().into(), formatter)?; } else { for item in trait_items.iter() { item.format(formatted_code, formatter)?; write!(formatted_code, "{NEW_LINE}")?; } } Self::close_curly_brace(formatted_code, formatter)?; if let Some(trait_defs) = &self.trait_defs_opt { write!(formatted_code, " ")?; Self::open_curly_brace(formatted_code, formatter)?; for trait_items in trait_defs.get().iter() { // format `Annotated<ItemFn>` trait_items.format(formatted_code, formatter)?; write!(formatted_code, "{NEW_LINE}")?; } if trait_defs.get().is_empty() { write!(formatted_code, "{NEW_LINE}")?; } Self::close_curly_brace(formatted_code, formatter)?; }; rewrite_with_comments::<ItemTrait>( formatter, self.span(), self.leaf_spans(), formatted_code, start_len, )?; Ok(()) } } impl Format for ItemTraitItem { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match self { ItemTraitItem::Fn(fn_decl, _) => { fn_decl.format(formatted_code, formatter)?; write!(formatted_code, ";")?; } ItemTraitItem::Const(const_decl, _) => { const_decl.format(formatted_code, formatter)?; } ItemTraitItem::Type(type_decl, _) => { type_decl.format(formatted_code, formatter)?; } ItemTraitItem::Error(_, _) => { return Err(FormatterError::SyntaxError); } } Ok(()) } } impl CurlyBrace for ItemTrait { fn open_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.indent(); let open_brace = Delimiter::Brace.as_open_char(); writeln!(line, "{open_brace}")?; Ok(()) } fn close_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.unindent(); write!(line, "{}", Delimiter::Brace.as_close_char())?; Ok(()) } } impl Format for Traits { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // prefix `PathType` self.prefix.format(formatted_code, formatter)?; // additional `PathType`s // // ` + PathType` for (_add_token, path_type) in self.suffixes.iter() { write!(formatted_code, " {} ", AddToken::AS_STR)?; path_type.format(formatted_code, formatter)?; } Ok(()) } } impl LeafSpans for ItemTrait { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); } collected_spans.push(ByteSpan::from(self.trait_token.span())); collected_spans.push(ByteSpan::from(self.name.span())); if let Some(super_traits) = &self.super_traits { collected_spans.append(&mut super_traits.leaf_spans()); } collected_spans.append(&mut self.trait_items.leaf_spans()); if let Some(trait_defs) = &self.trait_defs_opt { collected_spans.append(&mut trait_defs.leaf_spans()); } collected_spans } } impl LeafSpans for ItemTraitItem { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); match &self { ItemTraitItem::Fn(fn_sig, semicolon) => { collected_spans.append(&mut fn_sig.leaf_spans()); collected_spans.extend(semicolon.as_ref().into_iter().flat_map(|x| x.leaf_spans())); } ItemTraitItem::Const(const_decl, semicolon) => { collected_spans.append(&mut const_decl.leaf_spans()); collected_spans.extend(semicolon.as_ref().into_iter().flat_map(|x| x.leaf_spans())); } ItemTraitItem::Error(spans, _) => { collected_spans.extend(spans.iter().cloned().map(Into::into)); } ItemTraitItem::Type(type_decl, _) => { collected_spans.append(&mut type_decl.leaf_spans()) } }; collected_spans } } impl LeafSpans for Traits { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = self.prefix.leaf_spans(); collected_spans.append(&mut self.suffixes.leaf_spans()); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_storage/tests.rs
swayfmt/src/items/item_storage/tests.rs
use forc_tracing::{println_green, println_red}; use paste::paste; use prettydiff::{basic::DiffOp, diff_lines}; use test_macros::fmt_test_item; fmt_test_item!( storage_maps "storage { map1: StorageMap<u64, bool> = StorageMap {}, map2: StorageMap<u64, u8> = StorageMap {}, map3: StorageMap<u64, u16> = StorageMap {}, map4: StorageMap<u64, u32> = StorageMap {}, map5: StorageMap<u64, u64> = StorageMap {}, map6: StorageMap<u64, (b256, u8, bool)> = StorageMap {}, map7: StorageMap<u64, Struct> = StorageMap {}, map8: StorageMap<u64, Enum> = StorageMap {}, map9: StorageMap<u64, str[33]> = StorageMap {}, map10: StorageMap<u64, [b256; 3]> = StorageMap {}, map11: StorageMap<bool, u64> = StorageMap {}, map12: StorageMap<u8, u64> = StorageMap {}, map13: StorageMap<u16, u64> = StorageMap {}, map14: StorageMap<u32, u64> = StorageMap {}, map15: StorageMap<(b256, u8, bool), u64> = StorageMap {}, map16: StorageMap<Struct, u64> = StorageMap {}, map17: StorageMap<Enum, u64> = StorageMap {}, map18: StorageMap<str[33], u64> = StorageMap {}, map19: StorageMap<[b256; 3], u64> = StorageMap {}, }", wrong_new_lines "storage { map1: StorageMap<u64, bool> = StorageMap { }, map2: StorageMap<u64, u8> = StorageMap { }, map3: StorageMap<u64, u16> = StorageMap { }, map4: StorageMap<u64, u32> = StorageMap { }, map5: StorageMap<u64, u64> = StorageMap { }, map6: StorageMap<u64, (b256, u8, bool) > = StorageMap { }, map7: StorageMap<u64, Struct> = StorageMap { }, map8: StorageMap<u64, Enum> = StorageMap { }, map9: StorageMap<u64, str[33]> = StorageMap { }, map10: StorageMap<u64, [b256; 3]> = StorageMap { }, map11: StorageMap<bool, u64> = StorageMap { }, map12: StorageMap<u8, u64> = StorageMap { }, map13: StorageMap<u16, u64> = StorageMap { }, map14: StorageMap<u32, u64> = StorageMap { }, map15: StorageMap<(b256, u8, bool), u64 > = StorageMap { }, map16: StorageMap<Struct, u64> = StorageMap { }, map17: StorageMap<Enum, u64> = StorageMap { }, map18: StorageMap<str[33], u64> = StorageMap { }, map19: StorageMap<[b256; 3], u64> = StorageMap { }, }" );
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_storage/mod.rs
swayfmt/src/items/item_storage/mod.rs
use crate::{ comments::rewrite_with_comments, config::user_def::FieldAlignment, formatter::{ shape::{ExprKind, LineStyle}, *, }, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::{collections::HashMap, fmt::Write}; use sway_ast::{ keywords::{ColonToken, EqToken, Keyword, StorageToken, Token}, CommaToken, ItemStorage, StorageEntry, StorageField, }; use sway_types::{ast::Delimiter, IdentUnique, Spanned}; #[cfg(test)] mod tests; impl Format for ItemStorage { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Multiline, ExprKind::default()), |formatter| -> Result<(), FormatterError> { // Required for comment formatting let start_len = formatted_code.len(); // Add storage token write!(formatted_code, "{}", StorageToken::AS_STR)?; let entries = self.entries.get(); // Handle opening brace Self::open_curly_brace(formatted_code, formatter)?; formatter.shape.code_line.update_expr_new_line(true); // Determine alignment tactic match formatter.config.structures.field_alignment { FieldAlignment::AlignFields(storage_field_align_threshold) => { writeln!(formatted_code)?; let value_pairs = &entries .value_separator_pairs .iter() // TODO: Handle annotations instead of stripping them. // See: https://github.com/FuelLabs/sway/issues/6802 .map(|(storage_field, comma_token)| (&storage_field.value, comma_token)) .collect::<Vec<_>>(); // In first iteration we are going to be collecting the lengths of the // struct fields. let mut field_lengths: HashMap<IdentUnique, usize> = HashMap::<IdentUnique, usize>::new(); fn collect_field_lengths( entry: &StorageEntry, ident_size: usize, current_ident: usize, field_lengths: &mut HashMap<IdentUnique, usize>, ) { if let Some(namespace) = &entry.namespace { namespace.clone().into_inner().into_iter().for_each(|e| { collect_field_lengths( &e.value, ident_size, current_ident + ident_size, field_lengths, ) }); } else if let Some(storage_field) = &entry.field { field_lengths.insert( storage_field.name.clone().into(), current_ident + storage_field.name.as_str().len(), ); } } let ident_size = formatter.config.whitespace.tab_spaces; value_pairs.iter().for_each(|(storage_entry, _)| { collect_field_lengths(storage_entry, ident_size, 0, &mut field_lengths) }); if let Some(final_value) = &entries.final_value_opt { collect_field_lengths( &final_value.value, ident_size, 0, &mut field_lengths, ); } // Find the maximum length in the `field_length` vector that is still // smaller than `storage_field_align_threshold`. `max_valid_field_length`: // the length of the field that we are taking as a reference to align. let mut max_valid_field_length = 0; field_lengths.iter().for_each(|(_, length)| { if *length > max_valid_field_length && *length < storage_field_align_threshold { max_valid_field_length = *length; } }); fn format_entry( formatted_code: &mut FormattedCode, formatter: &mut Formatter, entry: &StorageEntry, field_lengths: &HashMap<IdentUnique, usize>, max_valid_field_length: usize, ) -> Result<(), FormatterError> { write!(formatted_code, "{}", formatter.indent_to_str()?)?; if let Some(namespace) = &entry.namespace { entry.name.format(formatted_code, formatter)?; ItemStorage::open_curly_brace(formatted_code, formatter)?; writeln!(formatted_code)?; for (e, _comma_token) in namespace.clone().into_inner().value_separator_pairs { format_entry( formatted_code, formatter, &e.value, field_lengths, max_valid_field_length, )?; writeln!(formatted_code, "{}", CommaToken::AS_STR)?; } if let Some(final_value) = &namespace.clone().into_inner().final_value_opt { format_entry( formatted_code, formatter, &final_value.value, field_lengths, max_valid_field_length, )?; writeln!(formatted_code)?; } ItemStorage::close_curly_brace(formatted_code, formatter)?; } else if let Some(storage_field) = &entry.field { // Add name storage_field.name.format(formatted_code, formatter)?; // `current_field_length`: the length of the current field that we are // trying to format. let current_field_length = field_lengths .get(&storage_field.name.clone().into()) .unwrap(); if *current_field_length < max_valid_field_length { // We need to add alignment between `:` and `ty` let mut required_alignment = max_valid_field_length - current_field_length; while required_alignment != 0 { write!(formatted_code, " ")?; required_alignment -= 1; } } // Add `:`, `ty` & `CommaToken` write!(formatted_code, " {} ", ColonToken::AS_STR)?; storage_field.ty.format(formatted_code, formatter)?; write!(formatted_code, " {} ", EqToken::AS_STR)?; storage_field .initializer .format(formatted_code, formatter)?; } Ok(()) } for (storage_entry, _comma_token) in value_pairs.iter().clone() { format_entry( formatted_code, formatter, storage_entry, &field_lengths, max_valid_field_length, )?; writeln!(formatted_code, "{}", CommaToken::AS_STR)?; } if let Some(final_value) = &entries.final_value_opt { format_entry( formatted_code, formatter, &final_value.value, &field_lengths, max_valid_field_length, )?; writeln!(formatted_code)?; } } FieldAlignment::Off => entries.format(formatted_code, formatter)?, } // Handle closing brace Self::close_curly_brace(formatted_code, formatter)?; rewrite_with_comments::<ItemStorage>( formatter, self.span(), self.leaf_spans(), formatted_code, start_len, )?; Ok(()) }, )?; Ok(()) } } impl CurlyBrace for ItemStorage { fn open_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.indent(); let open_brace = Delimiter::Brace.as_open_char(); // Add opening brace to the same line write!(line, " {open_brace}")?; Ok(()) } fn close_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // shrink_left would return error if the current indentation level is becoming < 0, in that // case we should use the Shape::default() which has 0 indentation level. formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; Ok(()) } } impl LeafSpans for ItemStorage { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.storage_token.span())]; collected_spans.append(&mut self.entries.leaf_spans()); collected_spans } } impl LeafSpans for StorageEntry { fn leaf_spans(&self) -> Vec<ByteSpan> { if let Some(namespace) = &self.namespace { let mut collected_spans = vec![ByteSpan::from(self.name.span())]; collected_spans.append(&mut namespace.leaf_spans()); collected_spans } else if let Some(field) = &self.field { field.leaf_spans() } else { vec![] } } } impl LeafSpans for StorageField { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.name.span())]; if let Some(in_token) = &self.in_token { collected_spans.push(ByteSpan::from(in_token.span())); } if let Some(key_expr) = &self.key_expr { collected_spans.push(ByteSpan::from(key_expr.span())); } collected_spans.push(ByteSpan::from(self.colon_token.span())); collected_spans.append(&mut self.ty.leaf_spans()); collected_spans.push(ByteSpan::from(self.eq_token.span())); collected_spans.append(&mut self.initializer.leaf_spans()); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_configurable/tests.rs
swayfmt/src/items/item_configurable/tests.rs
use forc_tracing::{println_green, println_red}; use paste::paste; use prettydiff::{basic::DiffOp, diff_lines}; use test_macros::fmt_test_item; fmt_test_item!( configurables "configurable { C0: bool = true, C1: u64 = 42, C2: b256 = 0x1111111111111111111111111111111111111111111111111111111111111111, C3: MyStruct = MyStruct { x: 42, y: true }, C4: MyEnum = MyEnum::A(42), C5: MyEnum = MyEnum::B(true), C6: str[4] = \"fuel\", C7: [u64; 4] = [1, 2, 3, 4], C8: u64 = 0, }", wrong_new_lines "configurable { C0: bool = true, C1: u64 = 42, C2: b256 = 0x1111111111111111111111111111111111111111111111111111111111111111, C3: MyStruct = MyStruct { x: 42, y: true }, C4: MyEnum = MyEnum::A(42), C5: MyEnum = MyEnum::B(true), C6: str[4] = \"fuel\", C7: [u64; 4] = [1, 2, 3, 4], C8: u64 = 0, }" );
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_configurable/mod.rs
swayfmt/src/items/item_configurable/mod.rs
use crate::{ config::user_def::FieldAlignment, formatter::{ shape::{ExprKind, LineStyle}, *, }, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::fmt::Write; use sway_ast::{ keywords::{ColonToken, ConfigurableToken, EqToken, Keyword, Token}, CommaToken, ConfigurableField, ItemConfigurable, }; use sway_types::{ast::Delimiter, Spanned}; #[cfg(test)] mod tests; impl Format for ItemConfigurable { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Multiline, ExprKind::default()), |formatter| -> Result<(), FormatterError> { // Add configurable token write!(formatted_code, "{}", ConfigurableToken::AS_STR)?; let fields = self.fields.get(); // Handle opening brace Self::open_curly_brace(formatted_code, formatter)?; formatter.shape.code_line.update_expr_new_line(true); // Determine alignment tactic match formatter.config.structures.field_alignment { FieldAlignment::AlignFields(configurable_field_align_threshold) => { writeln!(formatted_code)?; let configurable_fields = &fields .value_separator_pairs .iter() // TODO: Handle annotations instead of stripping them. // See: https://github.com/FuelLabs/sway/issues/6802 .map(|(configurable_field, _comma_token)| &configurable_field.value) .collect::<Vec<_>>(); // In first iteration we are going to be collecting the lengths of the // struct fields. let field_length: Vec<usize> = configurable_fields .iter() .map(|configurable_field| configurable_field.name.as_str().len()) .collect(); // Find the maximum length in the `field_length` vector that is still // smaller than `configurable_field_align_threshold`. // `max_valid_field_length`: the length of the field that we are taking as // a reference to align. let mut max_valid_field_length = 0; field_length.iter().for_each(|length| { if *length > max_valid_field_length && *length < configurable_field_align_threshold { max_valid_field_length = *length; } }); for (field_index, configurable_field) in configurable_fields.iter().enumerate() { write!(formatted_code, "{}", formatter.indent_to_str()?)?; // Add name configurable_field.name.format(formatted_code, formatter)?; // `current_field_length`: the length of the current field that we are // trying to format. let current_field_length = field_length[field_index]; if current_field_length < max_valid_field_length { // We need to add alignment between `:` and `ty` let mut required_alignment = max_valid_field_length - current_field_length; while required_alignment != 0 { write!(formatted_code, " ")?; required_alignment -= 1; } } // Add `:`, `ty` & `CommaToken` write!(formatted_code, " {} ", ColonToken::AS_STR)?; configurable_field.ty.format(formatted_code, formatter)?; write!(formatted_code, " {} ", EqToken::AS_STR)?; configurable_field .initializer .format(formatted_code, formatter)?; writeln!(formatted_code, "{}", CommaToken::AS_STR)?; } if let Some(final_value) = &fields.final_value_opt { final_value.format(formatted_code, formatter)?; writeln!(formatted_code)?; } } FieldAlignment::Off => fields.format(formatted_code, formatter)?, } // Handle closing brace Self::close_curly_brace(formatted_code, formatter)?; Ok(()) }, )?; Ok(()) } } impl CurlyBrace for ItemConfigurable { fn open_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.indent(); let open_brace = Delimiter::Brace.as_open_char(); // Add opening brace to the same line write!(line, " {open_brace}")?; Ok(()) } fn close_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // shrink_left would return error if the current indentation level is becoming < 0, in that // case we should use the Shape::default() which has 0 indentation level. formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; Ok(()) } } impl LeafSpans for ItemConfigurable { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.configurable_token.span())]; collected_spans.append(&mut self.fields.leaf_spans()); collected_spans } } impl LeafSpans for ConfigurableField { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.name.span())]; collected_spans.push(ByteSpan::from(self.colon_token.span())); collected_spans.append(&mut self.ty.leaf_spans()); collected_spans.push(ByteSpan::from(self.eq_token.span())); collected_spans.append(&mut self.initializer.leaf_spans()); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_fn/tests.rs
swayfmt/src/items/item_fn/tests.rs
use forc_tracing::{println_green, println_red}; use paste::paste; use prettydiff::{basic::DiffOp, diff_lines}; use test_macros::fmt_test_item; fmt_test_item!( long_fn_name "pub fn hello_this_is_a_really_long_fn_name_wow_so_long_ridiculous(\n self,\n foo: Foo,\n bar: Bar,\n baz: Baz,\n) {}", intermediate_whitespace "pub fn hello_this_is_a_really_long_fn_name_wow_so_long_ridiculous ( self , foo : Foo , bar : Bar , baz: Baz) {\n }" ); fmt_test_item!( long_fn_args "fn foo(\n mut self,\n this_is_a_really_long_variable: Foo,\n hello_im_really_long: Bar,\n) -> String {}", intermediate_whitespace " fn foo( \n mut self , \n this_is_a_really_long_variable : Foo ,\n hello_im_really_long: Bar , \n ) -> String { \n } " ); fmt_test_item!( non_self_fn "fn test_function( helloitsverylong: String, whatisgoingonthisistoolong: String, yetanotherlongboy: String, ) -> bool { match foo { Foo::foo => true, _ => false, } }", intermediate_whitespace "fn test_function (\n\n helloitsverylong : String , whatisgoingonthisistoolong : String , yetanotherlongboy : String ,\n ) -> bool { match foo { Foo :: foo => true , _ => false , } }" ); fmt_test_item!( fn_with_nested_items "fn returns_msg_sender(expected_id: ContractId) -> bool { let result: Result<Identity, AuthError> = msg_sender(); let mut ret = false; if result.is_err() { ret = false; } let unwrapped = result.unwrap(); match unwrapped { Identity::ContractId(v) => { ret = true } _ => { ret = false } } ret }", intermediate_whitespace "fn returns_msg_sender(expected_id: ContractId) -> bool { let result: Result<Identity, AuthError> = msg_sender(); let mut ret = false; if result.is_err() { ret = false; } let unwrapped = result.unwrap(); match unwrapped { Identity::ContractId(v) => {ret = true} _ => {ret = false} } ret }" ); fmt_test_item!( fn_nested_if_lets "fn has_nested_if_let() { let result_1 = if let Result::Ok(x) = x { 100 } else { 1 }; let result_2 = if let Result::Err(x) = x { 3 } else { 43 }; }", intermediate_whitespace "fn has_nested_if_let() { let result_1 = if let Result::Ok(x) = x { 100 } else { 1 }; let result_2 = if let Result::Err(x) = x { 3 } else { 43 }; }" ); fmt_test_item!( fn_conditional_with_comment "fn conditional_with_comment() { if true { // comment here } }", intermediate_whitespace "fn conditional_with_comment() { if true { // comment here } }" ); fmt_test_item!( fn_conditional_with_comment_and_else "fn conditional_with_comment() { if true { // if } else { // else } }", intermediate_whitespace "fn conditional_with_comment() { if true { // if } else { // else } }" ); fmt_test_item!(fn_comments_special_chars "fn comments_special_chars() { // this ↓↓↓↓↓ let val = 1; // this is a normal comment }", intermediate_whitespace "fn comments_special_chars() { // this ↓↓↓↓↓ let val = 1; // this is a normal comment }" );
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_fn/mod.rs
swayfmt/src/items/item_fn/mod.rs
use crate::{ comments::{has_comments_in_formatter, rewrite_with_comments, write_comments}, formatter::{ shape::{ExprKind, LineStyle}, *, }, utils::{ map::byte_span::{ByteSpan, LeafSpans}, {CurlyBrace, Parenthesis}, }, }; use std::fmt::Write; use sway_ast::{ keywords::{ ColonToken, FnToken, Keyword, MutToken, RefToken, RightArrowToken, SelfToken, Token, }, CommaToken, FnArg, FnArgs, FnSignature, ItemFn, PubToken, }; use sway_types::{ast::Delimiter, Spanned}; #[cfg(test)] mod tests; impl Format for ItemFn { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Required for comment formatting let start_len = formatted_code.len(); formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Normal, ExprKind::Function), |formatter| -> Result<(), FormatterError> { self.fn_signature.format(formatted_code, formatter)?; let body = self.body.get(); if !body.statements.is_empty() || body.final_expr_opt.is_some() { Self::open_curly_brace(formatted_code, formatter)?; formatter.indent(); body.format(formatted_code, formatter)?; if let Some(final_expr_opt) = body.final_expr_opt.as_ref() { write_comments( formatted_code, final_expr_opt.span().end()..self.span().end(), formatter, )?; } Self::close_curly_brace(formatted_code, formatter)?; } else { let range = self.span().into(); Self::open_curly_brace(formatted_code, formatter)?; if has_comments_in_formatter(formatter, &range) { formatter.indent(); write_comments(formatted_code, range, formatter)?; } Self::close_curly_brace(formatted_code, formatter)?; } rewrite_with_comments::<ItemFn>( formatter, self.span(), self.leaf_spans(), formatted_code, start_len, )?; Ok(()) }, )?; Ok(()) } } impl CurlyBrace for ItemFn { fn open_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { let open_brace = Delimiter::Brace.as_open_char(); match formatter.shape.code_line.has_where_clause { true => { let indent_str = formatter.indent_to_str()?; write!(line, "{indent_str}{open_brace}")?; formatter.shape.code_line.update_where_clause(false); } false => { write!(line, " {open_brace}")?; } } Ok(()) } fn close_curly_brace( line: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // If shape is becoming left-most aligned or - indent just have the default shape formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; Ok(()) } } impl Format for FnSignature { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.shape.code_line.has_where_clause = formatter.with_shape( formatter .shape .with_code_line_from(LineStyle::Normal, ExprKind::Function), |formatter| -> Result<bool, FormatterError> { let mut fn_sig = FormattedCode::new(); let mut fn_args = FormattedCode::new(); let mut temp_formatter = Formatter::default(); format_fn_sig(self, &mut fn_sig, &mut temp_formatter)?; format_fn_args(self.arguments.get(), &mut fn_args, &mut temp_formatter)?; let fn_sig_width = fn_sig.chars().count() + 2; // add two for opening brace + space let fn_args_width = fn_args.chars().count(); formatter.shape.code_line.update_width(fn_sig_width); formatter .shape .get_line_style(None, Some(fn_args_width), &formatter.config); format_fn_sig(self, formatted_code, formatter)?; Ok(formatter.shape.code_line.has_where_clause) }, )?; Ok(()) } } fn format_fn_sig( fn_sig: &FnSignature, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // `pub ` if fn_sig.visibility.is_some() { write!(formatted_code, "{} ", PubToken::AS_STR)?; } // `fn ` + name write!(formatted_code, "{} ", FnToken::AS_STR)?; fn_sig.name.format(formatted_code, formatter)?; // `<T>` if let Some(generics) = &fn_sig.generics { generics.format(formatted_code, formatter)?; } // `(` FnSignature::open_parenthesis(formatted_code, formatter)?; // FnArgs format_fn_args(fn_sig.arguments.get(), formatted_code, formatter)?; // `)` FnSignature::close_parenthesis(formatted_code, formatter)?; // `return_type_opt` if let Some((_right_arrow, ty)) = &fn_sig.return_type_opt { write!(formatted_code, " {} ", RightArrowToken::AS_STR)?; ty.format(formatted_code, formatter)?; // `Ty` } // `WhereClause` if let Some(where_clause) = &fn_sig.where_clause_opt { writeln!(formatted_code)?; where_clause.format(formatted_code, formatter)?; formatter.shape.code_line.update_where_clause(true); } Ok(()) } fn format_fn_args( fn_args: &FnArgs, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { match fn_args { FnArgs::Static(args) => match formatter.shape.code_line.line_style { LineStyle::Multiline => { formatter.shape.code_line.update_expr_new_line(true); if !args.is_empty() { formatter.indent(); args.format(formatted_code, formatter)?; formatter.unindent(); write!(formatted_code, "{}", formatter.indent_to_str()?)?; } } _ => args.format(formatted_code, formatter)?, }, FnArgs::NonStatic { self_token, ref_self, mutable_self, args_opt, } => { match formatter.shape.code_line.line_style { LineStyle::Multiline => { formatter.shape.code_line.update_expr_new_line(true); formatter.indent(); write!(formatted_code, "\n{}", formatter.indent_to_str()?)?; format_self(self_token, ref_self, mutable_self, formatted_code)?; // `args_opt` if let Some((_comma, args)) = args_opt { // `, ` write!(formatted_code, "{}", CommaToken::AS_STR)?; // `Punctuated<FnArg, CommaToken>` args.format(formatted_code, formatter)?; } } _ => { format_self(self_token, ref_self, mutable_self, formatted_code)?; // `args_opt` if let Some((_comma, args)) = args_opt { // `, ` write!(formatted_code, "{} ", CommaToken::AS_STR)?; // `Punctuated<FnArg, CommaToken>` args.format(formatted_code, formatter)?; } } } } } Ok(()) } fn format_self( _self_token: &SelfToken, ref_self: &Option<RefToken>, mutable_self: &Option<MutToken>, formatted_code: &mut FormattedCode, ) -> Result<(), FormatterError> { // `ref ` if ref_self.is_some() { write!(formatted_code, "{} ", RefToken::AS_STR)?; } // `mut ` if mutable_self.is_some() { write!(formatted_code, "{} ", MutToken::AS_STR)?; } // `self` write!(formatted_code, "{}", SelfToken::AS_STR)?; Ok(()) } impl Parenthesis for FnSignature { fn open_parenthesis( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_open_char())?; Ok(()) } fn close_parenthesis( line: &mut FormattedCode, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { write!(line, "{}", Delimiter::Parenthesis.as_close_char())?; Ok(()) } } impl Format for FnArg { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { self.pattern.format(formatted_code, formatter)?; // `: ` write!(formatted_code, "{} ", ColonToken::AS_STR)?; write_comments( formatted_code, self.colon_token.span().end()..self.ty.span().start(), formatter, )?; // `Ty` self.ty.format(formatted_code, formatter)?; Ok(()) } } impl LeafSpans for ItemFn { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.fn_signature.leaf_spans()); collected_spans.append(&mut self.body.leaf_spans()); collected_spans } } impl LeafSpans for FnSignature { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); } collected_spans.push(ByteSpan::from(self.fn_token.span())); collected_spans.push(ByteSpan::from(self.name.span())); if let Some(generics) = &self.generics { collected_spans.push(ByteSpan::from(generics.parameters.span())); } collected_spans.append(&mut self.arguments.leaf_spans()); if let Some(return_type) = &self.return_type_opt { collected_spans.append(&mut return_type.leaf_spans()); } if let Some(where_clause) = &self.where_clause_opt { collected_spans.append(&mut where_clause.leaf_spans()); } collected_spans } } impl LeafSpans for FnArgs { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); match &self { FnArgs::Static(arg_static) => { collected_spans.append(&mut arg_static.leaf_spans()); } FnArgs::NonStatic { self_token, ref_self, mutable_self, args_opt, } => { collected_spans.push(ByteSpan::from(self_token.span())); if let Some(reference) = ref_self { collected_spans.push(ByteSpan::from(reference.span())); } if let Some(mutable) = mutable_self { collected_spans.push(ByteSpan::from(mutable.span())); } if let Some(args) = args_opt { collected_spans.append(&mut args.leaf_spans()); } } }; collected_spans } } impl LeafSpans for FnArg { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.pattern.leaf_spans()); collected_spans.push(ByteSpan::from(self.colon_token.span())); collected_spans.push(ByteSpan::from(self.ty.span())); collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_abi/tests.rs
swayfmt/src/items/item_abi/tests.rs
use forc_tracing::{println_green, println_red}; use paste::paste; use prettydiff::{basic::DiffOp, diff_lines}; use test_macros::fmt_test_item; fmt_test_item!(abi_contains_constant "abi A { const ID: u32; }", intermediate_whitespace "abi A { const ID: u32; }"); fmt_test_item!(abi_contains_functions "abi A { fn hi() -> bool; fn hi2(hello: bool); fn hi3(hello: bool) -> u64; }", intermediate_whitespace "abi A { fn hi() -> bool; fn hi2(hello: bool); fn hi3(hello: bool)-> u64; }"); fmt_test_item!(abi_contains_comments "abi A { fn hi() -> bool; /// Function 2 fn hi2(hello: bool); fn hi3(hello: bool) -> u64; // here too }", intermediate_whitespace "abi A { fn hi() -> bool; /// Function 2 fn hi2(hello: bool); fn hi3(hello: bool)-> u64;// here too }"); fmt_test_item!(abi_multiline_method "abi MyContract { fn complex_function( arg1: MyStruct<[b256; 3], u8>, arg2: [MyStruct<u64, bool>; 4], arg3: (str[5], bool), arg4: MyOtherStruct, ) -> str[6]; }", intermediate_whitespace "abi MyContract { fn complex_function( arg1: MyStruct<[b256; 3], u8> , arg2: [MyStruct <u64, bool>; 4], arg3: ( str[5], bool ), arg4: MyOtherStruct) -> str[6] ; }");
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/items/item_abi/mod.rs
swayfmt/src/items/item_abi/mod.rs
use crate::{ comments::{rewrite_with_comments, write_comments}, constants::NEW_LINE, formatter::*, utils::{ map::byte_span::{ByteSpan, LeafSpans}, CurlyBrace, }, }; use std::fmt::Write; use sway_ast::{ keywords::{AbiToken, ColonToken, Keyword, Token}, ItemAbi, }; use sway_types::{ast::Delimiter, Spanned}; #[cfg(test)] mod tests; impl Format for ItemAbi { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { let start_len = formatted_code.len(); // `abi name` write!(formatted_code, "{} ", AbiToken::AS_STR)?; self.name.format(formatted_code, formatter)?; // ` : super_trait + super_trait` if let Some((_colon_token, traits)) = &self.super_traits { write!(formatted_code, " {} ", ColonToken::AS_STR)?; traits.format(formatted_code, formatter)?; } Self::open_curly_brace(formatted_code, formatter)?; let abi_items = self.abi_items.get(); // abi_items for trait_item in abi_items.iter() { trait_item.format(formatted_code, formatter)?; write!(formatted_code, "{NEW_LINE}")?; } if abi_items.is_empty() { write_comments( formatted_code, self.abi_items.span().start()..self.abi_items.span().end(), formatter, )?; } Self::close_curly_brace(formatted_code, formatter)?; // abi_defs_opt if let Some(abi_defs) = self.abi_defs_opt.clone() { Self::open_curly_brace(formatted_code, formatter)?; for item in abi_defs.get().iter() { item.format(formatted_code, formatter)?; write!(formatted_code, "{NEW_LINE}")?; } if abi_defs.get().is_empty() { write!(formatted_code, "{NEW_LINE}")?; } Self::close_curly_brace(formatted_code, formatter)?; } rewrite_with_comments::<ItemAbi>( formatter, self.span(), self.leaf_spans(), formatted_code, start_len, )?; Ok(()) } } impl CurlyBrace for ItemAbi { fn open_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { formatter.indent(); let open_brace = Delimiter::Brace.as_open_char(); // Add opening brace to the same line writeln!(line, " {open_brace}")?; Ok(()) } fn close_curly_brace( line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { // If shape is becoming left-most aligned or - indent just have the default shape formatter.unindent(); write!( line, "{}{}", formatter.indent_to_str()?, Delimiter::Brace.as_close_char() )?; Ok(()) } } impl LeafSpans for ItemAbi { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut collected_spans = vec![ByteSpan::from(self.abi_token.span())]; collected_spans.push(ByteSpan::from(self.name.span())); collected_spans.append(&mut self.abi_items.leaf_spans()); if let Some(abi_defs) = &self.abi_defs_opt { collected_spans.append(&mut abi_defs.leaf_spans()); } collected_spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/imports.rs
swayfmt/src/config/imports.rs
//! Configuration options related to formatting imports. use crate::config::{user_opts::ImportsOptions, whitespace::IndentStyle}; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone, Default)] pub struct Imports { /// Controls the strategy for how imports are grouped together. pub group_imports: GroupImports, /// Merge or split imports to the provided granularity. pub imports_granularity: ImportGranularity, /// Indent of imports. pub imports_indent: IndentStyle, } impl Imports { pub fn from_opts(opts: &ImportsOptions) -> Self { let default = Self::default(); Self { group_imports: opts.group_imports.unwrap_or(default.group_imports), imports_granularity: opts .imports_granularity .unwrap_or(default.imports_granularity), imports_indent: opts.imports_indent.unwrap_or(default.imports_indent), } } } /// Configuration for import groups, i.e. sets of imports separated by newlines. #[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)] pub enum GroupImports { /// Keep groups as they are. #[default] Preserve, /// Discard existing groups, and create new groups for /// 1. `std` / `core` / `alloc` imports /// 2. other imports /// 3. `self` / `crate` / `super` imports StdExternalCrate, /// Discard existing groups, and create a single group for everything One, } /// How to merge imports. #[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)] pub enum ImportGranularity { /// Do not merge imports. #[default] Preserve, /// Use one `use` statement per crate. Crate, /// Use one `use` statement per module. Module, /// Use one `use` statement per imported item. Item, /// Use one `use` statement including all items. One, }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/expr.rs
swayfmt/src/config/expr.rs
//! Configuration options related to formatting of expressions and punctuation. use crate::config::{items::ItemsLayout, user_opts::ExpressionsOptions}; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone)] pub struct Expressions { // PUNCTUATION /// Brace style for control flow constructs. pub expr_brace_style: ExprBraceStyle, /// Add trailing semicolon after break, continue and return. pub trailing_semicolon: bool, /// Leave a space before the colon. pub space_before_colon: bool, /// Leave a space after the colon. pub space_after_colon: bool, // OPERATORS /// Determines if `+` or `=` are wrapped in spaces in the punctuation of types. pub type_combinator_layout: TypeCombinatorLayout, /// Put spaces around the `..` and `..=` range operators. pub spaces_around_ranges: bool, // MATCH EXPR /// Put a trailing comma after a block based match arm (non-block arms are not affected). pub match_block_trailing_comma: bool, /// Determines whether leading pipes are emitted on match arms. pub match_arm_leading_pipe: MatchArmLeadingPipe, // FUNCTIONS /// Force multiline closure bodies and match arms to be wrapped in a block. pub force_multiline_blocks: bool, /// Control the layout of arguments in a function. pub fn_args_layout: ItemsLayout, /// Put single-expression functions on a single line. pub fn_single_line: bool, } impl Default for Expressions { fn default() -> Self { Self { expr_brace_style: Default::default(), trailing_semicolon: true, space_before_colon: false, space_after_colon: false, type_combinator_layout: Default::default(), spaces_around_ranges: false, match_block_trailing_comma: false, match_arm_leading_pipe: Default::default(), force_multiline_blocks: false, fn_args_layout: Default::default(), fn_single_line: false, } } } impl Expressions { pub fn from_opts(opts: &ExpressionsOptions) -> Self { let default = Self::default(); Self { expr_brace_style: opts.expr_brace_style.unwrap_or(default.expr_brace_style), trailing_semicolon: opts .trailing_semicolon .unwrap_or(default.trailing_semicolon), space_before_colon: opts .space_before_colon .unwrap_or(default.space_before_colon), space_after_colon: opts.space_after_colon.unwrap_or(default.space_after_colon), type_combinator_layout: opts .type_combinator_layout .unwrap_or(default.type_combinator_layout), spaces_around_ranges: opts .spaces_around_ranges .unwrap_or(default.spaces_around_ranges), match_block_trailing_comma: opts .match_block_trailing_comma .unwrap_or(default.match_block_trailing_comma), match_arm_leading_pipe: opts .match_arm_leading_pipe .unwrap_or(default.match_arm_leading_pipe), force_multiline_blocks: opts .force_multiline_blocks .unwrap_or(default.force_multiline_blocks), fn_args_layout: opts.fn_args_layout.unwrap_or(default.fn_args_layout), fn_single_line: opts.fn_single_line.unwrap_or(default.fn_single_line), } } } /////PUNCTUATION///// /// Where to put the opening brace of conditional expressions (`if`, `match`, etc.). #[allow(clippy::enum_variant_names)] #[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)] pub enum ExprBraceStyle { /// K&R style, Rust community default #[default] AlwaysSameLine, /// Stroustrup style ClosingNextLine, /// Allman style AlwaysNextLine, } /// Spacing around type combinators. #[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)] pub enum TypeCombinatorLayout { /// No spaces around "=" and "+" Compressed, /// Spaces around " = " and " + " #[default] Wide, } /////MATCH EXPR///// /// Controls how swayfmt should handle leading pipes on match arms. #[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)] pub enum MatchArmLeadingPipe { /// Place leading pipes on all match arms Always, /// Never emit leading pipes on match arms #[default] Never, /// Preserve any existing leading pipes Preserve, }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/items.rs
swayfmt/src/config/items.rs
//! Configuration options related to item formatting. use crate::{ config::user_opts::ItemsOptions, constants::{DEFAULT_BLANK_LINES_LOWER_BOUND, DEFAULT_BLANK_LINES_UPPER_BOUND}, }; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone)] pub struct Items { /// Brace style for items. pub item_brace_style: ItemBraceStyle, /// Maximum number of blank lines which can be put between items. pub blank_lines_upper_bound: usize, /// Minimum number of blank lines which must be put between items. pub blank_lines_lower_bound: usize, /// Put empty-body functions and impls on a single line. pub empty_item_single_line: bool, } impl Default for Items { fn default() -> Self { Self { item_brace_style: Default::default(), blank_lines_upper_bound: DEFAULT_BLANK_LINES_UPPER_BOUND, blank_lines_lower_bound: DEFAULT_BLANK_LINES_LOWER_BOUND, empty_item_single_line: true, } } } impl Items { pub fn from_opts(opts: &ItemsOptions) -> Self { let default = Self::default(); Self { item_brace_style: opts.item_brace_style.unwrap_or(default.item_brace_style), blank_lines_upper_bound: opts .blank_lines_upper_bound .unwrap_or(default.blank_lines_upper_bound), blank_lines_lower_bound: opts .blank_lines_lower_bound .unwrap_or(default.blank_lines_lower_bound), empty_item_single_line: opts .empty_item_single_line .unwrap_or(default.empty_item_single_line), } } } /// Preference of how list-like items are displayed. /// /// Defaults to `Tall`. #[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)] pub enum ItemsLayout { /// Fit as much on one line as possible. Compressed, /// Items are placed horizontally if sufficient space, vertically otherwise. #[default] Tall, /// Place every item on a separate line. Vertical, } /// Where to put the opening brace of items (`fn`, `impl`, etc.). /// /// Defaults to `SameLineWhere`. #[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)] pub enum ItemBraceStyle { /// Put the opening brace on the next line. AlwaysNextLine, /// Put the opening brace on the same line, if possible. PreferSameLine, /// Prefer the same line except where there is a where-clause, in which /// case force the brace to be put on the next line. #[default] SameLineWhere, }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/comments.rs
swayfmt/src/config/comments.rs
//! Configuration options related to formatting comments. use crate::{config::user_opts::CommentsOptions, constants::DEFAULT_MAX_COMMENT_WIDTH}; #[derive(Debug, Clone)] pub struct Comments { /// Break comments to fit on the line. pub wrap_comments: bool, /// Maximum length of comments. No effect unless wrap_comments = true. pub comment_width: usize, /// Convert /* */ comments to // comments where possible pub normalize_comments: bool, } impl Default for Comments { fn default() -> Self { Self { wrap_comments: false, comment_width: DEFAULT_MAX_COMMENT_WIDTH, normalize_comments: false, } } } impl Comments { pub fn from_opts(opts: &CommentsOptions) -> Self { let default = Self::default(); Self { wrap_comments: opts.wrap_comments.unwrap_or(default.wrap_comments), comment_width: opts.comment_width.unwrap_or(default.comment_width), normalize_comments: opts .normalize_comments .unwrap_or(default.normalize_comments), } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/ordering.rs
swayfmt/src/config/ordering.rs
//! Configuration options related to re-ordering imports, modules and items. use crate::config::user_opts::OrderingOptions; #[derive(Debug, Clone)] pub struct Ordering { /// Reorder import and extern crate statements alphabetically. pub reorder_imports: bool, /// Reorder module statements alphabetically in group. pub reorder_modules: bool, /// Reorder `impl` items. pub reorder_impl_items: bool, } impl Default for Ordering { fn default() -> Self { Self { reorder_imports: true, reorder_modules: true, reorder_impl_items: false, } } } impl Ordering { pub fn from_opts(opts: &OrderingOptions) -> Self { let default = Self::default(); Self { reorder_imports: opts.reorder_imports.unwrap_or(default.reorder_imports), reorder_modules: opts.reorder_modules.unwrap_or(default.reorder_modules), reorder_impl_items: opts .reorder_impl_items .unwrap_or(default.reorder_impl_items), } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/user_opts.rs
swayfmt/src/config/user_opts.rs
//! All of the user-facing configuration options stored in [ConfigOptions]. use crate::config::{ expr::{ExprBraceStyle, MatchArmLeadingPipe, TypeCombinatorLayout}, heuristics::HeuristicsPreferences, imports::{GroupImports, ImportGranularity}, items::{ItemBraceStyle, ItemsLayout}, literals::HexLiteralCase, user_def::FieldAlignment, whitespace::{IndentStyle, NewlineStyle}, }; use serde::{Deserialize, Serialize}; /// See parent struct [Whitespace]. #[derive(Serialize, Deserialize, Debug, Copy, Clone)] pub struct WhitespaceOptions { pub max_width: Option<usize>, pub hard_tabs: Option<bool>, pub tab_spaces: Option<usize>, pub newline_style: Option<NewlineStyle>, pub indent_style: Option<IndentStyle>, pub newline_threshold: Option<usize>, } /// See parent struct [Imports]. #[derive(Serialize, Deserialize, Debug, Copy, Clone)] pub struct ImportsOptions { pub group_imports: Option<GroupImports>, pub imports_granularity: Option<ImportGranularity>, pub imports_indent: Option<IndentStyle>, } /// See parent struct [Ordering]. #[derive(Serialize, Deserialize, Debug, Copy, Clone)] pub struct OrderingOptions { pub reorder_imports: Option<bool>, pub reorder_modules: Option<bool>, pub reorder_impl_items: Option<bool>, } /// See parent struct [Items]. #[derive(Serialize, Deserialize, Debug, Copy, Clone)] pub struct ItemsOptions { pub item_brace_style: Option<ItemBraceStyle>, pub blank_lines_upper_bound: Option<usize>, pub blank_lines_lower_bound: Option<usize>, pub empty_item_single_line: Option<bool>, } /// See parent struct [Literals]. #[derive(Serialize, Deserialize, Debug, Copy, Clone)] pub struct LiteralsOptions { pub format_strings: Option<bool>, pub hex_literal_case: Option<HexLiteralCase>, } /// See parent struct [Expressions]. #[derive(Serialize, Deserialize, Debug, Copy, Clone)] pub struct ExpressionsOptions { pub expr_brace_style: Option<ExprBraceStyle>, pub trailing_semicolon: Option<bool>, pub space_before_colon: Option<bool>, pub space_after_colon: Option<bool>, pub type_combinator_layout: Option<TypeCombinatorLayout>, pub spaces_around_ranges: Option<bool>, pub match_block_trailing_comma: Option<bool>, pub match_arm_leading_pipe: Option<MatchArmLeadingPipe>, pub force_multiline_blocks: Option<bool>, pub fn_args_layout: Option<ItemsLayout>, pub fn_single_line: Option<bool>, } /// See parent struct [Heuristics]. #[derive(Serialize, Deserialize, Debug, Copy, Clone)] pub struct HeuristicsOptions { pub heuristics_pref: Option<HeuristicsPreferences>, pub use_small_heuristics: Option<bool>, } /// See parent struct [Structures]. #[derive(Serialize, Deserialize, Debug, Copy, Clone)] pub struct StructuresOptions { pub field_alignment: Option<FieldAlignment>, pub struct_lit_single_line: Option<bool>, } /// See parent struct [Comments]. #[derive(Serialize, Deserialize, Debug, Copy, Clone)] pub struct CommentsOptions { pub wrap_comments: Option<bool>, pub comment_width: Option<usize>, pub normalize_comments: Option<bool>, }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/manifest.rs
swayfmt/src/config/manifest.rs
pub use crate::error::FormatterError; use crate::{ config::{ comments::Comments, expr::Expressions, heuristics::Heuristics, imports::Imports, items::Items, literals::Literals, ordering::Ordering, user_def::Structures, user_opts::*, whitespace::Whitespace, }, constants::SWAY_FORMAT_FILE_NAME, error::ConfigError, }; use forc_tracing::println_yellow_err; use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; use sway_utils::find_parent_dir_with_file; /// A finalized `swayfmt` config. #[derive(Debug, Default, Clone)] pub struct Config { pub whitespace: Whitespace, pub imports: Imports, pub ordering: Ordering, pub items: Items, pub literals: Literals, pub expressions: Expressions, pub heuristics: Heuristics, pub structures: Structures, pub comments: Comments, } /// A direct mapping to an optional `swayfmt.toml`. #[derive(Serialize, Deserialize, Debug, Copy, Clone)] #[serde(rename_all = "snake_case")] pub struct ConfigOptions { pub whitespace: Option<WhitespaceOptions>, pub imports: Option<ImportsOptions>, pub ordering: Option<OrderingOptions>, pub items: Option<ItemsOptions>, pub literals: Option<LiteralsOptions>, pub expressions: Option<ExpressionsOptions>, pub heuristics: Option<HeuristicsOptions>, pub structures: Option<StructuresOptions>, pub comments: Option<CommentsOptions>, } impl Config { /// Construct the set of configuration to be used from the given set of options. /// pub fn from_opts(opts: ConfigOptions) -> Self { Self { whitespace: opts .whitespace .as_ref() .map(Whitespace::from_opts) .unwrap_or_default(), imports: opts .imports .as_ref() .map(Imports::from_opts) .unwrap_or_default(), ordering: opts .ordering .as_ref() .map(Ordering::from_opts) .unwrap_or_default(), items: opts .items .as_ref() .map(Items::from_opts) .unwrap_or_default(), literals: opts .literals .as_ref() .map(Literals::from_opts) .unwrap_or_default(), expressions: opts .expressions .as_ref() .map(Expressions::from_opts) .unwrap_or_default(), heuristics: opts .heuristics .as_ref() .map(Heuristics::from_opts) .unwrap_or_default(), structures: opts .structures .as_ref() .map(Structures::from_opts) .unwrap_or_default(), comments: opts .comments .as_ref() .map(Comments::from_opts) .unwrap_or_default(), } } /// Given a directory to a forc project containing a `swayfmt.toml`, read and /// construct a `Config` from the project's `swayfmt.toml` configuration file. /// /// This is a combination of `ConfigOptions::from_dir` and `Config::from_opts`, /// and takes care of constructing a finalized config. pub fn from_dir(config_path: &Path) -> Result<Self, ConfigError> { let config_opts = ConfigOptions::from_dir(config_path)?; Ok(Self::from_opts(config_opts)) } } impl ConfigOptions { /// Given a path to a `swayfmt.toml`, read and construct the `ConfigOptions`. pub fn from_file(config_path: PathBuf) -> Result<Self, ConfigError> { let config_str = std::fs::read_to_string(&config_path).map_err(|e| ConfigError::ReadConfig { path: config_path, err: e, })?; let toml_de = toml::de::Deserializer::new(&config_str); let config_opts: Self = serde_ignored::deserialize(toml_de, |field| { let warning = format!(" WARNING! found unusable configuration: {field}"); println_yellow_err(&warning); }) .map_err(|e| ConfigError::Deserialize { err: (e) })?; Ok(config_opts) } /// Given a directory to a forc project containing a `swayfmt.toml`, read the config. /// /// This is short for `ConfigOptions::from_file`, but takes care of constructing the path to the /// file. pub fn from_dir(dir: &Path) -> Result<Self, ConfigError> { let config_dir = find_parent_dir_with_file(dir, SWAY_FORMAT_FILE_NAME).ok_or(ConfigError::NotFound)?; let file_path = config_dir.join(SWAY_FORMAT_FILE_NAME); Self::from_file(file_path) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/user_def.rs
swayfmt/src/config/user_def.rs
//! Configuration options related to formatting user-defined structures. use crate::config::user_opts::StructuresOptions; use serde::{Deserialize, Serialize}; /// Styling preferences for user-defined structures like `struct`s or `enum`s. #[derive(Debug, Clone)] pub struct Structures { /// Align fields of user-defined structures if their diffs fit within threshold. pub field_alignment: FieldAlignment, /// Put small user-defined structure literals on a single line. pub small_structures_single_line: bool, } impl Default for Structures { fn default() -> Self { Self { field_alignment: Default::default(), small_structures_single_line: true, } } } impl Structures { pub fn from_opts(opts: &StructuresOptions) -> Self { let default = Self::default(); Self { field_alignment: opts.field_alignment.unwrap_or(default.field_alignment), small_structures_single_line: opts .struct_lit_single_line .unwrap_or(default.small_structures_single_line), } } } /// Align fields if they fit within a provided threshold. #[derive(Debug, Copy, Clone, Serialize, Deserialize, Default)] pub enum FieldAlignment { AlignFields(usize), #[default] Off, }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/heuristics.rs
swayfmt/src/config/heuristics.rs
//! Configuration options related to heuristics. use crate::{ config::user_opts::HeuristicsOptions, constants::{ DEFAULT_ATTR_FN_LIKE_WIDTH, DEFAULT_CHAIN_WIDTH, DEFAULT_COLLECTION_WIDTH, DEFAULT_FN_CALL_WIDTH, DEFAULT_MAX_LINE_WIDTH, DEFAULT_SHORT_ARRAY_ELEM_WIDTH_THRESHOLD, DEFAULT_SINGLE_LINE_IF_ELSE_WIDTH, DEFAULT_STRUCTURE_LIT_WIDTH, DEFAULT_STRUCTURE_VAR_WIDTH, }, }; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone)] pub struct Heuristics { /// Determines heuristics level of involvement. pub heuristics_pref: HeuristicsPreferences, /// Whether to use different formatting for items and expressions if they satisfy a heuristic notion of 'small' pub use_small_heuristics: bool, } impl Default for Heuristics { fn default() -> Self { Self { heuristics_pref: Default::default(), use_small_heuristics: true, } } } impl Heuristics { pub fn from_opts(opts: &HeuristicsOptions) -> Self { let default = Self::default(); Self { heuristics_pref: opts.heuristics_pref.unwrap_or(default.heuristics_pref), use_small_heuristics: opts .use_small_heuristics .unwrap_or(default.use_small_heuristics), } } } /// Heuristic settings that can be used to simplify /// the configuration of the granular width configurations /// like `struct_lit_width`, `array_width`, etc. #[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)] pub enum HeuristicsPreferences { /// Turn off any heuristics Off, /// Turn on max heuristics Max, /// Use scaled values based on the value of `max_width` #[default] Scaled, } impl HeuristicsPreferences { pub fn to_width_heuristics(self, max_width: usize) -> WidthHeuristics { match self { HeuristicsPreferences::Off => WidthHeuristics::off(), HeuristicsPreferences::Max => WidthHeuristics::max(max_width), HeuristicsPreferences::Scaled => WidthHeuristics::scaled(max_width), } } } /// 'small' heuristic values #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)] pub struct WidthHeuristics { // Maximum width of the args of a function call before falling back // to vertical formatting. pub(crate) fn_call_width: usize, // Maximum width of the args of a function-like attributes before falling // back to vertical formatting. pub(crate) attr_fn_like_width: usize, // Maximum width in the body of a user-defined structure literal before falling back to // vertical formatting. pub(crate) structure_lit_width: usize, // Maximum width of a user-defined structure field before falling back // to vertical formatting. pub(crate) structure_field_width: usize, // Maximum width of a collection literal before falling back to vertical // formatting. pub(crate) collection_width: usize, // Maximum length of a chain to fit on a single line. pub(crate) chain_width: usize, // Maximum line length for single line if-else expressions. A value // of zero means always break if-else expressions. pub(crate) single_line_if_else_max_width: usize, pub(crate) short_array_element_width: usize, } impl WidthHeuristics { /// Using this WidthHeuristics means we ignore heuristics. pub fn off() -> WidthHeuristics { WidthHeuristics { fn_call_width: usize::MAX, attr_fn_like_width: usize::MAX, structure_lit_width: 0, structure_field_width: 0, collection_width: usize::MAX, chain_width: usize::MAX, single_line_if_else_max_width: 0, short_array_element_width: 0, } } pub fn max(max_width: usize) -> WidthHeuristics { WidthHeuristics { fn_call_width: max_width, attr_fn_like_width: max_width, structure_lit_width: max_width, structure_field_width: max_width, collection_width: max_width, chain_width: max_width, single_line_if_else_max_width: max_width, short_array_element_width: max_width, } } // scale the default WidthHeuristics according to max_width pub fn scaled(max_width: usize) -> WidthHeuristics { let max_width_ratio = if max_width > DEFAULT_MAX_LINE_WIDTH { let ratio = max_width as f32 / DEFAULT_MAX_LINE_WIDTH as f32; // round to the closest 0.1 (ratio * 10.0).round() / 10.0 } else { 1.0 }; WidthHeuristics { fn_call_width: (DEFAULT_FN_CALL_WIDTH as f32 * max_width_ratio).round() as usize, attr_fn_like_width: (DEFAULT_ATTR_FN_LIKE_WIDTH as f32 * max_width_ratio).round() as usize, structure_lit_width: (DEFAULT_STRUCTURE_LIT_WIDTH as f32 * max_width_ratio).round() as usize, structure_field_width: (DEFAULT_STRUCTURE_VAR_WIDTH as f32 * max_width_ratio).round() as usize, collection_width: (DEFAULT_COLLECTION_WIDTH as f32 * max_width_ratio).round() as usize, chain_width: (DEFAULT_CHAIN_WIDTH as f32 * max_width_ratio).round() as usize, single_line_if_else_max_width: (DEFAULT_SINGLE_LINE_IF_ELSE_WIDTH as f32 * max_width_ratio) .round() as usize, short_array_element_width: (DEFAULT_SHORT_ARRAY_ELEM_WIDTH_THRESHOLD as f32 * max_width_ratio) .round() as usize, } } } impl Default for WidthHeuristics { fn default() -> Self { Self::scaled(100) } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/whitespace.rs
swayfmt/src/config/whitespace.rs
//! Standard system and editor whitespace configuration options. Advanced whitespace options will be deferred to their corresponding sub-classes. use crate::{ config::user_opts::WhitespaceOptions, constants::{ CARRIAGE_RETURN, DEFAULT_MAX_LINE_WIDTH, DEFAULT_NEWLINE_THRESHOLD, DEFAULT_TAB_SPACES, LINE_FEED, }, }; use serde::{Deserialize, Serialize}; /// Whitespace styling preferences. #[derive(Debug, Copy, Clone)] pub struct Whitespace { /// Maximum width of each line. pub max_width: usize, /// Use tab characters for indentation, spaces for alignment. pub hard_tabs: bool, /// Number of spaces per tab. pub tab_spaces: usize, /// Unix or Windows line endings. pub newline_style: NewlineStyle, /// How we indent expressions or items. pub indent_style: IndentStyle, /// Max number of newlines allowed between statements before collapsing them to threshold pub newline_threshold: usize, } impl Default for Whitespace { fn default() -> Self { Self { max_width: DEFAULT_MAX_LINE_WIDTH, hard_tabs: false, tab_spaces: DEFAULT_TAB_SPACES, newline_style: Default::default(), indent_style: Default::default(), newline_threshold: DEFAULT_NEWLINE_THRESHOLD, } } } impl Whitespace { pub fn from_opts(opts: &WhitespaceOptions) -> Self { let default = Self::default(); Self { max_width: opts.max_width.unwrap_or(default.max_width), hard_tabs: opts.hard_tabs.unwrap_or(default.hard_tabs), tab_spaces: opts.tab_spaces.unwrap_or(default.tab_spaces), newline_style: opts.newline_style.unwrap_or(default.newline_style), indent_style: opts.indent_style.unwrap_or(default.indent_style), newline_threshold: opts.newline_threshold.unwrap_or(default.newline_threshold), } } } /// Handling of line indentation for expressions or items. #[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)] pub enum IndentStyle { /// First line on the same line as the opening brace, all lines aligned with /// the first line. Visual, /// First line is on a new line and all lines align with **block** indent. #[default] Block, } /// Handling of which OS new-line style should be applied. #[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)] pub enum NewlineStyle { /// Auto-detect based on the raw source input. #[default] Auto, /// Force CRLF (`\r\n`). Windows, /// Force CR (`\n). Unix, /// `\r\n` in Windows, `\n` on other platforms. Native, } /// The definitive system type for `[NewlineStyle]`. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum NewlineSystemType { Windows, Unix, } impl NewlineSystemType { pub fn get_newline_style(newline_style: NewlineStyle, raw_input_text: &str) -> Self { match newline_style { NewlineStyle::Auto => Self::auto_detect_newline_style(raw_input_text), NewlineStyle::Native => Self::native_newline_style(), NewlineStyle::Windows => Self::Windows, NewlineStyle::Unix => Self::Unix, } } pub fn auto_detect_newline_style(raw_input_text: &str) -> Self { let first_line_feed_pos = raw_input_text.chars().position(|ch| ch == LINE_FEED); match first_line_feed_pos { Some(first_line_feed_pos) => { let char_before_line_feed_pos = first_line_feed_pos.saturating_sub(1); let char_before_line_feed = raw_input_text.chars().nth(char_before_line_feed_pos); match char_before_line_feed { Some(CARRIAGE_RETURN) => Self::Windows, _ => Self::Unix, } } None => Self::native_newline_style(), } } fn native_newline_style() -> Self { if cfg!(windows) { Self::Windows } else { Self::Unix } } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/mod.rs
swayfmt/src/config/mod.rs
pub mod comments; pub mod expr; pub mod heuristics; pub mod imports; pub mod items; pub mod literals; pub mod manifest; pub mod ordering; pub mod user_def; pub mod user_opts; pub mod whitespace;
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/config/literals.rs
swayfmt/src/config/literals.rs
//! Configuration options related to formatting literals. use crate::config::user_opts::LiteralsOptions; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone, Default)] pub struct Literals { /// Format string literals where necessary. pub format_strings: bool, /// Format hexadecimal integer literals. pub hex_literal_case: HexLiteralCase, } impl Literals { pub fn from_opts(opts: &LiteralsOptions) -> Self { let default = Self::default(); Self { format_strings: opts.format_strings.unwrap_or(default.format_strings), hex_literal_case: opts.hex_literal_case.unwrap_or(default.hex_literal_case), } } } /// Controls how swayfmt should handle case in hexadecimal literals. #[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)] pub enum HexLiteralCase { /// Leave the literal as-is #[default] Preserve, /// Ensure all literals use uppercase lettering Upper, /// Ensure all literals use lowercase lettering Lower, }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false
FuelLabs/sway
https://github.com/FuelLabs/sway/blob/cc8f867043f3ec2c14ec4088d449cde603929a80/swayfmt/src/module/submodule.rs
swayfmt/src/module/submodule.rs
use crate::{ formatter::*, utils::map::byte_span::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_ast::{ keywords::{Keyword, ModToken, SemicolonToken, Token}, submodule::Submodule, PubToken, }; use sway_types::Spanned; impl Format for Submodule { fn format( &self, formatted_code: &mut FormattedCode, formatter: &mut Formatter, ) -> Result<(), FormatterError> { if self.visibility.is_some() { write!(formatted_code, "{} ", PubToken::AS_STR)?; } write!(formatted_code, "{} ", ModToken::AS_STR)?; self.name.format(formatted_code, formatter)?; writeln!(formatted_code, "{}", SemicolonToken::AS_STR)?; Ok(()) } } impl LeafSpans for Submodule { fn leaf_spans(&self) -> Vec<ByteSpan> { let mut spans = Vec::with_capacity(4); if let Some(visibility) = &self.visibility { spans.push(ByteSpan::from(visibility.span())); } spans.extend_from_slice(&[ ByteSpan::from(self.mod_token.span()), ByteSpan::from(self.name.span()), ByteSpan::from(self.semicolon_token.span()), ]); spans } }
rust
Apache-2.0
cc8f867043f3ec2c14ec4088d449cde603929a80
2026-01-04T15:31:58.694488Z
false