Thread_local & rust analyzer

I have initialized some variables inside thread_local, but the variables were imported into another module a few days back. But right now they are unable to import. Kindly help. Thanks!

thread_local! {

    static MEMORY_MANAGER: RefCell<MemoryManager<DefaultMemoryImpl>> =
        RefCell::new(MemoryManager::init(DefaultMemoryImpl::default()));

  // StableCell to store  Constants
  pub static CONSTANTS: RefCell<StableCell<Constants, Memory>> = RefCell::new(
    StableCell::init(
        MEMORY_MANAGER.with(|m| m.borrow().get(CONSTANTS_MEMORY)),
       Constants::default()
).unwrap()

);
//.....
}
1 Like

Please post the full error you get from running cargo build in the terminal.

I am not getting any build errors.
The problem I encountered was the file where I placed thread_local variables. Issues are

  1. Formatting not working only on that file
  2. Variables are not imported to other modules with intellisence

I tried to reinstall the extension but the issue persists

Actually, formatting is not working inside thread_local

Formatting isn't working for me either inside thread_local, and I'm using a different editor. So it must be a problem with rustfmt. There are a bunch of rustfmt issues related to macros, so we probably need to manually format inside thread_local, at least for now.

As a general practice, I try to keep the amount of code that is inside macros as small as possible — because even if it were formatted properly, there are still other tools that won't know what to do with the macro. In this case, you could move the initialization to separate functions, which rustfmt can format fine:

thread_local! {
    static MEMORY_MANAGER: RefCell<MemoryManager<DefaultMemoryImpl>> = init_mem();
    pub static CONSTANTS: RefCell<StableCell<Constants, Memory>> = init_constants();
}

const fn init_mem() -> RefCell<MemoryManager<DefaultMemoryImpl>> {
    RefCell::new(MemoryManager::init(DefaultMemoryImpl::default()))
}

const fn init_constants() -> RefCell<StableCell<Constants, Memory>> {
    RefCell::new(
        StableCell::init(
            MEMORY_MANAGER.with(|m| m.borrow().get(CONSTANTS_MEMORY)),
            Constants::default(),
        )
        .unwrap(),
    )
}

I can reproduce this even with something as simple as thread_local!(static FOO: i32 = 0;). Rust-analyzer just doesn't recognize FOO as a variable and all suggestions based on that (importing it in another module, suggesting methods that can be called on it etc etc) don't work.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.