# Other Declarations - Storybook Language Guide
Comprehensive documentation for the Storybook narrative simulation language

# Other Declarations

This chapter covers six utility declaration types that complete the Storybook language: Templates, Institutions, Locations, Species, Enums, and Use statements. These declarations enable code reuse, organizational modeling, world-building, type safety, and modular file organization.

## Templates

Templates are reusable field sets that characters inherit using the `from` keyword. Unlike species (which define what an entity is), templates define what an entity has—capabilities, traits, and characteristics.

### Syntax

    <template-decl> ::= "template" <identifier> <strict-clause>? <resource-links>? <includes-clause>? <body>

    <strict-clause> ::= "strict"

    <resource-links> ::= "uses" "behaviors" ":" <behavior-list>
                       | "uses" "schedule" ":" <schedule-ref>
                       | "uses" "schedules" ":" <schedule-list>

    <includes-clause> ::= "include" <identifier> ("," <identifier>)*

    <body> ::= "{" <field>* "}"

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

### Basic Template

    template Warrior {
        strength: 10..20
        dexterity: 8..15
        weapon_proficiency: 0.7..1.0
    }

Characters inheriting this template get these fields with values selected from the specified ranges.

### Template Includes

Templates can include other templates to compose functionality:

    template SkilledWorker {
        skill_level: SkillLevel
        confidence: Confidence
        years_experience: 0..50
        can_work_independently: false
    }

    template Baker {
        include SkilledWorker

        specialty: Specialty
        recipes_mastered: 0..200
        sourdough_starter_health: 0.0..1.0
    }

Semantics:

- `include SkilledWorker` brings in all fields from that template
- Fields are merged left-to-right (later overrides earlier)
- Transitive includes supported
- Multiple includes allowed: `include A, B, C`

### Range Values

Templates can specify ranges for procedural variation:

    template Villager {
        age: 18..65
        wealth: 10..100
        height: 150.0..190.0
        disposition: 0.0..1.0
    }

Range syntax:

- Integer ranges: `min..max` (inclusive)
- Float ranges: `min..max` (inclusive)
- Both bounds must be same type
- min ≤ max required

When a character uses this template, the runtime selects specific values within each range.

### Strict Mode

Strict templates enforce that characters using them can only have fields defined in the template:

    template RecipeCard strict {
        include SkilledWorker

        recipe_name: string
        difficulty: Difficulty
        prep_time_minutes: 10..180
        requires_starter: false
    }

Strict semantics:

- Characters using strict templates cannot add extra fields
- All template fields must be present in the character
- Enables type safety for well-defined schemas
- Use for controlled domains (game cards, rigid categories)

Non-strict (default):

    template Flexible {
        base_stat: 10
    }

    character Custom from Flexible {
        base_stat: 15      // Override
        extra_field: 42    // Allowed in non-strict
    }

Strict:

    template Rigid strict {
        required_stat: 10
    }

    character Constrained from Rigid {
        required_stat: 15  // OK: Override
        extra_field: 42    // ERROR: Not allowed in strict template
    }

### Resource Linking in Templates

Templates can link to behaviors and schedules (v0.2.0+):

    template BakeryStaffMember
        uses behaviors: DailyBakingRoutine, CustomerService
        uses schedule: BakerySchedule
    {
        include SkilledWorker

        on_shift: true
        orders_completed: 0..1000
        current_station: 0..4
    }

Characters inheriting this template automatically get the linked behaviors and schedule.

### Templates vs. Species

Aspect | Templates (`from`) | Species (`:`)
--- | --- | ---
Semantics | What entity has | What entity is
Cardinality | Multiple inheritance | Single inheritance
Ranges | Allowed | Not allowed
Strict mode | Supported | Not supported
Use case | Compositional traits | Ontological identity

Example combining both:

    species Dragon {
        lifespan: 1000
        can_fly: true
    }

    template Hoarder {
        treasure_value: 0..1000000
        greed_level: 0.5..1.0
    }

    character Smaug: Dragon from Hoarder {
        age: 850
        greed_level: 0.95
    }

### Validation Rules

1. Includes exist: All included templates must be defined
2. No circular includes: Cannot form cycles
3. Range validity: min ≤ max for all ranges
4. Strict enforcement: Strict templates reject extra fields in characters
5. Resource links valid: Behavior/schedule references must resolve

