MCPcopy Index your code
hub / github.com/RustPython/RustPython / make_constant

Method make_constant

crates/vm/src/builtins/code.rs:283–332  ·  view source on GitHub ↗
(&self, constant: BorrowedConstant<'_, C>)

Source from the content-addressed store, hash-verified

281 type Constant = Literal;
282
283 fn make_constant<C: Constant>(&self, constant: BorrowedConstant<'_, C>) -> Self::Constant {
284 let ctx = self.0;
285 let obj = match constant {
286 BorrowedConstant::Integer { value } => ctx.new_bigint(value).into(),
287 BorrowedConstant::Float { value } => ctx.new_float(value).into(),
288 BorrowedConstant::Complex { value } => ctx.new_complex(value).into(),
289 BorrowedConstant::Str { value } if value.len() <= 20 => {
290 ctx.intern_str(value).to_object()
291 }
292 BorrowedConstant::Str { value } => ctx.new_str(value).into(),
293 BorrowedConstant::Bytes { value } => ctx.new_bytes(value.to_vec()).into(),
294 BorrowedConstant::Boolean { value } => ctx.new_bool(value).into(),
295 BorrowedConstant::Code { code } => ctx.new_code(code.map_clone_bag(self)).into(),
296 BorrowedConstant::Tuple { elements } => {
297 let elements = elements
298 .iter()
299 .map(|constant| self.make_constant(constant.borrow_constant()).0)
300 .collect();
301 ctx.new_tuple(elements).into()
302 }
303 BorrowedConstant::Slice { elements } => {
304 let [start, stop, step] = elements;
305 let start_obj = self.make_constant(start.borrow_constant()).0;
306 let stop_obj = self.make_constant(stop.borrow_constant()).0;
307 let step_obj = self.make_constant(step.borrow_constant()).0;
308 // Store as PySlice with Some() for all fields (even None values)
309 // so borrow_obj_constant can reference them.
310 use crate::builtins::PySlice;
311 PySlice {
312 start: Some(start_obj),
313 stop: stop_obj,
314 step: Some(step_obj),
315 }
316 .into_ref(ctx)
317 .into()
318 }
319 BorrowedConstant::Frozenset { elements: _ } => {
320 // Creating a frozenset requires VirtualMachine for element hashing.
321 // PyObjBag only has Context, so we cannot construct PyFrozenSet here.
322 // Frozenset constants from .pyc are handled by PyMarshalBag which has VM access.
323 unimplemented!(
324 "frozenset constant in PyObjBag::make_constant requires VirtualMachine"
325 )
326 }
327 BorrowedConstant::None => ctx.none(),
328 BorrowedConstant::Ellipsis => ctx.ellipsis.clone().into(),
329 };
330
331 Literal(obj)
332 }
333
334 fn make_name(&self, name: &str) -> &'static PyStrInterned {
335 self.0.intern_str(name)

Callers

nothing calls this directly

Calls 15

new_bigintMethod · 0.80
intern_strMethod · 0.80
to_vecMethod · 0.80
map_clone_bagMethod · 0.80
collectMethod · 0.80
noneMethod · 0.80
LiteralClass · 0.70
SomeClass · 0.50
new_floatMethod · 0.45
new_complexMethod · 0.45
lenMethod · 0.45
to_objectMethod · 0.45

Tested by

no test coverage detected