Home / spec / language-specification · 언어 명세
English first · 한국어 병렬 draft v0.1.0 2025
§ 0
Overview & Design Philosophy · 개요 및 설계 철학
English first · Korean parallel in overview; grammar sections use bilingual labels

Cell Coding is a programming paradigm inspired by cell theory in biology. The unit of every program is the cell — each with a distinct role, selective communication through the membrane, and organic connection via signals.

Cell Coding is designed as a transpiled DSL on top of existing languages (Python, TypeScript, Go, etc.). It does not start as a standalone language; it absorbs existing ecosystems and can be adopted incrementally.

세포코딩(Cell Coding)은 생물학의 세포 이론에서 영감을 받은 새로운 프로그래밍 패러다임이다. 모든 프로그램의 구성 단위는 세포(cell)이며, 세포는 고유한 역할을 가지고, 막(membrane)을 통해 외부와 선택적으로 통신하며, 신호(signal)를 통해 유기적으로 연결된다.

세포코딩은 기존 언어(Python, TypeScript, Go 등) 위에서 동작하는 트랜스파일 방식의 DSL로 설계된다. 독립 언어로 시작하지 않고 기존 생태계를 흡수하며 점진적으로 도입 가능하다.

Why now: Classical software evolved around a narrower input-process-output frame. In Physical AI systems, both sensing and acting become multimodal and continuous, so a single linear pipeline model becomes insufficient.

왜 지금 필요한가: 고전 소프트웨어는 상대적으로 좁은 입력-처리-출력 프레임을 중심으로 발전했다. 그러나 Physical AI 시스템에서는 감지와 행동이 모두 다중 모달·연속 흐름으로 확장되므로, 단일 선형 파이프라인 모델만으로는 한계가 드러난다.

Functional cell definition: Cell Coding treats software as a collaboration network of functional cells. Each cell owns one role, is guarded by membrane contracts, and cooperates with others only through signals.

기능 세포 정의: Cell Coding은 소프트웨어를 기능 세포들의 협업 네트워크로 본다. 각 세포는 하나의 역할을 담당하고, 막 계약으로 경계를 유지하며, 다른 세포와는 신호를 통해서만 협업한다.

Physical AI scenarios: A spider robot adapts sensing and actuation to terrain; a humanoid coordinates balance, manipulation, and interaction organs; a companion PET robot maintains continuous affect and safety cells in home contexts. Each case maps to role-membrane-signal cooperation, not a linear I/O pipeline.

Physical AI 시나리오: 거미 로봇은 지형에 적응하는 감각·행동 세포를, 휴머노이드는 균형·조작·상호작용 기관의 협업을, 반려(PET) 로봇은 가정 환경에서 정서·안전 세포의 지속 상호작용을 보여준다. 각 사례는 선형 I/O 파이프라인이 아니라 역할-막-신호 협업으로 매핑된다.

Concept overview diagram: See the integrated 4-level process architecture at concept-overview.html (Modeling/Coding/Interworking → Sense/Decide/Act lanes → functional pairs → component cells).

개념 구조 다이어그램: 통합 4단계 프로세스 구조는 concept-overview.html 참고 (모델링/코딩/연동 → 감각/판단/행동 레인 → 기능 쌍 → 구성 세포).

Diagram level · 단계Spec term · 명세 용어
Level 0: Modeling · Coding · Interworkinggenomecellnervous
Level 1: Input / Process / Output lanestissue (Sense · Decide · Act)
Level 2: Functional pairscell roles within tissue
Level 3: Component cellsmembrane + signal contracts
📐 Core philosophy · 핵심 철학 A cell declares its role rather than hiding state; it reacts to signals rather than calling other cells; it must be able to survive on its own and, collectively, form an organism.
세포는 상태를 숨기는 것이 아니라 역할을 선언한다. 세포는 다른 세포를 호출하는 것이 아니라 신호에 반응한다. 세포는 단독으로 살아남을 수 있어야 하며, 집합적으로 유기체를 이룬다.