## Institutions

Institutions define organizations, groups, and systems—entities that function like characters but represent collectives rather than individuals.

### Syntax

    <institution-decl> ::= "institution" <identifier> <resource-links>? <body>

    <resource-links> ::= "uses" "behaviors" ":" <behavior-list>
                       | "uses" "schedule" ":" <schedule-ref>
                       | "uses" "schedules" ":" <schedule-list>

    <body> ::= "{" <field>* <prose-block>* "}"

### Basic Institution

    institution BakersGuild {
        type: trade_guild
        members: 50
        founded: "1450-03-15"
        reputation: 0.85
    }

### Institutions with Fields

    institution BakersGuild {
        type: professional_guild
        government_style: elected_board
        hierarchy: flat
        standards_enforcement: true

        // Leadership
        board_chair: Martha
        vice_chair: Henri
        board_temperament: collegial

        // Membership
        master_bakers: 12
        journeymen: 25
        apprentices: 8
        honorary_members: 3

        // Standards
        certification_process: "practical exam and peer review"
        quality_standard: "excellence"
        annual_competition: true
        scholarships_offered: 2

        ---description
        The local bakers' guild that sets quality standards, organizes
        competitions, and mentors apprentices. Martha has been a board
        member for three years.
        ---
    }

### Resource Linking

Institutions can use behaviors and schedules:

    institution MarthasBakery
        uses behaviors: DailyBakingRoutine, CustomerService
        uses schedule: BakerySchedule
    {
        type: small_business
        purpose: bread_and_pastry_production
        family_owned: true
        established: 2018

        permanent_staff: 4
        seasonal_helpers: 0..3

        ---description
        A beloved neighborhood bakery run by Martha and Jane,
        known for its sourdough bread and artisan pastries.
        ---
    }

### Prose Blocks

Institutions support rich narrative documentation:

    institution TownCulinaryScene {
        type: cultural_ecosystem
        governs: "local food culture"

        // Characteristics
        farm_to_table: true
        artisan_focus: strong
        seasonal_menus: true
        community_events: monthly

        ---description
        The overarching culinary culture of the town -- a network
        of bakeries, farms, and food artisans that sustain each other.
        ---

        ---philosophy
        The town's food scene operates on relationships: farmers
        supply bakers, bakers feed families, families support farms.
        Quality and trust are the currency of this ecosystem.
        ---
    }

### Use Cases

- Organizations: Guilds, companies, governments
- Systems: Magical systems, physical laws, economies
- Social structures: Families, tribes, castes
- Abstract entities: Dream logic, fate, chaos

### Validation Rules

1. Unique names: Institution names must be unique
2. Resource links valid: Behaviors/schedules must exist
3. Field types: All fields must have valid values

## Locations

Locations define places in your world—rooms, buildings, cities, landscapes, or abstract spaces.

### Syntax

    <location-decl> ::= "location" <identifier> <body>

    <body> ::= "{" <field>* <prose-block>* "}"

### Basic Location

    location MarthasBakery {
        square_feet: 1200
        type: commercial
        established: "2018"
        has_storefront: true

        ---description
        A warm, inviting bakery on Main Street. The aroma of fresh
        bread wafts out the door every morning. Exposed brick walls,
        a glass display case, and a view into the open kitchen.
        ---
    }

### Location with Structure

    location BakeryKitchen {
        type: "commercial kitchen"
        ovens: 3
        prep_stations: 4
        walk_in_cooler: true

        // Equipment
        has_proofing_cabinet: true
        mixer_capacity_kg: 20
        starter_shelf: true

        // Storage
        flour_bins: 6
        ingredient_shelves: 12
        cold_storage: true

        ---description
        The heart of the bakery. Three professional ovens line the
        back wall. The sourdough starter sits on a shelf near the
        warmest oven, bubbling contentedly in its ceramic crock.
        ---
    }

### Geographic Hierarchy

Locations can reference other locations:

    location MainStreet {
        type: commercial_district
        shops: 15
        foot_traffic: high
    }

    location BakeryStorefront {
        part_of: MainStreet
        seating_capacity: 12
        display_case: true

        ---description
        The customer-facing area with a glass display case full
        of fresh bread, pastries, and seasonal specials.
        ---
    }

    location FarmersMarket {
        part_of: MainStreet
        operates_on: saturday
        stalls: 30

        ---description
        The weekly Saturday market where Martha sells bread directly
        to the community. Her stall is always the first to sell out.
        ---
    }

