macroforge_ts_syn 0.6.0

TypeScript syntax types for build-time macro code generation
Documentation
//! Class-related IR types for TypeScript class declarations.
//!
//! This module provides the intermediate representation for TypeScript classes,
//! including their fields, methods, and associated metadata.
//!
//! ## Example
//!
//! Given this TypeScript class:
//!
//! ```typescript
//! /** @derive(Debug, Clone) */
//! class User {
//!     public name: string;
//!     private age: number;
//!
//!     constructor(name: string, age: number) {
//!         this.name = name;
//!         this.age = age;
//!     }
//!
//!     greet(): string {
//!         return `Hello, ${this.name}!`;
//!     }
//! }
//! ```
//!
//! The resulting [`ClassIR`] would contain:
//! - `name`: `"User"`
//! - `fields`: Two [`FieldIR`] entries for `name` and `age`
//! - `methods`: Two [`MethodSigIR`] entries for `constructor` and `greet`

use serde::{Deserialize, Serialize};

use crate::abi::ir::TypeParamIR;
use crate::abi::ir::interface::InterfaceFieldIR;
use crate::abi::{DecoratorIR, SpanIR};

/// Intermediate representation of a TypeScript class declaration.
///
/// This struct captures all relevant information about a class that macro
/// authors typically need: the class name, its fields, methods, inheritance
/// chain, type parameters, and decorators.
///
/// # Fields
///
/// - `name` - The class identifier (e.g., `"User"`, `"MyComponent"`)
/// - `span` - Source span covering the entire class declaration
/// - `body_span` - Source span of just the class body (between `{` and `}`)
/// - `is_abstract` - Whether the class is declared as `abstract`
/// - `type_params` - Generic type parameters as declared (`T`, `U` for `class Foo<T, U>`)
/// - `heritage` - Extended/implemented types (e.g., `["BaseClass", "IEncodable"]`)
/// - `decorators` - Decorators applied to the class
/// - `fields` - Class properties/fields
/// - `methods` - Class methods and constructor
///
/// # Example
///
/// ```rust,no_run
/// use macroforge_ts_syn::ClassIR;
///
/// fn generate_debug(class: &ClassIR) -> String {
///     let mut output = format!("class {} {{\n", class.name);
///
///     // Generate debug output for each field
///     for field in &class.fields {
///         output.push_str(&format!("  {}: {},\n", field.name, field.ts_type));
///     }
///
///     output.push_str("}\n");
///     output
/// }
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct ClassIR {
    /// The class name (identifier).
    pub name: String,

    /// Source span covering the entire class declaration.
    pub span: SpanIR,

    /// Source span of the class body (between `{` and `}`).
    /// Useful for inserting generated methods inside the class.
    pub body_span: SpanIR,

    /// Whether this is an `abstract class`.
    pub is_abstract: bool,

    /// Whether this is a `declare class`, which describes a class the
    /// module does not hold and has no body for generated code.
    #[serde(default)]
    pub is_declare: bool,

    /// Generic type parameters as declared (`T extends Shape` for
    /// `class Foo<T extends Shape>`).
    pub type_params: Vec<TypeParamIR>,

    /// Heritage clauses - extended classes and implemented interfaces.
    /// For `class Foo extends Bar implements IBaz`, this would be `["Bar", "IBaz"]`.
    pub heritage: Vec<String>,

    /// The class this one extends, when it extends one named by an
    /// identifier: `Bar` for `class Foo extends Bar implements IBaz`. Its
    /// instances hold that class's fields as well as their own.
    #[serde(default)]
    pub superclass: Option<String>,

    /// Macro directives from the JSDoc comment above the class.
    pub decorators: Vec<DecoratorIR>,

    /// Class fields/properties.
    pub fields: Vec<FieldIR>,

    /// Class methods (including constructor).
    pub methods: Vec<MethodSigIR>,
}

impl ClassIR {
    /// Resets every source span, for comparing declarations by content.
    pub(crate) fn clear_spans(&mut self) {
        self.span = SpanIR::default();
        self.body_span = SpanIR::default();
        self.decorators
            .iter_mut()
            .for_each(DecoratorIR::clear_spans);
        self.fields.iter_mut().for_each(FieldIR::clear_spans);
        self.methods.iter_mut().for_each(MethodSigIR::clear_spans);
    }
}

/// How a member's key is written, which decides whether its `name` is one a
/// macro can read the member by.
#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MemberKey {
    /// A name: an identifier, or a string or whole-number literal.
    #[default]
    Named,
    /// A `#private` name, which only the class's own body reaches. The
    /// member's `name` keeps the `#`.
    Private,
    /// A key worked out as the code runs, or an index signature. The member's
    /// `name` is the key as written, brackets included: `[KEY]`,
    /// `[key: string]`.
    Unnamed,
}