Design Goals · 설계 목표

Goal · 목표Description · 설명Metric · 측정 기준
Independence · 독립성Each cell is unaware of other cells' internals · 각 세포는 다른 세포의 내부 구현을 알지 못한다Cell testable in isolation · 세포 단독 테스트 가능 여부
Role clarity · 역할 명확성A cell's role is declaratively readable from outside the code · 세포의 역할이 코드 외부에서 선언적으로 읽힌다role field required · role 필드 필수화
Organic connection · 유기적 연결Cells communicate only through signals and membranes · 세포 간 통신은 신호와 막을 통해서만 이루어진다No direct references · 직접 참조 금지
Complexity tiers · 복잡도 계층System complexity maps naturally onto biological tiers · 시스템 복잡도가 생물학적 계층으로 자연스럽게 표현된다cell/tissue/organ/organism split · 계층 구분
Interoperability · 상호운용성Coexists with existing language codebases · 기존 언어 코드베이스와 공존할 수 있다Transpile support · 트랜스파일 지원

§ 1
Keyword Index · 키워드 인덱스
Reserved Keywords

Every reserved keyword in Cell Coding is grounded in a biological term. The 16 core keywords below form the backbone of the language; structural keywords (flow, when, query, from, with, etc.) are introduced in context.

세포코딩의 모든 예약어(reserved keyword)는 생물학적 용어를 기반으로 한다. 아래 16개의 핵심 키워드가 언어의 골격을 이루며, 구조 키워드(flow, when, query, from, with 등)는 문맥에서 함께 소개된다.

cell
UNIT · 세포
Smallest unit of composition; holds exactly one role. · 모든 구성의 최소 단위. 단 하나의 역할을 가진다.
tissue
COMPOSITION · 조직
Linear/parallel cluster of cells with a shared purpose. · 같은 목적을 가진 세포들의 선형/병렬 클러스터.
organ
COMPOSITION · 기관
Unit where multiple tissues cooperate for one function. · 여러 조직이 하나의 기능을 위해 협력하는 단위.
organism
COMPOSITION · 유기체
The whole system; top-level container of organs. · 전체 시스템. 기관들의 최상위 컨테이너.
signal
COMMUNICATION · 신호
The only means of inter-cell communication; immutable. · 세포 간 유일한 통신 수단. 불변(immutable)이다.
membrane
INTERFACE · 막
A cell's I/O contract; defines accepted/emitted signals. · 세포의 입출력 계약. 수용·방출 신호를 정의한다.
genome
TEMPLATE · 유전자
Reusable cell blueprint; a generic template. · 재사용 가능한 세포 설계도. 제네릭 템플릿.
nervous
SYSTEM · 신경계
Event bus that relays signals between organs. · 기관 간 신호를 중계하는 이벤트 버스.
immune
SYSTEM · 면역계
Quarantines faulty cells and protects the system. · 오류 세포를 격리하고 시스템을 보호한다.
on
HANDLER · 반응
Declares logic to run when a given signal arrives. · 특정 신호를 수신했을 때 실행할 로직 선언.
emit
ACTION · 방출
Sends a signal outward; it is not a return value. · 신호를 외부로 발송한다. 반환값이 아니다.
absorb
ACTION · 흡수
Consumes a signal so it propagates no further. · 신호를 소비하여 더 이상 전파되지 않게 한다.
divide
OPERATION · 분열
Dynamically replicates/parallelizes a cell. · 세포를 동적으로 복제·병렬화한다.
mutate
OPERATION · 변이
Redefines a cell's role or membrane at runtime. · 세포의 역할이나 막을 런타임에 재정의한다.
apoptosis
LIFECYCLE · 세포사멸
Voluntary cell termination and resource release. · 세포의 자발적 종료 및 자원 해제.
role
METADATA · 역할
Required attribute declaring a cell's job in natural language. · 세포가 하는 일을 자연어로 선언하는 필수 속성.