### Location with State

    location BakeryWarehouse {
        temperature: controlled
        square_feet: 400
        humidity_controlled: true
        shelving_units: 8

        // Storage state
        flour_stock_kg: 200
        yeast_supply_days: 14
        packaging_materials: true

        ---description
        The storage area behind the kitchen. Climate-controlled to
        keep flour dry and ingredients fresh. Martha takes inventory
        every Monday morning.
        ---

        ---logistics
        Deliveries arrive Tuesday and Friday mornings. The walk-in
        cooler holds butter, eggs, and cream. Dry goods are rotated
        on a first-in-first-out basis.
        ---
    }

### Use Cases

- Physical places: Cities, buildings, rooms
- Geographic features: Mountains, rivers, forests
- Abstract spaces: Dream realms, pocket dimensions
- Game boards: Arenas, dungeons, maps

### Validation Rules

1. Unique names: Location names must be unique
2. Field types: All fields must have valid values
3. References valid: Location references (like `part_of`) should resolve

## Species

Species define the fundamental ontological categories of beings. A species represents what an entity is at its core—human, dragon, sentient tree, animated playing card.

### Syntax

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

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

    <body> ::= "{" <field>* <prose-block>* "}"

### Basic Species

    species Human {
        lifespan: 70

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

### Species with Includes

Species can include other species for composition:

    species Mammal {
        warm_blooded: true
        has_fur: true
    }

    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.
        ---
    }

### Field Resolution with Includes

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

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

Example:

    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
    }

    // Resolved:
    // 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)

### Species vs. Templates

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

When to use species:

    species Dragon {
        lifespan: 1000
        can_fly: true
        breathes_fire: true
    }

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

When to use templates:

    template Hoarder {
        treasure_value: 0..1000000
        greed_level: 0.5..1.0
    }

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

### Design Pattern: Prefer Composition Over Deep Hierarchies

Avoid:

    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:

    species Mammal {
        warm_blooded: true
        live_birth: true
    }

    species Human includes Mammal {
        sapient: true
    }

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

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

### Validation Rules

1. Unique names: Species names must be unique
2. No circular includes: Cannot form cycles
3. Includes exist: All included species must be defined
4. Field types: All fields must have valid values

## Enums

Enums define controlled vocabularies—fixed sets of named values. They enable type-safe categorization and validation.

### Syntax

    <enum-decl> ::= "enum" <identifier> "{" <variant>+ "}"

    <variant> ::= <identifier> ","?

### Basic Enum

    enum Size {
        tiny,
        small,
        normal,
        large,
        huge
    }

### Using Enums

Enums are used as field values throughout the system:

    character Martha: Human {
        skill_level: master     // References SkillLevel enum
        specialty: sourdough    // References Specialty enum
    }

### Common Enum Patterns

Emotional States:

    enum EmotionalState {
        curious,
        frightened,
        confused,
        brave,
        angry,
        melancholy,
        amused
    }

Card Suits:

    enum CardSuit {
        hearts,
        diamonds,
        clubs,
        spades
    }

    enum CardRank {
        two, three, four, five, six, seven, eight, nine, ten,
        knave, queen, king
    }

Time States:

    enum TimeState {
        normal,
        frozen,
        reversed,
        accelerated
    }

Government Types:

    enum GovernmentType {
        monarchy,
        democracy,
        anarchy,
        tyranny,
        oligarchy
    }

    enum GovernmentStyle {
        absolute_tyranny,
        benevolent_dictatorship,
        constitutional_monarchy,
        direct_democracy,
        representative_democracy
    }

### Calendar Enums (Configurable)

Define custom calendars for your world:

    enum Season {
        spring,
        summer,
        fall,
        winter
    }

    enum DayOfWeek {
        monday,
        tuesday,
        wednesday,
        thursday,
        friday,
        saturday,
        sunday
    }

    enum Month {
        january, february, march, april,
        may, june, july, august,
        september, october, november, december
    }

Custom calendars:

    enum EightSeasons {
        deep_winter,
        late_winter,
        early_spring,
        late_spring,
        early_summer,
        late_summer,
        early_fall,
        late_fall
    }

