| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
use super::CodeType; |
| 6 |
use crate::{backend::Literal, bail, interface::Radix, Result}; |
| 7 |
|
| 8 |
fn render_literal(literal: &Literal) -> Result<String> { |
| 9 |
Ok(match literal { |
| 10 |
Literal::Boolean(v) => { |
| 11 |
if *v { |
| 12 |
"True".into() |
| 13 |
} else { |
| 14 |
"False".into() |
| 15 |
} |
| 16 |
} |
| 17 |
Literal::String(s) => format!("\"{s}\""), |
| 18 |
// https://docs.python.org/3/reference/lexical_analysis.html#integer-literals |
| 19 |
Literal::Int(i, radix, _) => match radix { |
| 20 |
Radix::Octal => format!("int(0o{i:o})"), |
| 21 |
Radix::Decimal => format!("{i}"), |
| 22 |
Radix::Hexadecimal => format!("{i:#x}"), |
| 23 |
}, |
| 24 |
Literal::UInt(i, radix, _) => match radix { |
| 25 |
Radix::Octal => format!("0o{i:o}"), |
| 26 |
Radix::Decimal => format!("{i}"), |
| 27 |
Radix::Hexadecimal => format!("{i:#x}"), |
| 28 |
}, |
| 29 |
Literal::Float(string, _type_) => string.clone(), |
| 30 |
|
| 31 |
_ => bail!("Invalid literal {literal:?}"), |
| 32 |
}) |
| 33 |
} |
| 34 |
|
| 35 |
macro_rules! impl_code_type_for_primitive { |
| 36 |
($T:ident, $python_name:literal, $canonical_name:literal) => { |
| 37 |
#[derive(Debug)] |
| 38 |
pub struct $T; |
| 39 |
impl CodeType for $T { |
| 40 |
fn type_label(&self) -> String { |
| 41 |
$python_name.into() |
| 42 |
} |
| 43 |
|
| 44 |
fn canonical_name(&self) -> String { |
| 45 |
$canonical_name.into() |
| 46 |
} |
| 47 |
|
| 48 |
fn literal(&self, literal: &Literal) -> Result<String> { |
| 49 |
render_literal(&literal) |
| 50 |
} |
| 51 |
} |
| 52 |
}; |
| 53 |
} |
| 54 |
|
| 55 |
impl_code_type_for_primitive!(BooleanCodeType, "bool", "Bool"); |
| 56 |
impl_code_type_for_primitive!(StringCodeType, "str", "String"); |
| 57 |
impl_code_type_for_primitive!(BytesCodeType, "bytes", "Bytes"); |
| 58 |
impl_code_type_for_primitive!(Int8CodeType, "int", "Int8"); |
| 59 |
impl_code_type_for_primitive!(Int16CodeType, "int", "Int16"); |
| 60 |
impl_code_type_for_primitive!(Int32CodeType, "int", "Int32"); |
| 61 |
impl_code_type_for_primitive!(Int64CodeType, "int", "Int64"); |
| 62 |
impl_code_type_for_primitive!(UInt8CodeType, "int", "UInt8"); |
| 63 |
impl_code_type_for_primitive!(UInt16CodeType, "int", "UInt16"); |
| 64 |
impl_code_type_for_primitive!(UInt32CodeType, "int", "UInt32"); |
| 65 |
impl_code_type_for_primitive!(UInt64CodeType, "int", "UInt64"); |
| 66 |
impl_code_type_for_primitive!(Float32CodeType, "float", "Float"); |
| 67 |
impl_code_type_for_primitive!(Float64CodeType, "float", "Double"); |