|
| 1 | +//! Declaration resolution contexts built natively from a Python scope lookup's positions. |
| 2 | +
|
| 3 | +use std::collections::HashMap; |
| 4 | + |
| 5 | +use pyo3::prelude::{Bound, Py, PyAny, PyAnyMethods, PyModule, PyModuleMethods, PyResult, Python}; |
| 6 | +use pyo3::types::{PyDict, PyDictMethods, PyTuple}; |
| 7 | +use pyo3::{FromPyObject, intern, pyclass, pymethods}; |
| 8 | + |
| 9 | +use crate::bindings::_helpers::boundary::panics::compiler_guard; |
| 10 | +use sqlbuild_scopes::scope_index::main::classify_resource::classify_resource; |
| 11 | +use sqlbuild_scopes::scope_index::models::{ |
| 12 | + ConsumerResource, GrantEntry, VisibilityReason, VisibilityTable, VisibleEntry, |
| 13 | +}; |
| 14 | + |
| 15 | +const ENUM_KIND: u8 = 0; |
| 16 | +const CONSTANT_KIND: u8 = 1; |
| 17 | +const MACRO_KIND: u8 = 2; |
| 18 | + |
| 19 | +type TableRow = ( |
| 20 | + Vec<usize>, |
| 21 | + HashMap<String, Vec<usize>>, |
| 22 | + HashMap<String, Vec<usize>>, |
| 23 | +); |
| 24 | +type VisibleRow<'py> = (Bound<'py, PyAny>, VisibleEntry, Option<Bound<'py, PyAny>>); |
| 25 | + |
| 26 | +/// One declaration position: identity, first record, name, kinds, runtime value and key. |
| 27 | +#[derive(FromPyObject)] |
| 28 | +struct PositionRow(Py<PyAny>, Py<PyAny>, Py<PyAny>, u8, Py<PyAny>, u8, u32); |
| 29 | + |
| 30 | +/// The Python classes and enum members the contexts are built from. |
| 31 | +#[derive(FromPyObject)] |
| 32 | +#[pyo3(from_item_all)] |
| 33 | +struct ContextClasses { |
| 34 | + visibility_record: Py<PyAny>, |
| 35 | + resolution_context: Py<PyAny>, |
| 36 | + allocate: Py<PyAny>, |
| 37 | + reasons: Py<PyDict>, |
| 38 | +} |
| 39 | + |
| 40 | +/// Positions, visibility table and classes of one scope lookup. |
| 41 | +#[pyclass(frozen, module = "sqlbuild._native")] |
| 42 | +struct NativeDeclarationContexts { |
| 43 | + positions: Vec<PositionRow>, |
| 44 | + table: VisibilityTable, |
| 45 | + classes: ContextClasses, |
| 46 | + lookup: LookupMappings, |
| 47 | +} |
| 48 | + |
| 49 | +/// The Python lookup mappings a matching resource's private positions and grants come from. |
| 50 | +#[derive(FromPyObject)] |
| 51 | +#[pyo3(from_item_all)] |
| 52 | +struct LookupMappings { |
| 53 | + identity_keys: Py<PyDict>, |
| 54 | + private_positions: Py<PyAny>, |
| 55 | + grants_by_resource: Py<PyAny>, |
| 56 | +} |
| 57 | + |
| 58 | +/// Dictionaries one context is assembled into, in Python's insertion order. |
| 59 | +struct ContextParts<'py> { |
| 60 | + enums: Bound<'py, PyDict>, |
| 61 | + constants: Bound<'py, PyDict>, |
| 62 | + macros: Bound<'py, PyDict>, |
| 63 | + macro_records: Bound<'py, PyDict>, |
| 64 | + inaccessible: [Bound<'py, PyDict>; 3], |
| 65 | + visibility: [Bound<'py, PyDict>; 3], |
| 66 | +} |
| 67 | + |
| 68 | +#[pymethods] |
| 69 | +impl NativeDeclarationContexts { |
| 70 | + #[new] |
| 71 | + fn new( |
| 72 | + positions: Vec<PositionRow>, |
| 73 | + table: TableRow, |
| 74 | + classes: ContextClasses, |
| 75 | + lookup: LookupMappings, |
| 76 | + ) -> Self { |
| 77 | + let (global, local, inherited) = table; |
| 78 | + let identity_keys: Vec<u32> = positions.iter().map(|row| row.6).collect(); |
| 79 | + Self { |
| 80 | + table: VisibilityTable { |
| 81 | + identity_keys, |
| 82 | + global, |
| 83 | + local, |
| 84 | + inherited, |
| 85 | + }, |
| 86 | + positions, |
| 87 | + classes, |
| 88 | + lookup, |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + /// Return the context Python's resolver builds for these matching resources, or None. |
| 93 | + fn context<'py>( |
| 94 | + &self, |
| 95 | + py: Python<'py>, |
| 96 | + matches: Vec<Bound<'py, PyAny>>, |
| 97 | + consumer: Bound<'py, PyAny>, |
| 98 | + ) -> PyResult<Option<Bound<'py, PyAny>>> { |
| 99 | + compiler_guard(|| self.classified_context(py, matches, consumer)) |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +impl NativeDeclarationContexts { |
| 104 | + fn classified_context<'py>( |
| 105 | + &self, |
| 106 | + py: Python<'py>, |
| 107 | + matches: Vec<Bound<'py, PyAny>>, |
| 108 | + consumer: Bound<'py, PyAny>, |
| 109 | + ) -> PyResult<Option<Bound<'py, PyAny>>> { |
| 110 | + let mut visible: Vec<VisibleRow<'py>> = Vec::new(); |
| 111 | + let mut inaccessible: Vec<usize> = Vec::new(); |
| 112 | + for record in matches { |
| 113 | + let identity: Bound<'py, PyAny> = record.getattr(intern!(py, "identity"))?; |
| 114 | + let path: String = record.getattr(intern!(py, "path"))?.extract()?; |
| 115 | + let private: Vec<usize> = self |
| 116 | + .lookup |
| 117 | + .private_positions |
| 118 | + .bind(py) |
| 119 | + .call_method1(intern!(py, "get"), (&identity, PyTuple::empty(py)))? |
| 120 | + .extract()?; |
| 121 | + if private |
| 122 | + .iter() |
| 123 | + .any(|position| *position >= self.positions.len()) |
| 124 | + { |
| 125 | + return Ok(None); |
| 126 | + } |
| 127 | + let (grants, throughs) = self.grants(py, &identity)?; |
| 128 | + let Ok(classified) = classify_resource( |
| 129 | + &self.table, |
| 130 | + &ConsumerResource { |
| 131 | + private, |
| 132 | + path, |
| 133 | + grants, |
| 134 | + }, |
| 135 | + ) else { |
| 136 | + return Ok(None); |
| 137 | + }; |
| 138 | + for entry in classified.visible { |
| 139 | + let through: Option<Bound<'py, PyAny>> = |
| 140 | + entry.through.map(|slot| throughs[slot].clone()); |
| 141 | + visible.push((identity.clone(), entry, through)); |
| 142 | + } |
| 143 | + inaccessible.extend(classified.inaccessible); |
| 144 | + } |
| 145 | + self.assemble(py, &visible, &inaccessible, consumer) |
| 146 | + .map(Some) |
| 147 | + } |
| 148 | + |
| 149 | + /// The resource's grants of indexed declarations, with each grant's `through` value. |
| 150 | + fn grants<'py>( |
| 151 | + &self, |
| 152 | + py: Python<'py>, |
| 153 | + identity: &Bound<'py, PyAny>, |
| 154 | + ) -> PyResult<(Vec<GrantEntry>, Vec<Bound<'py, PyAny>>)> { |
| 155 | + let records: Bound<'py, PyAny> = self |
| 156 | + .lookup |
| 157 | + .grants_by_resource |
| 158 | + .bind(py) |
| 159 | + .call_method1(intern!(py, "get"), (identity, PyTuple::empty(py)))?; |
| 160 | + let identity_keys: &Bound<'py, PyDict> = self.lookup.identity_keys.bind(py); |
| 161 | + let mut grants: Vec<GrantEntry> = Vec::new(); |
| 162 | + let mut throughs: Vec<Bound<'py, PyAny>> = Vec::new(); |
| 163 | + for grant in records.try_iter()? { |
| 164 | + let grant: Bound<'py, PyAny> = grant?; |
| 165 | + let Some(identity_key) = |
| 166 | + identity_keys.get_item(grant.getattr(intern!(py, "declaration"))?)? |
| 167 | + else { |
| 168 | + continue; |
| 169 | + }; |
| 170 | + let kind: String = grant |
| 171 | + .getattr(intern!(py, "kind"))? |
| 172 | + .getattr(intern!(py, "value"))? |
| 173 | + .extract()?; |
| 174 | + grants.push(GrantEntry { |
| 175 | + identity_key: identity_key.extract()?, |
| 176 | + reason: if kind == VisibilityReason::TestedMacro.as_str() { |
| 177 | + VisibilityReason::TestedMacro |
| 178 | + } else { |
| 179 | + VisibilityReason::ExpectedModel |
| 180 | + }, |
| 181 | + through: throughs.len(), |
| 182 | + }); |
| 183 | + throughs.push(grant.getattr(intern!(py, "through"))?); |
| 184 | + } |
| 185 | + Ok((grants, throughs)) |
| 186 | + } |
| 187 | + |
| 188 | + fn assemble<'py>( |
| 189 | + &self, |
| 190 | + py: Python<'py>, |
| 191 | + visible: &[VisibleRow<'py>], |
| 192 | + inaccessible: &[usize], |
| 193 | + consumer: Bound<'py, PyAny>, |
| 194 | + ) -> PyResult<Bound<'py, PyAny>> { |
| 195 | + let parts: ContextParts<'py> = ContextParts { |
| 196 | + enums: PyDict::new(py), |
| 197 | + constants: PyDict::new(py), |
| 198 | + macros: PyDict::new(py), |
| 199 | + macro_records: PyDict::new(py), |
| 200 | + inaccessible: [PyDict::new(py), PyDict::new(py), PyDict::new(py)], |
| 201 | + visibility: [PyDict::new(py), PyDict::new(py), PyDict::new(py)], |
| 202 | + }; |
| 203 | + let mut records_by_identity: HashMap<u32, Vec<Bound<'py, PyAny>>> = HashMap::new(); |
| 204 | + for (resource, entry, through) in visible { |
| 205 | + let record: Bound<'py, PyAny> = self.visibility_record(py, resource, entry, through)?; |
| 206 | + records_by_identity |
| 207 | + .entry(self.positions[entry.position].6) |
| 208 | + .or_default() |
| 209 | + .push(record); |
| 210 | + } |
| 211 | + for (_, entry, _) in visible { |
| 212 | + self.add_visible_value(py, &parts, entry.position)?; |
| 213 | + } |
| 214 | + for position in inaccessible { |
| 215 | + let row: &PositionRow = &self.positions[*position]; |
| 216 | + if let Some(target) = parts.inaccessible.get(usize::from(row.3)) { |
| 217 | + target.set_item(row.2.bind(py), row.1.bind(py))?; |
| 218 | + } |
| 219 | + } |
| 220 | + for (_, entry, _) in visible { |
| 221 | + let row: &PositionRow = &self.positions[entry.position]; |
| 222 | + if let Some(target) = parts.visibility.get(usize::from(row.3)) { |
| 223 | + let records: &[Bound<'py, PyAny>] = |
| 224 | + records_by_identity.get(&row.6).map_or(&[], Vec::as_slice); |
| 225 | + target.set_item(row.2.bind(py), PyTuple::new(py, records)?)?; |
| 226 | + } |
| 227 | + } |
| 228 | + let fields: Bound<'py, PyDict> = PyDict::new(py); |
| 229 | + fields.set_item("enums", &parts.enums)?; |
| 230 | + fields.set_item("constants", &parts.constants)?; |
| 231 | + fields.set_item("inaccessible_enums", &parts.inaccessible[0])?; |
| 232 | + fields.set_item("inaccessible_constants", &parts.inaccessible[1])?; |
| 233 | + fields.set_item("enum_visibility", &parts.visibility[0])?; |
| 234 | + fields.set_item("constant_visibility", &parts.visibility[1])?; |
| 235 | + fields.set_item("macros", &parts.macros)?; |
| 236 | + fields.set_item("macro_records", &parts.macro_records)?; |
| 237 | + fields.set_item("macro_visibility", &parts.visibility[2])?; |
| 238 | + fields.set_item("inaccessible_macros", &parts.inaccessible[2])?; |
| 239 | + fields.set_item("consumer", consumer)?; |
| 240 | + self.classes |
| 241 | + .resolution_context |
| 242 | + .bind(py) |
| 243 | + .call((), Some(&fields)) |
| 244 | + } |
| 245 | + |
| 246 | + fn add_visible_value<'py>( |
| 247 | + &self, |
| 248 | + py: Python<'py>, |
| 249 | + parts: &ContextParts<'py>, |
| 250 | + position: usize, |
| 251 | + ) -> PyResult<()> { |
| 252 | + let row: &PositionRow = &self.positions[position]; |
| 253 | + let name: &Bound<'py, PyAny> = row.2.bind(py); |
| 254 | + let value: &Bound<'py, PyAny> = row.4.bind(py); |
| 255 | + match row.5 { |
| 256 | + ENUM_KIND => parts.enums.set_item(name, value), |
| 257 | + CONSTANT_KIND => parts.constants.set_item(name, value), |
| 258 | + MACRO_KIND => { |
| 259 | + parts.macros.set_item(name, value)?; |
| 260 | + parts.macro_records.set_item(name, row.1.bind(py)) |
| 261 | + } |
| 262 | + _ => Ok(()), |
| 263 | + } |
| 264 | + } |
| 265 | + |
| 266 | + fn visibility_record<'py>( |
| 267 | + &self, |
| 268 | + py: Python<'py>, |
| 269 | + resource: &Bound<'py, PyAny>, |
| 270 | + entry: &VisibleEntry, |
| 271 | + through: &Option<Bound<'py, PyAny>>, |
| 272 | + ) -> PyResult<Bound<'py, PyAny>> { |
| 273 | + let class: &Bound<'py, PyAny> = self.classes.visibility_record.bind(py); |
| 274 | + let record: Bound<'py, PyAny> = self.classes.allocate.bind(py).call1((class,))?; |
| 275 | + let attributes: Bound<'py, PyDict> = |
| 276 | + record.getattr("__dict__")?.downcast_into::<PyDict>()?; |
| 277 | + attributes.set_item("resource", resource)?; |
| 278 | + attributes.set_item("declaration", self.positions[entry.position].0.bind(py))?; |
| 279 | + attributes.set_item( |
| 280 | + "reason", |
| 281 | + self.classes |
| 282 | + .reasons |
| 283 | + .bind(py) |
| 284 | + .get_item(entry.reason.as_str())?, |
| 285 | + )?; |
| 286 | + attributes.set_item("through", through)?; |
| 287 | + Ok(record) |
| 288 | + } |
| 289 | +} |
| 290 | + |
| 291 | +pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> { |
| 292 | + module.add_class::<NativeDeclarationContexts>()?; |
| 293 | + Ok(()) |
| 294 | +} |
0 commit comments