Skip to content

extended_command

extended_command

Base class for all extended commands.

Token

Bases: GerberCode

Base class for creating Gerber token classes.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
class Token(GerberCode):
    """Base class for creating Gerber token classes."""

    @classmethod
    def wrap(cls, expr: ParserElement) -> ParserElement:
        """Set parse result to be instance of this class."""
        return expr.set_parse_action(cls.new)

    @classmethod
    def new(cls, string: str, location: int, _tokens: ParseResults) -> Self:
        """Create instance of this class.

        Created to be used as callback in `ParserElement.set_parse_action()`.
        """
        return cls(string, location)

    def __init__(self, string: str, location: int) -> None:
        """Initialize token instance."""
        self.string = string
        self.location = location

    def __str__(self) -> str:
        return f"GerberCode::Token::{self.__class__.__qualname__}"

    def __repr__(self) -> str:
        """Return pretty representation of comment token."""
        return self.__str__()

    def get_debug_format(self) -> str:
        """Return debug formatted token object."""
        return super().__repr__()

    @classmethod
    def ensure_type(cls, thing: Any) -> Self:
        """Ensure that <thing> is a instance of this class.

        Raise TypeError otherwise.
        """
        if not isinstance(thing, cls):
            raise TypeError(thing)

        return thing

    def update_drawing_state(
        self,
        state: State,
        _backend: Backend,
    ) -> Tuple[State, Iterable[DrawCommand]]:
        """Update drawing state."""
        return state, ()

    def get_token_position(self) -> Position:
        """Get position of token."""
        return self._token_position

    @cached_property
    def _token_position(self) -> Position:
        return Position(
            lineno(self.location, self.string),
            col(self.location, self.string),
        )

    def get_hover_message(self, state: LanguageServerState) -> str:
        """Return language server hover message."""
        ref_doc = "\n".join(s.strip() for s in str(self.__doc__).split("\n"))
        op_specific_extra = self.get_operation_specific_info(state)
        return (
            "```gerber\n"
            f"{self.get_gerber_code_one_line_pretty_display()}"
            "\n"
            "```"
            "\n"
            "---"
            "\n"
            f"{op_specific_extra}\n"
            "\n"
            "---"
            "\n"
            f"{ref_doc}"
        )

    def get_operation_specific_info(
        self,
        state: LanguageServerState,  # noqa: ARG002
    ) -> str:
        """Return operation specific extra information about token."""
        return ""

    def find_closest_token(
        self,
        pos: Position,  # noqa: ARG002
        parent: Optional[TokenAccessor] = None,
    ) -> TokenAccessor:
        """Find token closest to specified position."""
        return TokenAccessor(self, parent)

    def get_gerber_code_one_line_pretty_display(self) -> str:
        """Get gerber code represented by this token."""
        return self.get_gerber_code()

    def __iter__(self) -> Iterator[Token]:
        yield self

    def __hash__(self) -> int:
        return id(self)

    def __eq__(self, __value: object) -> bool:
        if not isinstance(__value, Token):
            return NotImplemented
        return id(__value) == id(self)

wrap classmethod

wrap(expr: ParserElement) -> ParserElement

Set parse result to be instance of this class.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
@classmethod
def wrap(cls, expr: ParserElement) -> ParserElement:
    """Set parse result to be instance of this class."""
    return expr.set_parse_action(cls.new)

new classmethod

new(
    string: str, location: int, _tokens: ParseResults
) -> Self

Create instance of this class.

Created to be used as callback in ParserElement.set_parse_action().

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
@classmethod
def new(cls, string: str, location: int, _tokens: ParseResults) -> Self:
    """Create instance of this class.

    Created to be used as callback in `ParserElement.set_parse_action()`.
    """
    return cls(string, location)

__init__

__init__(string: str, location: int) -> None

Initialize token instance.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
def __init__(self, string: str, location: int) -> None:
    """Initialize token instance."""
    self.string = string
    self.location = location

__repr__

__repr__() -> str

Return pretty representation of comment token.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
def __repr__(self) -> str:
    """Return pretty representation of comment token."""
    return self.__str__()

get_debug_format

get_debug_format() -> str

Return debug formatted token object.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
def get_debug_format(self) -> str:
    """Return debug formatted token object."""
    return super().__repr__()

ensure_type classmethod

ensure_type(thing: Any) -> Self

Ensure that is a instance of this class.

Raise TypeError otherwise.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
@classmethod
def ensure_type(cls, thing: Any) -> Self:
    """Ensure that <thing> is a instance of this class.

    Raise TypeError otherwise.
    """
    if not isinstance(thing, cls):
        raise TypeError(thing)

    return thing

update_drawing_state

update_drawing_state(
    state: State, _backend: Backend
) -> Tuple[State, Iterable[DrawCommand]]

Update drawing state.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
def update_drawing_state(
    self,
    state: State,
    _backend: Backend,
) -> Tuple[State, Iterable[DrawCommand]]:
    """Update drawing state."""
    return state, ()

get_token_position

get_token_position() -> Position

Get position of token.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
def get_token_position(self) -> Position:
    """Get position of token."""
    return self._token_position

get_hover_message

get_hover_message(state: LanguageServerState) -> str