§ 2
cell — 세포
The Fundamental Unit

A cell is the smallest independent unit in Cell Coding. It must declare a role, communicates with the outside through its membrane, and reacts to signals via on handlers. A cell cannot directly reference or call another cell.

cell은 세포코딩의 가장 작은 독립 단위다. 세포는 반드시 role을 가져야 하며, membrane을 통해 외부와 통신하고, on 핸들러로 신호에 반응한다. 세포는 다른 세포를 직접 참조하거나 호출할 수 없다.

📏 Invariants · 불변 규칙 ① A cell must declare a role. ② A cell cannot emit signals not declared in its membrane. ③ A cell cannot import or directly call another cell.
① 세포는 반드시 role 을 선언해야 한다. ② 세포는 membrane 에 선언되지 않은 신호를 emit할 수 없다. ③ 세포는 다른 세포를 import하거나 직접 호출할 수 없다.

Anatomy · 해부 구조

cell-code anatomy.cell
// ── Full anatomy of a cell · 세포의 완전한 해부 구조 ──────

cell EmailValidator {

  // [required] role — natural language, the reason this cell exists · 역할 선언
  role     : "Validate the format and domain of an email address"

  // [optional] tags — metadata for search/classification · 검색·분류용 메타데이터
  tags     : ["validation", "auth", "input"]

  // [optional] lifespan — the cell's lifetime policy · 수명 정책
  lifespan : stateless   // stateless | persistent | session

  // [required] membrane — the I/O contract · 입출력 계약
  membrane {
    accepts: RawEmailInput
    emits  : ValidEmail | InvalidEmail
    rejects: NullInput    // this signal is not let through · 통과 불가
  }

  // [optional] internal state — only valid when lifespan is persistent · 내부 상태
  nucleus {
    cache: Map<String, Bool>
  }

  // [required] signal handler · 신호 핸들러
  on (RawEmailInput input) {
    if isValidFormat(input.address) && domainExists(input.address) {
      emit ValidEmail(address: input.address)
    } else {
      emit InvalidEmail(reason: "Invalid format or domain mismatch")
    }
  }

  // [optional] apoptosis hook · 세포 사멸 훅
  apoptosis {
    clearCache(nucleus.cache)
  }
}

Membrane · 막

The membrane is a cell's I/O contract. Only signals declared in the membrane may pass through the cell. The membrane is the cell's public API and its only interface.

막은 세포의 입출력 계약이다. 막에 선언된 신호만이 세포를 관통할 수 있다. 막은 세포의 공개 API이자 유일한 인터페이스다.

Keyword · 키워드Meaning · 의미Example · 예시
acceptsActivates the cell when this signal arrives · 이 신호가 올 때 세포가 활성화된다accepts: LoginRequest
emitsSignals the cell may emit after processing · 처리 후 방출할 수 있는 신호emits: TokenIssued | AuthFailed
rejectsExplicitly blocks this signal · 이 신호는 명시적으로 차단한다rejects: GuestRequest
observesDoes not react but senses/logs it · 반응하지 않고 감지·로깅한다observes: AnySignal
passthroughForwards the signal unchanged · 변환 없이 그대로 전달한다passthrough: HealthCheck

Cell Lifecycle · 세포 생존 주기

🌱
genesis
Created
세포 생성·초기화
👁
dormant
Awaiting
신호 대기
active
Processing
신호 수신·처리
📡
emitting
Emitting
신호 방출·전파
💤
dormant
Waiting
다음 신호 대기
🌸
apoptosis
Terminated
세포 사멸·자원 해제

§ 3
signal — 신호
The Communication Primitive

A signal is the only means of communication between cells. Signals are immutable and cannot be modified after creation. A signal carries data but does not command behavior — what a receiving cell does with it is entirely that cell's responsibility.

신호는 세포 간 유일한 통신 수단이다. 신호는 불변(immutable)이며, 생성 후 수정될 수 없다. 신호는 데이터를 운반하지만 행동을 명령하지 않는다. 어떤 세포가 신호를 받아 무엇을 할지는 전적으로 수신 세포의 책임이다.

