> For the complete documentation index, see [llms.txt](https://0xlava.gitbook.io/ducky-morph/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://0xlava.gitbook.io/ducky-morph/python-api/duckyparser.md).

# DuckyParser

### DuckyScript Parser

The `DuckyParser` is responsible for transforming raw DuckyScript source code into an Abstract Syntax Tree (AST).

It serves as the core parsing engine of DuckyMorph and implements a state-driven parsing architecture capable of handling both single-line and multi-line language constructs.

The parser validates syntax, manages parsing states, and produces a structured AST representation that can later be consumed by code generators.

***

### Design Overview

The parser operates in three major stages:

1. Read source lines from a file or raw script.
2. Resolve the appropriate parsing function for each line.
3. Convert parsed statements into AST nodes.

Generated nodes are accumulated internally and exposed through the <mark style="color:yellow;">`get_ast`</mark>`()` method.

***

### Parsing Architecture

The parser uses a dispatch-based architecture.

Each supported keyword is mapped to a dedicated parsing function:

```
REM        -> parse_rem()
DELAY      -> parse_delay()
STRING     -> parse_string()
STRINGLN   -> parse_stringln()
REM_BLOCK  -> parse_rem_block()
RELEASE    -> parse_key_release()
HOLD       -> parse_hold()
```

Additional conditional parsers are used for:

* Key presses.
* Key combinations.
* Single character input.

This architecture makes the parser easily extensible by simply registering additional parsing functions.

***

### State Machine

The parser implements a finite state machine (FSM) to support multi-line constructs.

Supported states include:

* <mark style="color:$primary;">`NORMAL`</mark>
* <mark style="color:$primary;">`WAIT_STRING`</mark>
* <mark style="color:$primary;">`WAIT_STRINGLN`</mark>
* <mark style="color:$primary;">`WAIT_REM`</mark>

#### Example

```duckyscript
STRING
Hello
World
END_STRING
```

When the parser encounters `STRING` without inline content, it switches to `WAIT_STRING` state and continues collecting lines until `END_STRING` is found.

The same mechanism is used for block comments.

***

### Core Methods

#### <mark style="color:yellow;">parse</mark>(ducky\_script)

Parses an entire DuckyScript source.

#### Behavior

* Reads script lines sequentially.
* Resolves a parser for each line.
* Generates AST nodes.
* Verifies that all parser states are properly closed.

***

#### <mark style="color:yellow;">parse\_line</mark>(script\_line)

Parses a single line of DuckyScript.

#### Behavior

* Ignores empty lines.
* Detects the statement type.
* Delegates parsing to the appropriate parser function.
* Appends generated nodes to the AST.

***

#### <mark style="color:yellow;">\_get\_parser</mark>(line\_start)

Resolves the parser responsible for handling the current line.

#### Resolution Order

1. Current parser state.
2. Registered keyword parsers.
3. Conditional parsers.

***

#### <mark style="color:yellow;">\_get\_script\_line</mark>(data\_source)

Creates a line iterator from either:

* A file path.
* A raw DuckyScript string.

This abstraction allows the parser to consume multiple input sources transparently.

***

#### <mark style="color:yellow;">get\_ast</mark>()

Returns the generated Abstract Syntax Tree.

***

### AST Generation

Every successful parsing operation produces one or more `ASTNode` objects.

Example:

```duckyscript
CTRL ALT DELETE
```

Produces:

```python
ASTNode(
    type=KEY_COMBO,
    value=["CTRL", "ALT", "DELETE"]
)
```

The complete AST is accumulated internally during parsing.

***

### Extending The Parser

New language statements can be added by:

1. Creating a dedicated parsing function.
2. Registering it inside `_parsing_functions`.

Example:

```python
self._parsing_functions["MY_COMMAND"] = self.parse_my_command
```

For context-sensitive commands, custom matchers can also be registered through `_conditional_parsers`.

***

### Error Handling

The parser raises specialized exceptions for syntax and state errors.

Common error scenarios include:

* Unknown keywords.
* Invalid key combinations.
* Incorrect `DELAY` syntax.
* Invalid `HOLD` or `RELEASE` usage.
* Unclosed `STRING` blocks.
* Unclosed `REM_BLOCK` blocks.
* Unknown parser states.
* Invalid input sources.

Examples:

```duckyscript
DELAY abc
```

```duckyscript
HOLD CTRL ALT
```

```duckyscript
STRING
Hello
```

The last example will raise a <mark style="color:cyan;">`DuckyParserInvalidEndState`</mark> exception because the block was never closed.

***

### Typical Workflow

```python
parser = DuckyParser()

parser.parse(script)

ast = parser.get_ast()
```

The resulting AST can then be passed to any code generator supported by DuckyMorph.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://0xlava.gitbook.io/ducky-morph/python-api/duckyparser.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
