# Wasot Selector Syntax Complete Reference

## Chapter 1: Basic Selector Structure

### Selector Grammar Hierarchy
- Selector Group: Multiple compound selectors separated by commas (`,`)
- Compound Selector: Simple selectors connected by combinators  
- Simple Selector: Chain of basic selectors without combinators
- Basic Selectors: Type, ID, class, attribute, pseudo-class selectors

### Entry Point
- Main rule: `selector_group` containing one or more compound selectors
- Whitespace handling: NOT ignored by default (acts as descendant combinator)
- Quote-aware parsing for identifiers and values

## Chapter 2: Identifiers and Strings

### Identifier Types
- Unquoted identifiers: `div`, `paragraph`, `custom-element`
- Quoted identifiers: `"type with spaces"`, `"special-type"`
- Start with letters, digits, underscore, or hyphen
- Allow alphanumeric, hyphen, underscore, and non-ASCII characters
- Can start with digits: `.123class`, `#456id`

### Quoted Strings
- Double-quoted: `"string with spaces"`
- Escaped quotes: `"text \"with quotes\" inside"`
- Escaped backslashes: `"path\\to\\file"`
- Support any characters including Unicode
- Used for both identifiers and attribute values

### Unicode Support
- Full Unicode support in identifiers and strings
- RTL text, emoji, combining characters
- Various scripts: CJK, Arabic, Hebrew
- Zero-width characters: `\u{200B}`, `\u{200C}`

## Chapter 3: Basic Selectors

### Universal Selector
- Syntax: `*`
- Matches any element type
- Can be combined with other selectors: `*.highlight`, `*:first-child`

### Type Selector
- Syntax: `element-name` or `"type with spaces"`
- Examples: `div`, `paragraph`, `"custom type"`
- Case-sensitive matching
- Supports quoted names with spaces

### ID Selector
- Syntax: `#id-name` or `#"id with spaces"`
- Examples: `#main`, `#"special id"`, `#123id`
- Matches element's ID attribute
- IDs can start with numbers or contain special characters

### Class Selector
- Syntax: `.class-name` or `."class with spaces"`
- Examples: `.highlight`, `.primary`, `."special class"`
- Matches positional arguments starting with `.`
- Multiple classes can be chained: `.red.bold.large`

## Chapter 4: Attribute Selectors

### Attribute Presence
- Syntax: `[attribute]`
- Examples: `[disabled]`, `[required]`, `[data-active]`
- Matches if attribute exists as positional or keyword argument
- Case-sensitive attribute names

### Attribute Negated Presence
- Syntax: `[!attribute]`
- Examples: `[!disabled]`, `[!hidden]`
- Matches if attribute does NOT exist
- Logical negation of presence check

### Attribute Exact Match
- Syntax: `[key=value]` or `[key="value with spaces"]`
- Examples: `[lang=en]`, `[role="navigation"]`, `[key=]`
- Supports empty values: `[attr=]`
- Quote-aware value parsing

### Attribute Negated Match
- Syntax: `[key~=value]`
- Examples: `[lang~=fr]`, `[type~="text"]`
- Matches when key exists but value doesn't match
- Supports empty values

### Attribute Prefix Match
- Syntax: `[key^=prefix]`
- Examples: `[href^="https"]`, `[class^="btn"]`
- Matches if value starts with prefix
- Empty prefix matches any value

### Attribute Suffix Match
- Syntax: `[key$=suffix]`
- Examples: `[href$=".pdf"]`, `[file$=".jpg"]`
- Matches if value ends with suffix
- Empty suffix matches any value

### Attribute Substring Match
- Syntax: `[key*=substring]`
- Examples: `[title*="hello"]`, `[url*="example"]`
- Matches if value contains substring
- Case-sensitive matching

### Complex Attribute Examples
- Multiple attributes: `[disabled][required][type="text"]`
- Quoted keys: `["data-test"="value"]`
- Special characters: `[data-url="https://example.com/path?query=1"]`
- Mixed quoted/unquoted: `[role=button][title="Click me"]`

## Chapter 5: Pseudo-Class Selectors