💡 Message vs Signal · 메시지 vs 신호 An OOP message knows its receiver. A Cell Coding signal does not. A signal is released into the air, and only interested cells react — this fundamentally lowers coupling.
OOP의 메시지는 수신자를 알고 있다. 세포코딩의 신호는 수신자를 모른다. 신호는 공기 중에 방출되고, 관심 있는 세포들이 반응할 뿐이다. 이것이 결합도를 근본적으로 낮춘다.

Signal Types · 신호 유형

cell-code signals.cell
// ── Signal definitions · 신호 정의 ───────────────────────

// 1. Data signal (most common) — carries immutable data · 데이터 신호
signal UserRegistered {
  userId   : UUID
  email    : Email
  createdAt: Timestamp
}

// 2. Error signal — detected by the immune system · 에러 신호
signal DatabaseError extends ErrorSignal {
  code     : Int
  message  : String
  retryable: Bool
}

// 3. Empty signal — its mere existence is the meaning · 빈 신호
signal SessionExpired   // no data, only the fact it occurred · 발생 사실만 전달
signal HealthCheckPing  // health check request · 상태 확인 요청

// 4. Generic signal — used with a genome · 제네릭 신호
signal Paginated<T> {
  items  : List<T>
  total  : Int
  page   : Int
  hasMore: Bool
}

// 5. Priority signal — nervous system decides processing order · 우선순위 신호
signal PaymentFailed priority: critical {
  orderId : UUID
  amount  : Money
  reason  : String
}

Signal Routing Rules · 신호 라우팅 규칙

Rule · 규칙Description · 설명Exception · 예외
broadcast-firstBy default a signal propagates to all interested cells · 모든 관심 세포에 전파된다Can be stopped with absorb · absorb로 중단
immutabilityA signal cannot change during propagation · 전파 중 변경될 수 없다None (absolutely immutable) · 없음
no-replyA signal expects no response · 응답을 기대하지 않는다query pattern · query 패턴 예외
priority-orderProcessed critical > high > normal > low · 우선순위 순으로 처리Override via nervous · nervous 설정으로 오버라이드
type-safetyNot delivered if it mismatches the membrane type · 타입 불일치 시 전달 안 됨AnySignal wildcard · 와일드카드
cell-code signal-routing.cell
// ── Signal flow patterns · 신호 흐름 패턴 ────────────────

// Pattern 1: Pipeline (A → B → C) · 파이프라인
cell Parser {
  membrane { accepts: RawInput; emits: ParsedData }
  on(RawInput raw) { emit ParsedData(parse(raw)) }
}

// Pattern 2: Fan-out (one signal → many cells) · 분기
cell OrderCompleted_EmailNotifier {
  membrane { accepts: OrderCompleted; emits: EmailSent }
  on(OrderCompleted e) { emit EmailSent(to: e.userEmail) }
}

cell OrderCompleted_StockReducer {
  membrane { accepts: OrderCompleted; emits: StockUpdated }
  on(OrderCompleted e) { emit StockUpdated(sku: e.sku) }
}

// Pattern 3: Absorb (stop signal propagation) · 흡수
cell RateLimiter {
  membrane { accepts: ApiRequest; emits: TooManyRequests }
  on(ApiRequest req) {
    if exceeded(req.clientId) {
      absorb   // stop propagation — never reaches the next cell · 전파 중단
      emit TooManyRequests(clientId: req.clientId)
    }
  }
}

// Pattern 4: Query (a special signal that awaits a reply) · 질의
cell UserFinder {
  membrane {
    accepts: FindUser query       // query keyword: awaits a response signal · 응답 신호 대기
    emits  : UserFound | UserNotFound
  }
  on(FindUser q) {
    let user = db.find(q.userId)
    user ? emit UserFound(user) : emit UserNotFound
  }
}

