use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct Name(pub u32);
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct StrId(pub u32);
#[derive(Default)]
struct Interner {
map: HashMap<Rc<str>, u32>,
items: Vec<Rc<str>>,
}
impl Interner {
fn get(&mut self, s: &str) -> u32 {
if let Some(&i) = self.map.get(s) {
return i;
}
let i = self.items.len() as u32;
let r: Rc<str> = Rc::from(s);
self.items.push(r.clone());
self.map.insert(r, i);
i
}
}
#[derive(Default)]
struct GlobalStrs {
map: HashMap<Arc<str>, u32>,
items: Vec<Arc<str>>,
}
static GLOBAL_STRS: Mutex<Option<GlobalStrs>> = Mutex::new(None);
const PROVISIONAL: u32 = 0x4000_0000;
#[derive(Default)]
struct StrCache {
map: HashMap<Rc<str>, u32>,
items: Vec<Option<Rc<str>>>,
provisional: Vec<Rc<str>>,
}
impl StrCache {
#[cold]
fn slow_id(&mut self, s: &str) -> u32 {
let r: Rc<str> = Rc::from(s);
let i = {
let mut g = GLOBAL_STRS.lock().unwrap_or_else(|e| e.into_inner());
let g = g.get_or_insert_with(GlobalStrs::default);
match g.map.get(s) {
Some(&i) => i,
None if is_worker() => {
worker_impure("a string first created during the search");
let i = PROVISIONAL + self.provisional.len() as u32;
self.provisional.push(r.clone());
self.map.insert(r, i);
return i;
}
None => {
let i = g.items.len() as u32;
let a: Arc<str> = Arc::from(s);
g.items.push(a.clone());
g.map.insert(a, i);
i
}
}
};
self.put(i, r.clone());
self.map.insert(r, i);
i
}
fn put(&mut self, i: u32, r: Rc<str>) {
let i = i as usize;
if i >= self.items.len() {
self.items.resize(i + 1, None);
}
self.items[i] = Some(r);
}
#[cold]
fn slow_str(&mut self, i: u32) -> Rc<str> {
if i >= PROVISIONAL {
return self.provisional[(i - PROVISIONAL) as usize].clone();
}
let r: Rc<str> = {
let g = GLOBAL_STRS.lock().unwrap_or_else(|e| e.into_inner());
Rc::from(&*g.as_ref().expect("string table").items[i as usize])
};
self.put(i, r.clone());
self.map.insert(r.clone(), i);
r
}
}
thread_local! {
static NAMES: RefCell<Interner> = RefCell::new(Interner::default());
static STRS: RefCell<StrCache> = RefCell::new(StrCache::default());
static WORKER: Cell<bool> = const { Cell::new(false) };
static IMPURE: Cell<Option<&'static str>> = const { Cell::new(None) };
}
pub fn set_worker(on: bool) {
WORKER.with(|w| w.set(on));
}
#[inline]
pub fn is_worker() -> bool {
WORKER.with(|w| w.get())
}
#[inline]
pub fn worker_impure(what: &'static str) -> bool {
if !is_worker() {
return false;
}
IMPURE.with(|c| {
if c.get().is_none() {
c.set(Some(what));
}
});
true
}
pub fn take_impure() -> Option<&'static str> {
IMPURE.with(|c| c.take())
}
#[cold]
pub fn impure_err<T>() -> R<T> {
eval_err("this operator is evaluated by the sequential search only".to_string())
}
pub fn name(s: &str) -> Name {
NAMES.with(|n| Name(n.borrow_mut().get(s)))
}
pub fn name_str(n: Name) -> Rc<str> {
NAMES.with(|t| t.borrow().items[n.0 as usize].clone())
}
pub fn str_id(s: &str) -> StrId {
STRS.with(|n| {
let mut n = n.borrow_mut();
if let Some(&i) = n.map.get(s) {
return StrId(i);
}
StrId(n.slow_id(s))
})
}
fn content_hash(s: &str) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in s.as_bytes() {
h = (h ^ *b as u64).wrapping_mul(0x0000_0100_0000_01B3);
}
h ^= h >> 32;
h = h.wrapping_mul(0xD6E8_FEB8_6659_FD93);
h ^= h >> 32;
h | (h == 0) as u64
}
thread_local! {
static STR_HASH_TABLE: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
static STR_HASHES: Cell<(*const u64, usize)> = const { Cell::new((std::ptr::null(), 0)) };
}
#[inline]
pub fn str_hash(id: StrId) -> u64 {
let (p, len) = STR_HASHES.with(|c| c.get());
if (id.0 as usize) < len {
let h = unsafe { *p.add(id.0 as usize) };
if h != 0 {
return h;
}
}
str_hash_slow(id)
}
#[cold]
fn str_hash_slow(id: StrId) -> u64 {
let h = content_hash(&str_of(id));
if id.0 < PROVISIONAL {
STR_HASH_TABLE.with(|t| {
let mut t = t.borrow_mut();
let i = id.0 as usize;
if i >= t.len() {
t.resize((i + 1).next_power_of_two(), 0);
}
t[i] = h;
STR_HASHES.with(|c| c.set((t.as_ptr(), t.len())));
});
}
h
}
pub fn str_of(id: StrId) -> Rc<str> {
STRS.with(|t| {
let mut t = t.borrow_mut();
if let Some(Some(r)) = t.items.get(id.0 as usize) {
return r.clone();
}
t.slow_str(id.0)
})
}
impl std::fmt::Display for Name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&name_str(*self))
}
}
thread_local! {
static MV_TYPES: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}
static ANY_TYPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
#[inline]
pub fn any_typed() -> bool {
ANY_TYPED.load(std::sync::atomic::Ordering::Relaxed)
}
pub fn model_value(name: &str) -> StrId {
let b = name.as_bytes();
if b.len() > 2 && b[1] == b'_' {
ANY_TYPED.store(true, std::sync::atomic::Ordering::Relaxed);
}
str_id(name)
}
pub fn model_type(id: StrId) -> Option<u8> {
if !any_typed() || id.0 >= PROVISIONAL {
return None;
}
MV_TYPES.with(|c| {
let mut c = c.borrow_mut();
let i = id.0 as usize;
if i >= c.len() {
c.resize(i + 1, 255);
}
if c[i] == 255 {
let s = str_of(id);
let b = s.as_bytes();
c[i] = if b.len() > 2 && b[1] == b'_' { b[0] } else { 0 };
}
if c[i] == 0 { None } else { Some(c[i]) }
})
}
pub type Loc = [u32; 4];
#[derive(Debug, Clone)]
pub struct TlaError {
pub msg: String,
pub loc: Option<Loc>,
pub module: Option<String>,
pub kind: &'static str,
}
#[derive(Debug)]
pub enum Fail {
Found,
Tla(TlaError),
Check { status: &'static str, message: String },
}
pub type R<T> = Result<T, Box<Fail>>;
pub fn err<T>(kind: &'static str, msg: String) -> R<T> {
Err(Box::new(Fail::Tla(TlaError { msg, loc: None, module: None, kind })))
}
pub fn eval_err<T>(msg: String) -> R<T> {
err("eval", msg)
}