From 48721ac2cf236d39ea31fa0a9cb46a4430e0d596 Mon Sep 17 00:00:00 2001 From: tx-tomcat Date: Sat, 1 Jun 2024 02:16:18 +0700 Subject: [PATCH] [move][move-linter] implement public mut context rules --- .../src/linters/constant_naming.rs | 4 +- .../crates/move-compiler/src/linters/mod.rs | 42 ++++--- .../src/linters/public_mut_tx_context.rs | 88 ++++++++++++++ .../src/linters/shift_overflow.rs | 109 ------------------ .../move-compiler/src/naming/translate.rs | 7 +- .../tests/custom_rules/shift_overflow.exp | 24 ---- .../tests/custom_rules/shift_overflow.move | 9 -- .../linter/correct_public_mut_tx_context.move | 10 ++ .../linter/incorrect_constant_naming.exp | 4 +- .../incorrect_public_mut_tx_context.exp | 8 ++ .../incorrect_public_mut_tx_context.move | 10 ++ .../tests/linter/suppressed_lints.move | 11 ++ 12 files changed, 163 insertions(+), 163 deletions(-) create mode 100644 external-crates/move/crates/move-compiler/src/linters/public_mut_tx_context.rs delete mode 100644 external-crates/move/crates/move-compiler/src/linters/shift_overflow.rs delete mode 100644 external-crates/move/crates/move-compiler/tests/custom_rules/shift_overflow.exp delete mode 100644 external-crates/move/crates/move-compiler/tests/custom_rules/shift_overflow.move create mode 100644 external-crates/move/crates/move-compiler/tests/linter/correct_public_mut_tx_context.move create mode 100644 external-crates/move/crates/move-compiler/tests/linter/incorrect_public_mut_tx_context.exp create mode 100644 external-crates/move/crates/move-compiler/tests/linter/incorrect_public_mut_tx_context.move diff --git a/external-crates/move/crates/move-compiler/src/linters/constant_naming.rs b/external-crates/move/crates/move-compiler/src/linters/constant_naming.rs index 99525fd2757602..7c8e3e6407e90f 100644 --- a/external-crates/move/crates/move-compiler/src/linters/constant_naming.rs +++ b/external-crates/move/crates/move-compiler/src/linters/constant_naming.rs @@ -19,13 +19,13 @@ use crate::{ }, }; -use super::{LinterDiagCategory, CONSTANT_NAMING_DIAG_CODE, LINT_WARNING_PREFIX}; +use super::{LinterDiagnosticCategory, CONSTANT_NAMING_DIAG_CODE, LINT_WARNING_PREFIX}; /// Diagnostic information for constant naming violations. const CONSTANT_NAMING_DIAG: DiagnosticInfo = custom( LINT_WARNING_PREFIX, Severity::Warning, - LinterDiagCategory::Style as u8, + LinterDiagnosticCategory::Style as u8, CONSTANT_NAMING_DIAG_CODE, "constant should follow naming convention", ); diff --git a/external-crates/move/crates/move-compiler/src/linters/mod.rs b/external-crates/move/crates/move-compiler/src/linters/mod.rs index 0baa1323936c1c..5973f2ec80ec4f 100644 --- a/external-crates/move/crates/move-compiler/src/linters/mod.rs +++ b/external-crates/move/crates/move-compiler/src/linters/mod.rs @@ -1,13 +1,16 @@ // Copyright (c) The Move Contributors // SPDX-License-Identifier: Apache-2.0 -use move_symbol_pool::Symbol; - use crate::{ command_line::compiler::Visitor, diagnostics::codes::WarningFilter, - linters::constant_naming::ConstantNamingVisitor, typing::visitor::TypingVisitor, + linters::constant_naming::ConstantNamingVisitor, + linters::public_mut_tx_context::RequireMutableTxContext, typing::visitor::TypingVisitor, }; +use move_symbol_pool::Symbol; + pub mod constant_naming; +pub mod public_mut_tx_context; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LintLevel { // No linters @@ -32,22 +35,28 @@ pub enum LinterDiagnosticCategory { pub const ALLOW_ATTR_CATEGORY: &str = "lint"; pub const LINT_WARNING_PREFIX: &str = "Lint "; pub const CONSTANT_NAMING_FILTER_NAME: &str = "constant_naming"; - pub const CONSTANT_NAMING_DIAG_CODE: u8 = 1; -pub enum LinterDiagCategory { - Style, -} +pub const REQUIRE_MUTABLE_TX_CONTEXT_FILTER_NAME: &str = "public_mut_tx_context"; +pub const REQUIRE_MUTABLE_TX_CONTEXT_DIAG_CODE: u8 = 14; pub fn known_filters() -> (Option, Vec) { ( Some(ALLOW_ATTR_CATEGORY.into()), - vec![WarningFilter::code( - Some(LINT_WARNING_PREFIX), - LinterDiagCategory::Style as u8, - CONSTANT_NAMING_DIAG_CODE, - Some(CONSTANT_NAMING_FILTER_NAME), - )], + vec![ + WarningFilter::code( + Some(LINT_WARNING_PREFIX), + LinterDiagnosticCategory::Style as u8, + CONSTANT_NAMING_DIAG_CODE, + Some(CONSTANT_NAMING_FILTER_NAME), + ), + WarningFilter::code( + Some(LINT_WARNING_PREFIX), + LinterDiagnosticCategory::Suspicious as u8, + REQUIRE_MUTABLE_TX_CONTEXT_DIAG_CODE, + Some(REQUIRE_MUTABLE_TX_CONTEXT_FILTER_NAME), + ), + ], ) } @@ -56,9 +65,10 @@ pub fn linter_visitors(level: LintLevel) -> Vec { LintLevel::None => vec![], LintLevel::Default => vec![], LintLevel::All => { - vec![constant_naming::ConstantNamingVisitor::visitor( - ConstantNamingVisitor, - )] + vec![ + constant_naming::ConstantNamingVisitor::visitor(ConstantNamingVisitor), + public_mut_tx_context::RequireMutableTxContext::visitor(RequireMutableTxContext), + ] } } } diff --git a/external-crates/move/crates/move-compiler/src/linters/public_mut_tx_context.rs b/external-crates/move/crates/move-compiler/src/linters/public_mut_tx_context.rs new file mode 100644 index 00000000000000..9abc22f7243e64 --- /dev/null +++ b/external-crates/move/crates/move-compiler/src/linters/public_mut_tx_context.rs @@ -0,0 +1,88 @@ +// Copyright (c) The Move Contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Enforces that public functions use `&mut TxContext` instead of `&TxContext` to ensure upgradability. +//! Detects and reports instances where a non-mutable reference to `TxContext` is used in public function signatures. +//! Promotes best practices for future-proofing smart contract code by allowing mutation of the transaction context. +use crate::{ + diag, + diagnostics::{ + codes::{custom, DiagnosticInfo, Severity}, + WarningFilters, + }, + expansion::ast::{ModuleIdent, Visibility}, + naming::ast::{TypeName_, Type_}, + parser::ast::{DatatypeName, FunctionName}, + shared::CompilationEnv, + typing::{ + ast as T, + visitor::{TypingVisitorConstructor, TypingVisitorContext}, + }, +}; +use move_ir_types::location::Loc; + +use super::{LinterDiagnosticCategory, LINT_WARNING_PREFIX, REQUIRE_MUTABLE_TX_CONTEXT_DIAG_CODE}; + +const REQUIRE_MUTABLE_TX_CONTEXT_DIAG: DiagnosticInfo = custom( + LINT_WARNING_PREFIX, + Severity::Warning, + LinterDiagnosticCategory::Suspicious as u8, + REQUIRE_MUTABLE_TX_CONTEXT_DIAG_CODE, + "", +); + +pub struct RequireMutableTxContext; + +pub struct Context<'a> { + env: &'a mut CompilationEnv, +} + +impl TypingVisitorConstructor for RequireMutableTxContext { + type Context<'a> = Context<'a>; + + fn context<'a>(env: &'a mut CompilationEnv, _program: &T::Program) -> Self::Context<'a> { + Context { env } + } +} + +impl TypingVisitorContext for Context<'_> { + fn visit_function_custom( + &mut self, + _module: ModuleIdent, + _function_name: FunctionName, + fdef: &mut T::Function, + ) -> bool { + if let Visibility::Public(_) = fdef.visibility { + for param in &fdef.signature.parameters { + if let Type_::Ref(false, var_type) = ¶m.2.value { + if let Type_::Apply(_, type_name, _) = &var_type.value { + if let TypeName_::ModuleType(_, DatatypeName(sp!(_, struct_name))) = + &type_name.value + { + if struct_name.to_string() == "TxContext" { + report_non_mutable_tx_context(self.env, type_name.loc); + } + } + } + } + } + } + + false + } + fn add_warning_filter_scope(&mut self, filter: WarningFilters) { + self.env.add_warning_filter_scope(filter) + } + + fn pop_warning_filter_scope(&mut self) { + self.env.pop_warning_filter_scope() + } +} + +fn report_non_mutable_tx_context(env: &mut CompilationEnv, loc: Loc) { + let diag = diag!( + REQUIRE_MUTABLE_TX_CONTEXT_DIAG, + (loc, "Public functions should take `&mut TxContext` instead of `&TxContext` for better upgradability.") + ); + env.add_diag(diag); +} diff --git a/external-crates/move/crates/move-compiler/src/linters/shift_overflow.rs b/external-crates/move/crates/move-compiler/src/linters/shift_overflow.rs deleted file mode 100644 index a66d97525fb8e1..00000000000000 --- a/external-crates/move/crates/move-compiler/src/linters/shift_overflow.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! Detect potential overflow scenarios where the number of bits being shifted exceeds the bit width of -//! the variable being shifted, which could lead to unintended behavior or loss of data. If such a -//! potential overflow is detected, a warning is generated to alert the developer. -use crate::{ - diag, - diagnostics::{ - codes::{custom, DiagnosticInfo, Severity}, - WarningFilters, - }, - expansion::ast::Value_, - naming::ast::{BuiltinTypeName_, TypeName_, Type_}, - parser::ast::BinOp_, - shared::{program_info::TypingProgramInfo, CompilationEnv}, - typing::{ - ast::{self as T, UnannotatedExp_}, - visitor::{TypingVisitorConstructor, TypingVisitorContext}, - }, -}; -use move_ir_types::location::Loc; -use std::str::FromStr; - -use super::{LinterDiagCategory, LINTER_DEFAULT_DIAG_CODE, LINT_WARNING_PREFIX}; - -const SHIFT_OPERATION_OVERFLOW_DIAG: DiagnosticInfo = custom( - LINT_WARNING_PREFIX, - Severity::Warning, - LinterDiagCategory::ShiftOperationOverflow as u8, - LINTER_DEFAULT_DIAG_CODE, - "Potential overflow detected. The number of bits being shifted exceeds the bit width of the variable being shifted.", -); - -pub struct ShiftOperationOverflow; - -pub struct Context<'a> { - env: &'a mut CompilationEnv, -} - -impl TypingVisitorConstructor for ShiftOperationOverflow { - type Context<'a> = Context<'a>; - - fn context<'a>( - env: &'a mut CompilationEnv, - _program_info: &'a TypingProgramInfo, - _program: &T::Program_, - ) -> Self::Context<'a> { - Context { env } - } -} - -impl TypingVisitorContext for Context<'_> { - fn visit_exp_custom(&mut self, exp: &mut T::Exp) -> bool { - // Check if the expression is a binary operation and if it is a shift operation. - if let UnannotatedExp_::BinopExp(lhs, op, _, rhs) = &exp.exp.value { - // can't do let UnannotatedExp_::BinopExp(lhs, BinOp_::Shl | BinOp_::Shr, _, rhs) = &exp.exp.value else { return }; - // because the op is Spanned and not BinOp_ - if matches!(op.value, BinOp_::Shl | BinOp_::Shr) { - match ( - get_bit_width(&lhs.ty.value), - get_shift_amount(&rhs.exp.value), - ) { - (Some(bit_width), Some(shift_amount)) if shift_amount >= bit_width => { - report_overflow(self.env, shift_amount, bit_width, op.loc); - } - _ => (), - } - } - } - false - } - fn add_warning_filter_scope(&mut self, filter: WarningFilters) { - self.env.add_warning_filter_scope(filter) - } - - fn pop_warning_filter_scope(&mut self) { - self.env.pop_warning_filter_scope() - } -} - -fn get_bit_width(ty: &Type_) -> Option { - ty.builtin_name().and_then(|typ| match typ.value { - BuiltinTypeName_::U8 => Some(8), - BuiltinTypeName_::U16 => Some(16), - BuiltinTypeName_::U32 => Some(32), - BuiltinTypeName_::U64 => Some(64), - BuiltinTypeName_::U128 => Some(128), - BuiltinTypeName_::U256 => Some(256), - _ => None, - }) -} - -fn get_shift_amount(value: &UnannotatedExp_) -> Option { - if let UnannotatedExp_::Value(v) = value { - match &v.value { - Value_::U8(v) => Some(*v as u128), - _ => None, - } - } else { - None - } -} - -fn report_overflow(env: &mut CompilationEnv, shift_amount: u128, bit_width: u128, loc: Loc) { - let msg = format!( - "The {} of bits being shifted exceeds the {} bit width of the variable being shifted.", - shift_amount, bit_width - ); - let diag = diag!(SHIFT_OPERATION_OVERFLOW_DIAG, (loc, msg)); - env.add_diag(diag); -} diff --git a/external-crates/move/crates/move-compiler/src/naming/translate.rs b/external-crates/move/crates/move-compiler/src/naming/translate.rs index 38a68e913601ac..035d88c7ae55af 100644 --- a/external-crates/move/crates/move-compiler/src/naming/translate.rs +++ b/external-crates/move/crates/move-compiler/src/naming/translate.rs @@ -444,7 +444,12 @@ pub fn build_member_map( tyarg_arity, field_info, }; - assert!(members.insert(name.value(), M::Datatype(ResolvedDatatype::Struct(Box::new(struct_def)))).is_none()) + assert!(members + .insert( + name.value(), + M::Datatype(ResolvedDatatype::Struct(Box::new(struct_def))) + ) + .is_none()) } for (enum_name, edef) in mdef.enums.key_cloned_iter() { let tyarg_arity = edef.type_parameters.len(); diff --git a/external-crates/move/crates/move-compiler/tests/custom_rules/shift_overflow.exp b/external-crates/move/crates/move-compiler/tests/custom_rules/shift_overflow.exp deleted file mode 100644 index ed6efd6a2ea675..00000000000000 --- a/external-crates/move/crates/move-compiler/tests/custom_rules/shift_overflow.exp +++ /dev/null @@ -1,24 +0,0 @@ -warning[Lint W00001]: Potential overflow detected. The number of bits being shifted exceeds the bit width of the variable being shifted. - ┌─ tests/custom_rules/shift_overflow.move:5:20 - │ -5 │ let _b = x << 64; // Should not raise an issue - │ ^^ The 64 of bits being shifted exceeds the 64 bit width of the variable being shifted. - │ - = This warning can be suppressed with '#[allow(lint(shift_overflow))]' applied to the 'module' or module member ('const', 'fun', or 'struct') - -warning[Lint W00001]: Potential overflow detected. The number of bits being shifted exceeds the bit width of the variable being shifted. - ┌─ tests/custom_rules/shift_overflow.move:6:20 - │ -6 │ let _b = x << 65; // Should raise an issue - │ ^^ The 65 of bits being shifted exceeds the 64 bit width of the variable being shifted. - │ - = This warning can be suppressed with '#[allow(lint(shift_overflow))]' applied to the 'module' or module member ('const', 'fun', or 'struct') - -warning[Lint W00001]: Potential overflow detected. The number of bits being shifted exceeds the bit width of the variable being shifted. - ┌─ tests/custom_rules/shift_overflow.move:7:20 - │ -7 │ let _b = x >> 66; // Should raise an issue - │ ^^ The 66 of bits being shifted exceeds the 64 bit width of the variable being shifted. - │ - = This warning can be suppressed with '#[allow(lint(shift_overflow))]' applied to the 'module' or module member ('const', 'fun', or 'struct') - diff --git a/external-crates/move/crates/move-compiler/tests/custom_rules/shift_overflow.move b/external-crates/move/crates/move-compiler/tests/custom_rules/shift_overflow.move deleted file mode 100644 index e5dc71e6f6563e..00000000000000 --- a/external-crates/move/crates/move-compiler/tests/custom_rules/shift_overflow.move +++ /dev/null @@ -1,9 +0,0 @@ -module 0x42::M { - - fun func1(x: u64) { - let _b = x << 24; - let _b = x << 64; // Should raise an issue - let _b = x << 65; // Should raise an issue - let _b = x >> 66; // Should raise an issue - } -} \ No newline at end of file diff --git a/external-crates/move/crates/move-compiler/tests/linter/correct_public_mut_tx_context.move b/external-crates/move/crates/move-compiler/tests/linter/correct_public_mut_tx_context.move new file mode 100644 index 00000000000000..a9da2efe4f299f --- /dev/null +++ b/external-crates/move/crates/move-compiler/tests/linter/correct_public_mut_tx_context.move @@ -0,0 +1,10 @@ +module 0x42::M { + use sui::tx_context::TxContext; + public fun mint(_ctx: &mut TxContext) { + + } +} + +module sui::tx_context { + struct TxContext has drop {} +} \ No newline at end of file diff --git a/external-crates/move/crates/move-compiler/tests/linter/incorrect_constant_naming.exp b/external-crates/move/crates/move-compiler/tests/linter/incorrect_constant_naming.exp index 763e36f065ba38..944dd5bdad57fe 100644 --- a/external-crates/move/crates/move-compiler/tests/linter/incorrect_constant_naming.exp +++ b/external-crates/move/crates/move-compiler/tests/linter/incorrect_constant_naming.exp @@ -1,4 +1,4 @@ -warning[Lint W00001]: constant should follow naming convention +warning[Lint W04001]: constant should follow naming convention ┌─ tests/linter/incorrect_constant_naming.move:3:5 │ 3 │ const Another_BadName: u64 = 42; // Should trigger a warning @@ -6,7 +6,7 @@ warning[Lint W00001]: constant should follow naming convention │ = This warning can be suppressed with '#[allow(lint(constant_naming))]' applied to the 'module' or module member ('const', 'fun', or 'struct') -warning[Lint W00001]: constant should follow naming convention +warning[Lint W04001]: constant should follow naming convention ┌─ tests/linter/incorrect_constant_naming.move:4:5 │ 4 │ const JSON_Max_Size: u64 = 1048576; diff --git a/external-crates/move/crates/move-compiler/tests/linter/incorrect_public_mut_tx_context.exp b/external-crates/move/crates/move-compiler/tests/linter/incorrect_public_mut_tx_context.exp new file mode 100644 index 00000000000000..f4b522cebc33dc --- /dev/null +++ b/external-crates/move/crates/move-compiler/tests/linter/incorrect_public_mut_tx_context.exp @@ -0,0 +1,8 @@ +warning[Lint W02014]: + ┌─ tests/linter/incorrect_public_mut_tx_context.move:3:28 + │ +3 │ public fun mint(_ctx: &TxContext) { + │ ^^^^^^^^^ Public functions should take `&mut TxContext` instead of `&TxContext` for better upgradability. + │ + = This warning can be suppressed with '#[allow(lint(public_mut_tx_context))]' applied to the 'module' or module member ('const', 'fun', or 'struct') + diff --git a/external-crates/move/crates/move-compiler/tests/linter/incorrect_public_mut_tx_context.move b/external-crates/move/crates/move-compiler/tests/linter/incorrect_public_mut_tx_context.move new file mode 100644 index 00000000000000..97bde7c96e6964 --- /dev/null +++ b/external-crates/move/crates/move-compiler/tests/linter/incorrect_public_mut_tx_context.move @@ -0,0 +1,10 @@ +module 0x42::M { + use sui::tx_context::TxContext; + public fun mint(_ctx: &TxContext) { + + } +} + +module sui::tx_context { + struct TxContext has drop {} +} \ No newline at end of file diff --git a/external-crates/move/crates/move-compiler/tests/linter/suppressed_lints.move b/external-crates/move/crates/move-compiler/tests/linter/suppressed_lints.move index a75210a0364a70..fcc98fdff0264d 100644 --- a/external-crates/move/crates/move-compiler/tests/linter/suppressed_lints.move +++ b/external-crates/move/crates/move-compiler/tests/linter/suppressed_lints.move @@ -1,5 +1,16 @@ module 0x42::M { + use sui::tx_context::TxContext; #[allow(lint(constant_naming))] const Another_BadName: u64 = 42; // Should trigger a warning + + #[allow(lint(public_mut_tx_context))] + public fun mint(_ctx: &TxContext) { + + } +} + + +module sui::tx_context { + struct TxContext has drop {} }