# Species

Species define the fundamental ontological categories of beings in your world. A species represents what a character or entity *is* at its core—human, dragon, sentient tree, animated playing card. Unlike templates (which provide compositional trait sets), species provide singular, essential identity.

## Syntax

```bnf
<species-decl> ::= "species" <identifier> <includes-clause>? <body>

<includes-clause> ::= "includes" <qualified-path> ("," <qualified-path>)*

<body> ::= "{" <species-body-item>* "}"

<species-body-item> ::= <field>
                      | <prose-block>

<field> ::= <identifier> ":" <value>

<prose-block> ::= "---" <identifier> <content> "---"
```

## Components

### Name
The species identifier. Must be unique within its module and follow standard identifier rules.

**Naming conventions:**
- Use PascalCase: `Human`, `Dragon`, `PlayingCardPerson`
- Be specific: `BakeryCat` vs. generic `Cat` if varieties exist
- Avoid abbreviations: `ElderDragon` not `EldDrgn`

### Includes Clause (Optional)
Species can include other species to inherit their fields. This enables species composition without deep hierarchies.

```storybook
species Mammal {
    warm_blooded: true
    has_fur: true
}

species Carnivore includes Mammal {
    diet: "meat"
    has_claws: true
}

species Feline includes Carnivore {
    retractable_claws: true
    purrs: true
}
```

**Semantics:**
- **Multiple includes**: `species X includes A, B, C`
- **Resolution order**: Left-to-right (later overrides earlier)
- **Transitive**: Including `Feline` also brings in `Carnivore` and `Mammal`
- **No circular includes**: Compiler rejects circular dependencies

### Fields
Species fields define the default attributes shared by all members of that species.

**Common field categories:**
- **Biological**: `lifespan`, `reproductive_cycle`, `diet`
- **Physical**: `has_fur`, `warm_blooded`, `can_fly`
- **Cognitive**: `sapience_level`, `intelligence_range`
- **Special abilities**: `can_vanish`, `breathes_fire`, `regenerates`

All [value types](./18-value-types.md) are supported. Unlike templates, species fields should use concrete values rather than ranges (templates handle variation).

### Prose Blocks
Species can include narrative descriptions. Common tags:

- `---description`: What this species is and how it behaves
- `---ecology`: Habitat, diet, lifecycle
- `---culture`: Social structures (if sapient)
- `---notes`: Design notes or inspirations

## Species vs. Templates

Understanding the distinction is crucial for effective modeling:

| Aspect | Species (`:`) | Templates (`from`) |
|--------|--------------|-------------------|
| **Question** | "What *is* it?" | "What *traits* does it have?" |
| **Cardinality** | One per character | Zero or more |
| **Inheritance** | `includes` (species from species) | Characters inherit from templates |
| **Variation** | Concrete defaults | Ranges allowed |
| **Example** | `species Human` | `template Warrior` |
| **Override** | Characters can override | Characters can override |

**When to use species:**
```storybook
species Dragon {
    lifespan: 1000
    can_fly: true
    breathes_fire: true
}

character Smaug: Dragon {
    // Smaug IS a Dragon
    age: 850
}
```

**When to use templates:**
```storybook
template Hoarder {
    treasure_value: 0..1000000
    greed_level: 0.5..1.0
}

character Smaug: Dragon from Hoarder {
    // Smaug HAS hoarder traits
    greed_level: 0.95
}
```

## Field Resolution with Includes

When a species includes other species, fields are merged in declaration order:

1. **Base species** (leftmost in `includes`)
2. **Middle species** (middle in `includes`)
3. **Rightmost species** (rightmost in `includes`)
4. **Current species fields** (highest priority)

Example:
```storybook
species Aquatic {
    breathes_underwater: true
    speed_in_water: 2.0
}

species Reptile {
    cold_blooded: true
    speed_in_water: 1.0
}

species SeaTurtle includes Aquatic, Reptile {
    has_shell: true
    speed_in_water: 1.5  // Overrides both Aquatic and Reptile
}

// Resolved fields:
// breathes_underwater: true  (from Aquatic)
// cold_blooded: true         (from Reptile)
// speed_in_water: 1.5        (SeaTurtle overrides Reptile overrides Aquatic)
// has_shell: true            (from SeaTurtle)
```