§ 4
tissue — 조직
Ordered Cell Clusters

A tissue is a bundle of cells sharing the same purpose. Cells within a tissue are connected by linear, parallel, or conditional flows. A tissue has its own membrane, so from the outside it looks like a single cell.

tissue는 같은 목적을 가진 세포들의 묶음이다. 조직 내 세포들은 선형(linear), 병렬(parallel), 또는 조건부(conditional) 흐름으로 연결된다. 조직은 그 자체가 하나의 막을 가져 외부에서는 단일 세포처럼 보인다.

cell-code auth-tissue.cell
// ── Tissue: authentication pipeline · 인증 파이프라인 ─────

tissue AuthPipeline {

  // the tissue's external contract · 외부 계약
  membrane {
    accepts: LoginRequest
    emits  : SessionCreated | AuthDenied
  }

  // linear flow: run in order · 선형 흐름
  flow linear {
    InputSanitizer    // 1. sanitize input · 입력 정제
     CredentialChecker // 2. check credentials · 자격 확인
     TokenIssuer       // 3. issue token · 토큰 발급
     SessionCreator    // 4. create session · 세션 생성
  }

  // conditional branch · 조건부 분기
  when (AuthDenied) {
    AuditLogger     // audit log on failure · 실패 시 감사 로그
    BruteForceGuard // brute-force detection · 브루트포스 감지
  }
}

// ── Parallel tissue · 병렬 조직 ──────────────────────────
tissue OrderNotifications {

  membrane {
    accepts: OrderCompleted
    emits  : AllNotified
  }

  // parallel flow: run together, emit after all complete · 병렬 흐름
  flow parallel {
    EmailNotifier
    SmsNotifier
    PushNotifier
    SlackNotifier
  }

  after all {
    emit AllNotified
  }
}

§ 5
organ — 기관
Functional System Unit

An organ is a unit where multiple tissues cooperate to handle one domain function. An organ has its own signal namespace; signals inside an organ do not automatically propagate outside it. Inter-organ communication is possible only through the nervous system.

organ은 여러 조직이 협력하여 하나의 도메인 기능을 담당하는 단위다. 기관은 독립적인 신호 공간(signal namespace)을 가지며, 기관 내부의 신호는 기관 밖으로 자동 전파되지 않는다. 기관 간 통신은 nervous를 통해서만 가능하다.

cell-code user-organ.cell
organ UserOrgan {

  // the organ's external contract · 기관의 외부 계약
  membrane {
    accepts: LoginRequest | RegisterRequest | ProfileUpdateRequest
    emits  : UserEvent    // the organ's external signal type · 외부 신호 타입
  }

  // internal tissue composition · 내부 조직 구성
  tissues {
    AuthPipeline     // authentication · 인증 처리
    RegistrationFlow // sign-up · 회원가입 처리
    ProfileManager   // profile management · 프로필 관리
  }

  // signals the organ exposes (the rest stay isolated) · 외부 공개 신호
  exports {
    UserRegistered
    UserLoggedIn
    UserDeleted
  }

  // organ-level state (shared by all tissues) · 기관 수준 공유 상태
  shared {
    userRepository: UserRepository
    auditLog       : AuditLogger
  }
}

§ 6
organism — 유기체
The Complete System

An organism is the top-level container of the whole system. It defines the list of organs, the nervous system (event bus), the immune system (error handler), and the environment configuration.

organism은 전체 시스템의 최상위 컨테이너다. 유기체는 기관들의 목록, 신경계(eventbus), 면역계(error handler), 그리고 환경(environment) 설정을 정의한다.

