Skip to main content

react_compiler_ast/
literals.rs

1use react_compiler_diagnostics::JsString;
2use serde::Serialize;
3
4use crate::common::BaseNode;
5
6#[derive(Debug, Clone, Serialize)]
7pub struct StringLiteral {
8    #[serde(flatten)]
9    pub base: BaseNode,
10    /// JS string values may contain unpaired surrogates; see [`JsString`].
11    pub value: JsString,
12}
13
14#[derive(Debug, Clone, Serialize)]
15pub struct NumericLiteral {
16    #[serde(flatten)]
17    pub base: BaseNode,
18    pub value: f64,
19    /// Babel's extra field containing the raw source text.
20    /// Used to recover exact f64 values that serde_json may parse imprecisely.
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub extra: Option<NumericLiteralExtra>,
23}
24
25impl NumericLiteral {
26    /// Get the f64 value, preferring re-parsing from `extra.raw` when available
27    /// to avoid serde_json float parsing precision issues.
28    pub fn precise_value(&self) -> f64 {
29        if let Some(extra) = &self.extra {
30            if let Ok(v) = extra.raw.parse::<f64>() {
31                return v;
32            }
33        }
34        self.value
35    }
36}
37
38#[derive(Debug, Clone, Serialize)]
39pub struct NumericLiteralExtra {
40    pub raw: String,
41    #[serde(default, rename = "rawValue")]
42    pub raw_value: Option<f64>,
43}
44
45#[derive(Debug, Clone, Serialize)]
46pub struct BooleanLiteral {
47    #[serde(flatten)]
48    pub base: BaseNode,
49    pub value: bool,
50}
51
52#[derive(Debug, Clone, Serialize)]
53pub struct NullLiteral {
54    #[serde(flatten)]
55    pub base: BaseNode,
56}
57
58#[derive(Debug, Clone, Serialize)]
59pub struct BigIntLiteral {
60    #[serde(flatten)]
61    pub base: BaseNode,
62    pub value: String,
63}
64
65#[derive(Debug, Clone, Serialize)]
66pub struct RegExpLiteral {
67    #[serde(flatten)]
68    pub base: BaseNode,
69    pub pattern: String,
70    pub flags: String,
71}
72
73#[derive(Debug, Clone, Serialize)]
74pub struct TemplateElement {
75    #[serde(flatten)]
76    pub base: BaseNode,
77    pub value: TemplateElementValue,
78    pub tail: bool,
79}
80
81#[derive(Debug, Clone, Serialize)]
82pub struct TemplateElementValue {
83    pub raw: String,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub cooked: Option<String>,
86}