## Validation Rules

1. **Unique names**: Species names must be unique within their module
2. **No circular includes**: Cannot form include cycles (compile-time error)
3. **Includes exist**: All included species must be defined
4. **Field type consistency**: Field values must be well-typed
5. **Reserved keywords**: Cannot use reserved keywords as field names
6. **Prose tag uniqueness**: Each prose tag can appear at most once per species

## Examples

### Simple Species
```storybook
species Human {
    lifespan: 70

    ---description
    Bipedal mammals with complex language and tool use.
    Highly variable in cultures and capabilities.
    ---
}
```

### Species with Includes
```storybook
species Mammal {
    warm_blooded: true
    has_fur: true
    reproductive_cycle: "live_birth"
}

species Primate includes Mammal {
    opposable_thumbs: true
    sapience_potential: 0.5..1.0
}

species Human includes Primate {
    sapience_potential: 1.0
    language_complexity: "high"

    ---description
    Highly intelligent primates with advanced tool use,
    complex social structures, and symbolic communication.
    ---
}
```

### Domestic Species
```storybook
species Cat {
    lifespan: 15

    ---description
    Domestic cats often found in bakeries and shops for pest
    control and companionship. Independent and territorial.
    ---
}

species Dog {
    lifespan: 12

    ---description
    Loyal companion animals. Some breeds are working dogs
    found on farms and in family households.
    ---
}
```

### Fantasy Species Hierarchy
```storybook
species Draconic {
    lifespan: 1000
    magic_affinity: true
    scales: true

    ---description
    Ancient lineage of magical reptilian beings.
    ---
}

species Dragon includes Draconic {
    can_fly: true
    breathes_fire: true
    hoard_instinct: 0.8

    ---description
    The apex predators of the sky. Territorial, intelligent,
    and obsessed with collecting treasure.
    ---
}

species Drake includes Draconic {
    can_fly: false
    breathes_fire: false
    pack_hunting: true

    ---description
    Smaller, land-bound cousins of true dragons. Hunt in packs
    and lack the fire breath of their larger kin.
    ---
}

species Wyrm includes Draconic {
    can_fly: false
    breathes_fire: true
    burrows_underground: true

    ---description
    Serpentine dragons without legs or wings. Burrow through
    earth and stone with ease.
    ---
}
```

### Composed Species
```storybook
species ElementalBeing {
    physical_form: false
    elemental_affinity: "none"
    lifespan: 500
}

species FireElemental includes ElementalBeing {
    elemental_affinity: "fire"
    temperature: 1500  // Celsius

    ---ecology
    Born from volcanic eruptions and wildfires. Feed on combustion
    and heat. Hostile to water and ice.
    ---
}

species WaterElemental includes ElementalBeing {
    elemental_affinity: "water"
    fluidity: 1.0

    ---ecology
    Manifest in rivers, lakes, and oceans. Can assume any liquid
    form. Vulnerable to extreme heat.
    ---
}
```

### Species with Rich Metadata
```storybook
species Elf {
    lifespan: 1000
    aging_rate: 0.1  // Relative to humans
    magic_sensitivity: 0.9
    height_range: 160..190  // cm

    ---description
    Long-lived humanoids with innate magical abilities and
    connection to ancient forests.
    ---

    ---culture
    Elven societies value art, music, and the preservation of
    knowledge. They see the rise and fall of human kingdoms as
    fleeting moments in the great tapestry of time.
    ---

    ---ecology
    Elves are closely tied to the health of forests. When
    woodlands are destroyed, nearby elven communities weaken
    and may fade entirely.
    ---

    ---notes
    Inspired by Tolkien's concept of immortal sadness—the burden
    of watching all mortal things pass away.
    ---
}
```