Return language server hover message.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
def get_hover_message(self, state: LanguageServerState) -> str:
    """Return language server hover message."""
    ref_doc = "\n".join(s.strip() for s in str(self.__doc__).split("\n"))
    op_specific_extra = self.get_operation_specific_info(state)
    return (
        "```gerber\n"
        f"{self.get_gerber_code_one_line_pretty_display()}"
        "\n"
        "```"
        "\n"
        "---"
        "\n"
        f"{op_specific_extra}\n"
        "\n"
        "---"
        "\n"
        f"{ref_doc}"
    )

get_operation_specific_info

get_operation_specific_info(
    state: LanguageServerState,
) -> str

Return operation specific extra information about token.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
def get_operation_specific_info(
    self,
    state: LanguageServerState,  # noqa: ARG002
) -> str:
    """Return operation specific extra information about token."""
    return ""

find_closest_token

find_closest_token(
    pos: Position, parent: Optional[TokenAccessor] = None
) -> TokenAccessor

Find token closest to specified position.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
def find_closest_token(
    self,
    pos: Position,  # noqa: ARG002
    parent: Optional[TokenAccessor] = None,
) -> TokenAccessor:
    """Find token closest to specified position."""
    return TokenAccessor(self, parent)

get_gerber_code_one_line_pretty_display

get_gerber_code_one_line_pretty_display() -> str

Get gerber code represented by this token.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/token.py
def get_gerber_code_one_line_pretty_display(self) -> str:
    """Get gerber code represented by this token."""
    return self.get_gerber_code()

ExtendedCommandToken

Bases: Token

3.3 Commands.

Commands are the core syntactic element of the Gerber format. A Gerber file is a stream of commands. Commands define the graphics state, create graphical objects, defines apertures, manage attributes and so on.

Commands are built with words, the basic syntactic building block of a Gerber file. A word is a non-empty character string, excluding the reserved characters '' and '%', terminated with an ''

free_character = /[^%*]/; # All characters but * and %
word = {free_character}+ '*';

For historic reasons, there are two command syntax styles: word commands and extended commands.

command =
| extended_command
| word_command
;
word_command = word;
extended_command = '%' {word}+ '%';

Word commands are identified by a command code, the letter G, D or M followed by a positive integer, e.g. G02. Most word commands only consist of the command code, some also contain coordinates.

Extended commands are identified by a two-character command code that is followed by parameters specific to the code. An extended command is enclosed by a pair of "%" delimiters

An overview of all commands is in section 2.8, a full description in chapters 3.5 and 5.


Example 1

The example below shows a stream of Gerber commands.

G04 Different command styles*
G75*
G02*
D10*
X0Y0D02*
X2000000Y0I1000000J0D01*
D11*
X0Y2000000D03*
M02*

Example 2

The example below shows a stream of Gerber extended commands.

%FSLAX26Y26*%
%MOMM*%
%AMDonut*
1,1,$1,$2,$3*
$4=$1x0.75*
1,0,$4,$2,$3*
%
%ADD11Donut,0.30X0X0*%
%ADD10C,0.1*%

See section 3.3 of The Gerber Layer Format Specification

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/extended_command.py
class ExtendedCommandToken(Token):
    """## 3.3 Commands.

    Commands are the core syntactic element of the Gerber format. A Gerber file is a stream of
    commands. Commands define the graphics state, create graphical objects, defines apertures,
    manage attributes and so on.

    Commands are built with words, the basic syntactic building block of a Gerber file. A word is a
    non-empty character string, excluding the reserved characters '*' and '%', terminated with an '*'

    ```ebnf
    free_character = /[^%*]/; # All characters but * and %
    word = {free_character}+ '*';
    ```

    For historic reasons, there are two command syntax styles: word commands and extended
    commands.

    ```ebnf
    command =
    | extended_command
    | word_command
    ;
    word_command = word;
    extended_command = '%' {word}+ '%';
    ```


    Word commands are identified by a command code, the letter G, D or M followed by a positive
    integer, e.g. `G02`. Most word commands only consist of the command code, some also contain
    coordinates.

    Extended commands are identified by a two-character command code that is followed by
    parameters specific to the code. An extended command is enclosed by a pair of "%" delimiters

    An overview of all commands is in section 2.8, a full description in chapters 3.5 and 5.


    ---

    ## Example 1

    The example below shows a stream of Gerber commands.

    ```gerber
    G04 Different command styles*
    G75*
    G02*
    D10*
    X0Y0D02*
    X2000000Y0I1000000J0D01*
    D11*
    X0Y2000000D03*
    M02*
    ```


    ---

    ## Example 2

    The example below shows a stream of Gerber extended commands.

    ```gerber
    %FSLAX26Y26*%
    %MOMM*%
    %AMDonut*
    1,1,$1,$2,$3*
    $4=$1x0.75*
    1,0,$4,$2,$3*
    %
    %ADD11Donut,0.30X0X0*%
    %ADD10C,0.1*%
    ```

    ---

    See section 3.3 of [The Gerber Layer Format Specification](https://www.ucamco.com/files/downloads/file_en/456/gerber-layer-format-specification-revision-2023-08_en.pdf#page=33)

    """  # noqa: E501

    def get_gerber_code_one_line_pretty_display(self) -> str:
        """Get gerber code represented by this token."""
        return f"%{self.get_gerber_code()}*%"

get_gerber_code_one_line_pretty_display

get_gerber_code_one_line_pretty_display() -> str

Get gerber code represented by this token.

Source code in src/pygerber/gerberx3/tokenizer/tokens/bases/extended_command.py
def get_gerber_code_one_line_pretty_display(self) -> str:
    """Get gerber code represented by this token."""
    return f"%{self.get_gerber_code()}*%"