### Simple Pseudo-Classes
- First child: `:first-child`
- Last child: `:last-child`
- First block: `:first-block`
- Last block: `:last-block`
- First text: `:first-text`
- Last text: `:last-text`

### Functional Pseudo-Classes
- Nth child: `:nth-child(n)`
- Nth block: `:nth-block(n)`
- Nth text: `:nth-text(n)`
- Examples: `:nth-child(1)`, `:nth-child(3)`, `:nth-block(2)`
- Numeric argument only (currently)

### Negation Pseudo-Class
- Syntax: `:not(selector-group)`
- Examples: `:not(p)`, `:not(.hidden)`, `:not([disabled])`
- Can contain complex selectors: `:not(div.modal[aria-hidden])`
- Accepts full selector groups: `:not(p, #intro)`
- Cannot contain other `:not()` selectors (CSS limitation)

### Pseudo-Class Combinations
- Chaining: `:first-child:not(.hidden)`
- With other selectors: `div.container:nth-child(2)`
- Complex conditions: `.item:not(.disabled):not([aria-hidden])`

## Chapter 6: Combinators

### Descendant Combinator (Whitespace)
- Syntax: `ancestor descendant` (one or more spaces)
- Examples: `body div`, `section paragraph`
- Matches any descendant at any depth
- Most permissive combinator

### Child Combinator
- Syntax: `parent > child`
- Examples: `ul > li`, `div > p`
- Matches direct children only
- Whitespace around `>` is optional: `div>p`, `div > p`

### Adjacent Sibling Combinator
- Syntax: `element + next-sibling`
- Examples: `h1 + p`, `label + input`
- Matches immediately following sibling
- Whitespace around `+` is optional

### General Sibling Combinator
- Syntax: `element ~ later-sibling`
- Examples: `h1 ~ p`, `dt ~ dd`
- Matches any following sibling at same level
- Whitespace around `~` is optional

### Combinator Precedence
- Order matters in parser: specific symbols before whitespace
- `>` checked before descendant whitespace
- `+` and `~` checked before descendant whitespace
- Proper spacing: `div > p + span ~ em`

## Chapter 7: Compound Selectors

### Simple Compound Selectors
- Type + ID: `div#main`
- Type + class: `div.container`
- Type + attribute: `input[required]`
- Type + pseudo-class: `div:first-child`

### Complex Compound Selectors
- Everything: `div#main.container.active[role="button"][disabled]:first-child`
- Multiple classes: `.red.bold.large`
- Multiple attributes: `[type="text"][required][placeholder]`
- Multiple pseudo-classes: `:first-child:not(.hidden)`

### Chaining Rules
- ID selector: at most one per simple selector
- Type selector: at most one per simple selector
- Class selectors: multiple allowed
- Attribute selectors: multiple allowed
- Pseudo-class selectors: multiple allowed

## Chapter 8: Selector Groups (Comma-Separated)

### Basic Selector Groups
- Multiple types: `h1, h2, h3`
- Mixed selectors: `div, .container, #main`
- Complex groups: `article > p, section > div`

### Whitespace Handling
- Around commas: `h1, h2` vs `h1,h2` vs `h1 , h2`
- All variations are valid
- Consistent formatting recommended

### Complex Group Examples
- Forms: `input[type="text"], input[type="email"], textarea`
- Navigation: `nav > ul > li, .breadcrumb > span`
- States: `.active, .selected, :focus, :hover`

## Chapter 9: Real-World Selector Examples

### Navigation Selectors
- `nav ul li`: Any list item in navigation
- `nav > ul > li`: Direct navigation list items
- `.breadcrumb > a`: Direct breadcrumb links
- `nav a:not(.disabled)`: Enabled navigation links

### Content Selectors
- `article p`: Paragraphs in articles
- `.content > h1, .content > h2`: Direct headings in content
- `blockquote cite`: Citations in blockquotes
- `.highlight:not(.faded)`: Visible highlights

### Form Selectors
- `input[type="text"][required]`: Required text inputs
- `label + input`: Inputs following labels
- `.form-group > label`: Direct form labels
- `input:not([disabled]):not([readonly])`: Editable inputs