## Use Cases

### Taxonomy Systems
Build biological hierarchies:
```storybook
species Vertebrate {
    has_spine: true
    bilateral_symmetry: true
}

species Fish includes Vertebrate {
    breathes_underwater: true
    fins: true
}

species Amphibian includes Vertebrate {
    metamorphosis: true
    moist_skin: true
}

species Reptile includes Vertebrate {
    cold_blooded: true
    scales: true
}

species Bird includes Vertebrate {
    feathers: true
    lays_eggs: true
}

species Mammal includes Vertebrate {
    warm_blooded: true
    mammary_glands: true
}
```

### Fantasy Races
Define playable races or NPC types:
```storybook
species Dwarf {
    lifespan: 300
    height_range: 120..150
    darkvision: true
    stone_affinity: 0.9

    ---culture
    Master craftsmen who live in underground mountain halls.
    Value honor, loyalty, and fine metalwork.
    ---
}

species Orc {
    lifespan: 60
    height_range: 180..220
    strength_bonus: 2
    darkvision: true

    ---culture
    Tribal warriors with strong oral traditions. Misunderstood
    by outsiders as brutal savages; actually have complex honor
    codes and shamanistic practices.
    ---
}
```

### Sci-Fi Species
Model alien life:
```storybook
species Crystalline {
    silicon_based: true
    communicates_via: "resonance"
    reproduction: "budding"
    lifespan: 10000

    ---ecology
    Crystalline beings grow slowly in high-pressure environments.
    They communicate through harmonic vibrations and perceive
    electromagnetic spectra invisible to carbon-based life.
    ---
}
```

### Surreal Species
For absurdist or dreamlike worlds:
```storybook
species SentientColor {
    has_physical_form: false
    wavelength: 400..700  // nanometers
    emotional_resonance: true

    ---description
    Living colors that exist as pure wavelengths of light.
    They experience emotions as shifts in frequency and can
    paint themselves onto surfaces to communicate.
    ---
}
```

## Design Patterns

### Prefer Composition Over Deep Hierarchies
**Avoid:**
```storybook
species Being { ... }
species LivingBeing includes Being { ... }
species Animal includes LivingBeing { ... }
species Vertebrate includes Animal { ... }
species Mammal includes Vertebrate { ... }
species Primate includes Mammal { ... }
species Human includes Primate { ... }  // Too deep!
```

**Prefer:**
```storybook
species Mammal {
    warm_blooded: true
    live_birth: true
}

species Human includes Mammal {
    sapient: true
    language: true
}

// Use templates for capabilities
template Climber { ... }
template SocialCreature { ... }

character Jane: Human from Climber, SocialCreature { ... }
```

### Use Species for Ontology, Templates for Variation
```storybook
// Species: What they are
species Wolf {
    pack_animal: true
    carnivore: true
}

// Templates: Different wolf types
template AlphaWolf {
    dominance: 0.9..1.0
    pack_size: 5..15
}

template LoneWolf {
    dominance: 0.3..0.5
    pack_size: 0..2
}

character Fenrir: Wolf from AlphaWolf { ... }
character Outcast: Wolf from LoneWolf { ... }
```

## Cross-References

- [Characters](./10-characters.md) - How characters use species with `:` syntax
- [Templates](./16-other-declarations.md#templates) - Compositional alternative to species
- [Value Types](./18-value-types.md) - All supported field value types
- [Use Statements](./16-other-declarations.md#use-statements) - Importing species from other modules
- [Enums](./16-other-declarations.md#enums) - Defining controlled vocabularies for species fields

## Related Concepts

- **Taxonomic thinking**: Species form natural hierarchies mirroring biological classification
- **Essence vs. Traits**: Species capture essence (what something *is*); templates capture traits (what it *has*)
- **Single inheritance for identity**: A character can only be one species (you can't be both Human and Dragon)
- **Multiple inheritance for capabilities**: A character can have many templates (a Human can be both Warrior and Mage)