/// Intermediate representation of a class field/property.
///
/// Represents a property declaration within a TypeScript class, including
/// its type annotation, modifiers, and any decorators.
///
/// # Example
///
/// For the TypeScript field:
///
/// ```typescript
/// /** @endec(skip) */
/// private readonly email?: string;
/// ```
///
/// The `FieldIR` would have:
/// - `name`: `"email"`
/// - `ts_type`: `"string"`
/// - `optional`: `true`
/// - `readonly`: `true`
/// - `visibility`: `Visibility::Private`
/// - `decorators`: Contains the `@endec(skip)` decorator
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct FieldIR {
    /// The field name (identifier).
    pub name: String,

    /// How the field's key is written.
    #[serde(default)]
    pub key: MemberKey,

    /// Source span of the field declaration.
    pub span: SpanIR,

    /// The field's type as a string (e.g., `"string"`, `"number[]"`, `"Map<K, V>"`):
    /// its annotation as written, else the type its initializer makes plain
    /// (`number` for `count = 0`), else `any`.
    pub ts_type: String,

    /// Whether the field is optional (`?`).
    pub optional: bool,

    /// Whether the field is marked `readonly`.
    pub readonly: bool,

    /// The access modifier (`public`, `protected`, or `private`).
    pub visibility: Visibility,

    /// Decorators applied to this field.
    pub decorators: Vec<DecoratorIR>,

    /// The initializer expression as written (`"dark"` for `theme = "dark"`).
    #[serde(default)]
    pub initializer: Option<String>,

    /// Whether the field is declared with `accessor`: its value is kept in a
    /// private slot behind a getter and a setter, which the class's
    /// constructor sets up.
    #[serde(default)]
    pub accessor: bool,

    /// Whether the declaration leaves the field's type unsaid: it has no
    /// annotation and no initializer whose type is plain, and `ts_type` is
    /// `any` for want of one.
    #[serde(default)]
    pub untyped: bool,
}

impl FieldIR {
    /// The field as the member an interface would declare for it, dropping
    /// what only a class says: visibility, initializer and accessor storage.
    pub fn as_interface_field(&self) -> InterfaceFieldIR {
        InterfaceFieldIR {
            name: self.name.clone(),
            key: self.key,
            span: self.span,
            ts_type: self.ts_type.clone(),
            optional: self.optional,
            readonly: self.readonly,
            decorators: self.decorators.clone(),
        }
    }

    /// Resets every source span, for comparing declarations by content.
    pub(crate) fn clear_spans(&mut self) {
        self.span = SpanIR::default();
        self.decorators
            .iter_mut()
            .for_each(DecoratorIR::clear_spans);
    }
}

/// Intermediate representation of a class method signature.
///
/// Captures the signature of a class method (including constructors) without
/// the method body. The signature components are stored as source strings
/// for easy code generation.
///
/// # Example
///
/// For the TypeScript method:
///
/// ```typescript
/// async fetchUser<T>(id: string): Promise<T> {
///     // ...
/// }
/// ```
///
/// The `MethodSigIR` would have:
/// - `name`: `"fetchUser"`
/// - `type_params`: `T`
/// - `params_src`: `"id: string"`
/// - `return_type_src`: `"Promise<T>"`
/// - `is_async`: `true`
/// - `is_static`: `false`
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct MethodSigIR {
    /// The method name (or `"constructor"` for constructors).
    pub name: String,

    /// Source span of the method declaration.
    pub span: SpanIR,

    /// Generic type parameters as declared (`T`, `U extends Foo`).
    pub type_params: Vec<TypeParamIR>,

    /// Method parameters as source string (e.g., `"name: string, age: number"`).
    pub params_src: String,

    /// Return type as source string (e.g., `"void"`, `"Promise<User>"`).
    /// Empty string if no explicit return type.
    pub return_type_src: String,

    /// Whether this is a static method.
    pub is_static: bool,

    /// Whether this is an async method.
    pub is_async: bool,

    /// The access modifier (`public`, `protected`, or `private`).
    pub visibility: Visibility,

    /// Decorators applied to this method.
    pub decorators: Vec<DecoratorIR>,

    /// Body span (between `{` and `}`). `None` for abstract or interface methods.
    #[serde(default)]
    pub body_span: Option<SpanIR>,

    /// Raw source of the body (between but not including the braces).
    /// `None` for abstract or interface methods.
    #[serde(default)]
    pub body_src: Option<String>,
}

impl MethodSigIR {
    /// Resets every source span, for comparing declarations by content.
    pub(crate) fn clear_spans(&mut self) {
        self.span = SpanIR::default();
        self.body_span = self.body_span.map(|_| SpanIR::default());
        self.decorators
            .iter_mut()
            .for_each(DecoratorIR::clear_spans);
    }
}

/// Access modifier for class members.
///
/// Represents the visibility level of a class field or method in TypeScript.
/// When no modifier is specified, TypeScript defaults to `public`.
///
/// # Examples
///
/// ```typescript
/// class Example {
///     public name: string;      // Visibility::Public
///     protected id: number;     // Visibility::Protected
///     private secret: string;   // Visibility::Private
///     age: number;              // Visibility::Public (implicit)
/// }
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum Visibility {
    /// Accessible from anywhere.
    Public,
    /// Accessible from the class and its subclasses.
    Protected,
    /// Accessible only within the class.
    Private,
}