### Validation Integration

Enums enable compile-time validation:

    enum Size {
        tiny, small, normal, large, huge
    }

    character Martha {
        skill_level: medium  // ERROR: 'medium' not in SkillLevel enum
    }

### Use Cases

- Controlled vocabularies: Prevent typos and invalid values
- Schema constraints: Temporal systems, card decks, status types
- Type safety: Catch errors at compile time
- Documentation: Enumerate all valid options

### Validation Rules

1. Unique enum names: Enum names must be unique
2. Unique variants: Variant names must be unique within the enum
3. Non-empty: Enums must have at least one variant
4. Valid identifiers: Variants must follow identifier rules

## Use Statements

Use statements import definitions from other files, enabling modular organization and code reuse.

### Syntax

    <use-decl> ::= "use" <use-path> <use-kind>

    <use-path> ::= <identifier> ("::" <identifier>)*

    <use-kind> ::= ";"                                   // Single import
                 | "::{" <identifier> ("," <identifier>)* "}" ";"  // Grouped import
                 | "::*" ";"                             // Wildcard import

### Single Import

    use schema::beings::Human;

Imports the `Human` species from `schema/beings.sb`.

### Grouped Import

    use schema::core_enums::{Size, EmotionalState};

Imports multiple items from the same module.

### Wildcard Import

    use schema::beings::*;

Imports all public items from `schema/beings.sb`.

### Qualified Paths

Module structure:

    examples/alice-in-wonderland/
    ├─ schema/
    │   ├─ core_enums.sb
    │   ├─ templates.sb
    │   └─ beings.sb
    └─ world/
        ├─ characters/
        │   └─ alice.sb
        └─ locations/
            └─ wonderland_places.sb

In `martha.sb`:

    use schema::core_enums::{SkillLevel, Specialty};
    use schema::templates::Baker;
    use schema::beings::Human;

    character Martha: Human from Baker {
        skill_level: master
        specialty: sourdough
    }

### Path Resolution

1. Relative to file’s module path: Imports are resolved relative to the current file’s location
2. Module hierarchy: `schema::beings` maps to `schema/beings.sb`
3. Transitive imports: Imported modules can themselves import others

### Common Patterns

Schema organization:

    // In schema/core_enums.sb
    enum SkillLevel { novice, beginner, intermediate, advanced, master }
    enum Specialty { sourdough, pastries, cakes, general }

    // In world/characters/martha.sb
    use schema::core_enums::{SkillLevel, Specialty};

Template composition:

    // In schema/templates.sb
    template SkilledWorker { ... }
    template Baker {
        include SkilledWorker
        ...
    }

    // In world/characters/martha.sb
    use schema::templates::Baker;

Cross-file references:

    // In world/characters/martha.sb
    character Martha { ... }

    // In world/relationships/bakery.sb
    use world::characters::Martha;

    relationship MarthaAndJane {
        Martha
        Jane
    }

### Validation Rules

1. Path exists: Imported paths must reference defined modules/items
2. No circular imports: Modules cannot form circular dependency chains
3. Valid identifiers: All path segments must be valid identifiers
4. Grouped import validity: All items in `{}` must exist

### Best Practices

1. Group related imports:

    use schema::core_enums::{SkillLevel, Specialty, Confidence};
    use schema::beings::{Human, Cat};

2. Explicit over wildcard:

    // Prefer:
    use schema::core_enums::{SkillLevel, Specialty};

    // Over:
    use schema::core_enums::*;  // Imports everything

3. Organize by hierarchy:

    // Schema imports first
    use schema::core_enums::SkillLevel;
    use schema::templates::Baker;

    // Then world imports
    use world::characters::Martha;

4. Use qualified paths for clarity:

    character Elena: Human from Baker, Apprentice {
        // Human is species (from schema::beings)
        // Baker, Apprentice are templates (from schema::templates)
    }

## Cross-References

- Characters - Using templates and species
- Relationships - Institutions can participate
- Schedules - Resource linking
- Behavior Trees - Resource linking
- Value Types - Field value types

## Related Concepts

- Modularity: Use statements enable file organization
- Composition: Templates provide trait-based composition
- Type safety: Enums prevent invalid values
- World-building: Locations and institutions model environments
- Ontology: Species define entity essence