cell-code app.organism
organism ECommerceApp {

  // ① organ list · 기관 목록
  organs {
    UserOrgan
    ProductOrgan
    OrderOrgan
    PaymentOrgan
    NotificationOrgan
  }

  // ② nervous — inter-organ signal routing · 신경계
  nervous EventBus {
    // declare which signal flows to which organ · 신호 흐름 명시
    UserOrgan.UserRegistered     NotificationOrgan
    OrderOrgan.OrderPlaced        [PaymentOrgan, ProductOrgan]
    PaymentOrgan.PaymentConfirmed  [OrderOrgan, NotificationOrgan]
    PaymentOrgan.PaymentFailed     [OrderOrgan, NotificationOrgan]
  }

  // ③ immune — error-handling strategy (block form, canonical EBNF) · 면역계
  immune ErrorPolicy {
    on DatabaseError {
      strategy: retry
      retries : 3
      backoff : exponential
    }
    on NetworkTimeout {
      strategy: fallback
    }
    on UnknownError {
      strategy: isolate
      escalate: true
    }
  }

  // ④ environment configuration · 환경 설정
  environment {
    runtime  : "node:20"
    transport: "redis"    // actual transport layer for nervous · 전송 계층
    scale    : auto        // automatic cell division/scaling · 자동 분열·스케일링
    observe  : "opentelemetry"
  }
}

§ 7
nervous — 신경계
Inter-organ Signal Bus

The nervous system governs the flow of signals between organs. Without it, organs are completely isolated islands. Because the nervous system owns the wiring, the organs themselves need to know nothing about routing.

신경계는 기관 간 신호의 흐름을 관장한다. 신경계 없이 기관은 완전히 격리된 섬이다. 신경계가 배선(wiring)을 담당함으로써 기관 자체는 라우팅에 대해 전혀 알 필요가 없다.

cell-code nervous-system.cell
nervous AppNervousSystem {

  // basic routing · 기본 라우팅
  UserOrgan.UserBanned  OrderOrgan  // simple forward · 단순 전달

  // transform routing — convert then forward · 변환 라우팅
  PaymentOrgan.PaymentConfirmed
     transform(p) { OrderApproved(orderId: p.orderId) }
     OrderOrgan

  // conditional routing · 조건부 라우팅
  OrderOrgan.OrderPlaced
     when (o.amount > 1000000)  FraudDetectionOrgan
     always                     PaymentOrgan

  // signal aggregation — fires only when all signals arrive · 신호 집계
  aggregate {
    wait: [PaymentConfirmed, InventoryReserved]
    emit: ReadyToShip
    timeout: 30s  FulfillmentFailed
  }
}

§ 8
immune — 면역계
System-wide Error Policy

The immune system detects abnormal cells (those raising errors), quarantines them, and protects the system so it keeps surviving. Each organ may have its own immune policy, and a global policy is defined at the organism level.

면역계는 이상 세포(오류 발생 세포)를 감지하고, 격리하며, 시스템이 계속 생존할 수 있도록 보호한다. 각 기관이 자체 면역 정책을 가질 수 있고, organism 레벨에서 전역 정책을 정의한다.

cell-code immune.cell
immune GlobalPolicy {

  // strategy per error type · 오류 유형별 대응 전략
  on DatabaseError {
    strategy: retry(attempts: 3, backoff: exponential)
    fallback: useCache
    escalate: after 3 failures
  }

  on MemoryExceeded {
    strategy: quarantine   // isolate cell, block signals · 세포 격리
    recover : divide        // split load to new cells · 부하 분산 분열
  }

  on UnhandledSignal {
    strategy: deadLetter   // store undeliverable signals · 처리 불가 신호 보관
    alert   : true
  }

  // Circuit Breaker · 회로 차단기
  circuit {
    threshold  : 5 failures in 60s
    open       : 30s   // break duration · 차단 시간
    halfOpen   : 1 probe  // recovery probe · 회복 탐침
  }
}

§ 9
genome — 유전자
Cell Templates & Generics

A genome is a reusable cell blueprint. It is specialized by type parameters — similar to an OOP generic class or a Rust trait, but designed around roles.

genome은 재사용 가능한 세포 설계도다. 타입 파라미터를 받아 구체화되며, OOP의 제네릭 클래스나 Rust의 트레이트와 유사하지만 역할 중심으로 설계된다.