### State-Based Selectors
- `.modal:not(.hidden)`: Visible modals
- `.item.selected:first-child`: First selected item
- `[aria-expanded="true"]`: Expanded elements
- `.button:not(.loading):not(.disabled)`: Actionable buttons

## Chapter 10: Edge Cases and Limitations

### Parser Edge Cases
- Empty selectors: `""` (invalid)
- Whitespace-only: `"   "` (invalid)
- Unclosed quotes: `"unclosed` (error)
- Invalid escapes: `\invalid` (handled gracefully)
- Extreme nesting: 1000+ levels (parser dependent)

### Combinator Edge Cases
- Multiple consecutive: `div > > p` (invalid)
- Trailing combinator: `div >` (invalid)
- Leading combinator: `> div` (invalid)
- Mixed spaces: `div   >   p` (valid)

### Quote Handling
- Nested quotes: `"outer \"inner\" outer"`
- Escaped backslashes: `"path\\to\\file"`
- Unicode in quotes: `"日本語クラス"`
- Empty quoted strings: `""` (valid but unusual)

### Attribute Edge Cases
- Empty values: `[attr=""]`, `[attr=]`
- Special characters: `[data-url="https://example.com/path?a=1&b=2"]`
- Quoted keys: `["data-test"="value"]`
- No value: `[attr]` vs `[attr=]` (different meanings)

### Pseudo-Class Limitations
- `:not()` cannot contain `:not()` (CSS standard)
- Numeric arguments only: `:nth-child(2n+1)` not yet supported
- Complex selectors in `:not()`: implementation dependent
- Sibling pseudo-classes: limited implementation

## Chapter 11: Performance Considerations

### Efficient Selectors
- Specific rightmost selectors: `div.content p` better than `div p`
- ID selectors are fastest: `#main` > `.class` > `type`
- Avoid universal selectors: `*` in complex chains
- Minimize `:not()` usage in hot paths

### Inefficient Patterns
- Complex descendant chains: `body div section article p span`
- Multiple `:not()` conditions: `:not(.a):not(.b):not(.c)`
- Universal with descendants: `* div p`
- Overly generic selectors: `div div div`

### Memory Usage
- Deep nesting: bounded by document depth
- Long selector chains: linear memory growth
- Attribute matching: string comparison overhead
- Regex-like patterns: avoid in performance-critical code

## Chapter 12: Error Handling and Validation

### Parse Errors
- Syntax errors: clear error messages with position
- Unclosed structures: quotes, brackets, parentheses
- Invalid characters: handled gracefully where possible
- Empty input: rejected with appropriate error

### Runtime Errors
- Malformed document stack: handled defensively
- Missing elements: returns false, doesn't panic
- Invalid selector structure: validated during parsing
- Memory limits: bounded channel usage prevents overflow

### Error Recovery
- Partial parsing: best-effort approach
- Graceful degradation: invalid parts ignored where possible
- Clear error messages: position and context information
- Fallback behavior: conservative matching when uncertain

## Chapter 13: Compatibility and Standards

### CSS Compatibility
- CSS3 selector syntax foundation
- Wasot-specific extensions: block types, positional arguments
- Standard combinators: descendant, child, sibling
- Pseudo-class subset: common patterns supported

### Wasot Extensions
- Block type selectors: match Wasot element types
- Positional argument matching: classes as `.arg` patterns
- ID syntax: `:id` in Wasot vs `id="value"` in HTML
- Attribute access: both positional and keyword arguments

### Future Extensions
- Advanced pseudo-classes: `:nth-child(2n+1)` formulas
- Custom pseudo-classes: `:empty`, `:has-children`
- String matching operators: case-insensitive options
- Performance optimizations: indexing, caching

## Chapter 14: Testing and Validation

### Test Coverage
- All grammar rules tested
- Edge cases documented
- Performance stress tests
- Unicode and special character handling
- Error condition coverage

### Integration Tests
- Parser + AST + matching pipeline
- Real-world selector patterns
- Complex document structures
- Multi-language content support
- Memory usage validation

### Regression Testing
- Parser stability across versions
- Backward compatibility maintenance
- Performance regression detection
- Error message consistency
- API stability verification