# Compose Language Grammar (EBNF)

This document defines the formal grammar for Compose v0.2.0 using Extended Backus-Naur Form (EBNF).

---

## Notation

- `::=` — Definition
- `|` — Alternation (OR)
- `( )` — Grouping
- `[ ]` — Optional (0 or 1)
- `{ }` — Repetition (0 or more)
- `" "` — Terminal string
- `< >` — Non-terminal

---

## Grammar Rules

### Program Structure

```ebnf
<program> ::= { <statement> }

<statement> ::= <import_statement>
              | <comment>
              | <model_declaration>
              | <feature_declaration>
              | <guide_declaration>
```

### Comments

```ebnf
<comment> ::= "#" <text> <newline>
```

### Imports

```ebnf
<import_statement> ::= "import" <string_literal> <newline>

<string_literal> ::= '"' <text> '"'
```

### Model Declarations

```ebnf
<model_declaration> ::= "model" <identifier> ":" <newline>
                        <indent> { <field_definition> } <dedent>

<field_definition> ::= <identifier> ":" <field_type> <newline>

<field_type> ::= <type> [ <optional_marker> ]

<optional_marker> ::= "?"

<type> ::= <primitive_type>
         | <identifier>
         | "list" "of" <type>
         | <enum_type>

<primitive_type> ::= "text"
                   | "number"
                   | "bool"
                   | "date"
                   | "timestamp"
                   | "image"
                   | "file"
                   | "markdown"
                   | "json"

<enum_type> ::= <string_literal> { "|" <string_literal> }
```

### Feature Declarations

```ebnf
<feature_declaration> ::= "feature" <string_literal> ":" <newline>
                          <indent> { <feature_item> } <dedent>

<feature_item> ::= "-" <text> <newline>
                 | "-" <reference_code> <newline>

<reference_code> ::= "Reference:" "@" <file_path>
```

### Guide Declarations

```ebnf
<guide_declaration> ::= "guide" <string_literal> ":" <newline>
                        <indent> { <guide_item> } <dedent>

<guide_item> ::= "-" <text> <newline>
               | "-" <reference_code> <newline>
```

### Lexical Elements

```ebnf
<identifier> ::= <letter> { <letter> | <digit> | "_" }

<letter> ::= "a" | "b" | ... | "z" | "A" | "B" | ... | "Z"

<digit> ::= "0" | "1" | ... | "9"

<text> ::= { <any_character_except_newline> }

<file_path> ::= <path_segment> { "/" <path_segment> } [ <file_extension> ]

<path_segment> ::= <identifier> | "." | ".."

<file_extension> ::= "." <identifier>

<newline> ::= "\n" | "\r\n"

<indent> ::= <whitespace> { <whitespace> }

<dedent> ::= <end_of_indentation>
```

---

## Indentation Rules

Compose uses **significant indentation** (Python-style):

- Block contents are indented with **2 spaces** (recommended)
- Parent-child relationships are determined by indentation level
- Inconsistent indentation is a syntax error
- Indent/dedent tokens are emitted by the lexer

**Valid indentation:**
```compose
model User:
  name: text      # Indented 2 spaces
  email: text     # Same level
```

**Invalid indentation:**
```compose
model User:
   name: text     # 3 spaces - error!
  email: text     # 2 spaces - inconsistent!
```

---

## Complete Example

```compose
# Import shared models
import "models/shared.compose"

# Data model
model Customer:
  id: number
  name: text
  email: text
  role: "admin" | "member"
  tags: list of text
  avatar: image?

# Application behavior
feature "Customer Management":
  - Display customer list with search and filters
  - Create new customers with form validation
  - Edit existing customer details
  - Delete customers with confirmation dialog
  - Export customer list to CSV

# Implementation details
guide "Data Validation":
  - Email must match regex pattern
  - Name required, 2-50 characters
  - Role defaults to "member"

guide "UI/UX":
  - Use card layout for customer list
  - Add loading skeleton during data fetch
  - Show success/error toasts for actions

guide "Performance":
  - Paginate customer list (20 per page)
  - Debounce search input (300ms)
  - Cache customer data for 5 minutes
```

---

## Reference Code Syntax

The `@` operator references external code files:

```ebnf
<reference_syntax> ::= "@" <file_path> [ "::" <function_name> ]
```

**Examples:**

```compose
feature "Pricing Calculation":
  - Reference: @reference/pricing.py

guide "Tax Rules":
  - Reference: @reference/tax-calculator.py::calculate_tax
```

The referenced code is **translated** by the LLM into the target language, not directly imported.

---

## Type System

### Primitive Types

| Type | Description | Maps to |
|------|-------------|---------|
| `text` | String | string, str, String |
| `number` | Numeric | number, int/float, i32/f64 |
| `bool` | Boolean | boolean, bool, bool |
| `date` | Date only | Date, date, LocalDate |
| `timestamp` | Date + time | DateTime, datetime, Instant |
| `image` | Image file | File/URL | string (URL) |
| `file` | Generic file | File/URL | string (URL) |
| `markdown` | Markdown text | string | string |
| `json` | JSON data | object | dict/Map |

### Composite Types

**Lists:**
```compose
tags: list of text
items: list of Product
```

**Optional:**
```compose
avatar: image?
bio: text?
```

**Enums:**
```compose
status: "pending" | "approved" | "rejected"
role: "admin" | "member" | "guest"
```

**Model References:**
```compose
userId: User        # Reference to User model
items: list of Product
```

---

## Keywords

Reserved keywords (case-sensitive):

- `model` — Define data structure
- `feature` — Define application behavior
- `guide` — Define implementation hints
- `import` — Import other .compose files
- `list of` — List type modifier

**Type keywords:**
- `text`, `number`, `bool`, `date`, `timestamp`
- `image`, `file`, `markdown`, `json`

---

## Operators

| Operator | Meaning | Example |
|----------|---------|---------|
| `:` | Type annotation | `name: text` |
| `?` | Optional marker | `email: text?` |
| `\|` | Enum separator | `"a" \| "b"` |
| `@` | Reference code | `@reference/file.py` |
| `::` | Function reference | `@file.py::func` |

---

## Whitespace Rules

1. **Significant:** Indentation (must be consistent)
2. **Ignored:** Spaces between tokens (except indentation)
3. **Line terminators:** `\n` or `\r\n`

---

## Grammar Summary

**Three keywords:**
- `model` — Data ("WHAT we store")
- `feature` — Behavior ("WHAT the app does")
- `guide` — Hints ("HOW to implement")

**File structure:**
1. Optional imports
2. Models (data structures)
3. Features (requirements)
4. Guides (implementation details)

**Philosophy:**
- Minimal syntax
- Natural language descriptions
- LLM-friendly format
- Framework-agnostic specifications