cell-code genome.cell
// ── Genome: reusable cell template · 재사용 가능한 세포 템플릿 ──

genome CrudCell<Entity, CreateCmd, UpdateCmd> {
  membrane {
    accepts: CreateCmd | UpdateCmd | DeleteCmd<Entity>
    emits  : Created<Entity> | Updated<Entity> | Deleted<Entity>
  }

  on(CreateCmd cmd) { emit Created<Entity>(persist(cmd)) }
  on(UpdateCmd cmd) { emit Updated<Entity>(merge(cmd)) }
  on(DeleteCmd<Entity> cmd) { emit Deleted<Entity>(cmd.id) }
}

// instantiate the genome — create concrete cells · genome 인스턴스화
cell ProductCell from CrudCell<Product, CreateProduct, UpdateProduct>
cell UserCell    from CrudCell<User,    CreateUser,    UpdateUser>

// ── Behavioral genome (used like an interface) · 행동 Genome ──
genome Retryable {
  maxRetries: Int = 3
  backoff   : BackoffStrategy = exponential

  on ErrorSignal {
    if retries < maxRetries { retry }
    else { emit Exhausted }
  }
}

// mix a genome into a cell · 세포에 genome 믹스인
cell PaymentProcessor with Retryable {
  role: "Process payments and auto-retry"
  membrane {
    accepts: ProcessPayment
    emits  : PaymentSuccess | PaymentFailed
  }
  // Retryable's retry logic is injected automatically · 재시도 로직 자동 주입
}

§ 10
Mutation & Differentiation · 변이 및 분화
Runtime Adaptation

Cells can divide or mutate at runtime. This is the mechanism that supports scaling, A/B testing, rolling deployments, and feature flags at the language level.

세포는 런타임에 분열(divide)하거나 변이(mutate)할 수 있다. 이는 스케일링, A/B 테스트, 롤링 배포, 기능 플래그를 언어 수준에서 지원하는 메커니즘이다.

cell-code mutation.cell
// ── Cell division — horizontal scaling · 세포 분열 ───────
cell ImageProcessor {
  role: "Resize and compress images"
  lifespan: stateless

  // auto-divide under load · 부하에 따라 자동 분열
  divide when (queue.depth > 100) {
    max     : 16         // up to 16 replicas · 최대 16개 복제
    strategy: round-robin
  }

  membrane { accepts: ImageTask; emits: ImageReady }
  on(ImageTask t) { emit ImageReady(process(t)) }
}

// ── Cell mutation — A/B test / feature flag · 세포 변이 ───
cell RecommendationEngine {
  role: "Product recommendation algorithm"

  // mutate the algorithm based on an env variable · 환경 변수에 따라 변이
  mutate when (env.feature.mlRecommend == true) {
    role: "ML-based personalized recommendation"
    membrane { accepts: UserContext; emits: MLRecommendations }
    on(UserContext u) { emit MLRecommendations(mlModel.predict(u)) }
  }

  // default behavior (when the mutate condition is not met) · 기본 동작
  membrane { accepts: UserContext; emits: BasicRecommendations }
  on(UserContext u) { emit BasicRecommendations(rule.apply(u)) }
}

§ 11
Type System · 타입 시스템
Signal-Centric Types

Cell Coding's type system is signal-centric. The compatibility of signal types determines whether membranes can connect. Type inference is supported, but membrane declarations require explicit types.

세포코딩의 타입 시스템은 신호 중심으로 설계된다. 신호 타입의 호환성이 막의 연결 가능성을 결정한다. 타입 추론을 지원하지만 막 선언은 명시적 타입이 필수다.

Primitive Types · 기본 타입

Int Float String Bool UUID Timestamp Money Email URL List<T> Map<K,V> Option<T> Result<T,E> AnySignal ErrorSignal NullSignal

Type Compatibility Rules · 타입 호환성 규칙

Rule · 규칙Description · 설명
structuralCompatibility judged by structure, not name (structural subtyping) · 구조로 호환성 판단
signal unionA | B means it accepts signal A or B · A 또는 B 신호를 수용
signal extendsA subtype signal is also delivered to membranes accepting its supertype · 상위 타입 막에도 전달
AnySignalAccepts any signal (use with observes, avoid in accepts) · 모든 신호 수용
NullSignalNo signal; used on reject or a missed conditional emit · 신호 없음

§ 12
Formal Grammar (EBNF) · 공식 문법
Extended Backus-Naur Form

The official Extended Backus-Naur Form grammar of the Cell Coding language. Parsers and compilers are implemented on top of this grammar.

세포코딩 언어의 공식 Extended Backus-Naur Form 문법이다. 이 문법을 기반으로 파서와 컴파일러가 구현된다.

program ::= statement+ statement ::= signalDecl | cellDecl | tissueDecl | organDecl | organismDecl | genomeDecl signalDecl ::= "signal" TypeName ["extends" TypeName] ["priority" ":" priorityLevel] ["{" fieldList "}"] cellDecl ::= "cell" TypeName ["from" TypeName genericArgs] ["with" TypeName ("," TypeName)*] "{" cellBody "}" cellBody ::= roleDecl tagsDecl lifespanDecl membraneDecl nucleusDecl handlerDecl+ apoptosisDecl divideDecl mutateDecl membraneDecl ::= "membrane" "{" "accepts" ":" signalType ["query"] "emits" ":" signalType ("|" signalType)* "rejects" ":" signalType "observes" ":" signalType "passthrough" ":" signalType "}" handlerDecl ::= "on" "(" TypeName identifier ")" "{" stmtList "}" emitStmt ::= "emit" TypeName ["(" argList ")"] absorbStmt ::= "absorb" tissueDecl ::= "tissue" TypeName "{" membraneDecl flowDecl whenBlock* "}" flowDecl ::= "flow" ["linear" | "parallel" | "race"] "{" TypeName ("->" TypeName)* "}" genomeDecl ::= "genome" TypeName genericParams "{" cellBody "}" priorityLevel ::= "critical" | "high" | "normal" | "low" lifespanVal ::= "stateless" | "persistent" | "session"

§ 13
Interoperability · 상호운용성
Coexistence with Existing Languages

Cell Coding coexists with existing languages. A transpiler converts .cell files into the target language, and an adapter pattern lets you wrap existing code as cells.

세포코딩은 기존 언어와 공존한다. 트랜스파일러가 .cell 파일을 대상 언어로 변환하며, 기존 코드를 세포로 래핑하는 어댑터 패턴을 지원한다.

Python
🐍
@cell decorator · 데코레이터
TypeScript
🔷
Auto-generated type defs · 타입 정의 자동 생성
Go
🐹
Interface mapping · 인터페이스 매핑
Rust
🦀
Trait conversion · 트레이트 변환
Kubernetes
☸️
organ → service mapping · 서비스 매핑
WASM
🌐
Run cells in browser · 브라우저 세포 실행
python cell_compat.py — Python adapter example · 어댑터 예시
from cellcoding import cell, membrane, signal, emit

# wrap an existing Python function as a cell · 기존 함수를 세포로 래핑
@cell(
    role="Validate user email",
    accepts="RawEmailInput",
    emits=["ValidEmail", "InvalidEmail"]
)
def email_validator(input_signal):
    if is_valid_email(input_signal.address):
        return emit("ValidEmail", address=input_signal.address)
    return emit("InvalidEmail", reason="format error")
⚠️ Draft Notice · 초안 안내 This document is a draft (v0.1-draft). The transpiler implementation, IDE plugins, and runtime libraries are managed in separate spec documents. Keywords and grammar may change during implementation.
이 문서는 초안(v0.1-draft)이다. 트랜스파일러 구현, IDE 플러그인, 런타임 라이브러리는 별도 스펙 문서로 관리된다. 키워드와 문법은 구현 과정에서 변경될 수 있다.