# evennia.utils.funcparser

Generic function parser for functions embedded in a string, on the form $funcname(*args, **kwargs), for example:

“A string $foo() with $bar(a, b, c, $moo(), d=23) etc.”

Each arg/kwarg can also be another nested function. These will be executed inside-out and their return will used as arguments for the enclosing function (so the same as for regular Python function execution).

This is the base for all forms of embedded func-parsing, like inlinefuncs and protfuncs. Each function available to use must be registered as a ‘safe’ function for the parser to accept it. This is usually done in a module with regular Python functions on the form:

    # in a module whose path is passed to the parser

    def _helper(x):
        # use underscore to NOT make the function available as a callable

    def funcname(*args, **kwargs):
        # this can be accessed as $funcname(*args, **kwargs)
        # it must always accept *args and **kwargs.
        ...
        return something

Usage:

    from evennia.utils.funcparser import FuncParser

    parser = FuncParser("path.to.module_with_callables")
    result = parser.parse("String with $funcname() in it")

The FuncParser also accepts a direct dict mapping of {‘name’: callable, …}.

—

exception `evennia.utils.funcparser.``ParsingError`

  Bases: `RuntimeError`

  Failed to parse for some reason.

class `evennia.utils.funcparser.``FuncParser`(callables, start_char='$', escape_char='\\', max_nesting=20, **default_kwargs)

  Bases: `object`

  Sets up a parser for strings containing $funcname(*args, **kwargs) substrings.

  `__init__`(callables, start_char='$', escape_char='\\', max_nesting=20, **default_kwargs)

    Initialize the parser.

    Parameters

      - callables (str, module, list or dict) – Where to find ‘safe’ functions to make available in the parser. If a dict, it should be a direct mapping {“funcname”: callable, …}. If one or mode modules or module-paths, the module(s) are first checked for a dict FUNCPARSER_CALLABLES = {“funcname”, callable, …}. If no such variable exists, all callables in the module (whose name does not start with an underscore) will be made available to the parser.

      - start_char (str, optional) – A character used to identify the beginning of a parseable function. Default is $.

      - escape_char (str, optional) – Prepend characters with this to have them not count as a function. Default is the backtick, \.

      - max_nesting (int, optional) – How many levels of nested function calls are allowed, to avoid exploitation. Default is 20.

      - **default_kwargs – These kwargs will be passed into all callables. These kwargs can be overridden both by kwargs passed direcetly to .parse and by kwargs given directly in the string $funcname call. They are suitable for global defaults that is intended to be changed by the user. To guarantee a call always gets a particular kwarg, pass it into .parse as **reserved_kwargs instead.

  `validate_callables`(callables)

    Validate the loaded callables. Each callable must support at least funcname(*args, **kwargs). property.

    Parameters

      callables (dict) – A mapping {“funcname”: callable, …} to validate

    Raises

      AssertionError – If invalid callable was found.

    Notes

    This is also a good method to override for individual parsers needing to run any particular pre-checks.

  `execute`(parsedfunc, raise_errors=False, **reserved_kwargs)

    Execute a parsed function

    Parameters

      - parsedfunc (_ParsedFunc) – This dataclass holds the parsed details of the function.

      - raise_errors (bool, optional) – Raise errors. Otherwise return the string with the function unparsed.

      - **reserved_kwargs – These kwargs are _guaranteed_ to always be passed into the callable on every call. It will override any default kwargs _and_ also a same-named kwarg given manually in the $funcname call. This is often used by Evennia to pass required data into the callable, for example the current Session for inlinefuncs.

    Returns

      any –

      The result of the execution. If this is a nested function, it

        can be anything, otherwise it will be converted to a string later. Always a string on un-raised error (the unparsed function string).

    Raises

      - ParsingError, any – A ParsingError if the function could not be

      - found, otherwise error from function definition. Only raised if –

      - raise_errors –

    Notes

    The kwargs passed into the callable will be a mixture of the default_kwargs passed into FuncParser.__init__, kwargs given directly in the $funcdef string, and the reserved_kwargs this function gets from .parse(). For colliding keys, funcdef-defined kwargs will override default kwargs while reserved kwargs will always override the other two.

  `parse`(string, raise_errors=False, escape=False, strip=False, return_str=True, **reserved_kwargs)

    Use parser to parse a string that may or may not have $funcname(*args, **kwargs) - style tokens in it. Only the callables used to initiate the parser will be eligible for parsing.

    Parameters

      - string (str) – The string to parse.

      - raise_errors (bool, optional) – By default, a failing parse just means not parsing the string but leaving it as-is. If this is True, errors (like not closing brackets) will lead to an ParsingError.

      - escape (bool, optional) – If set, escape all found functions so they are not executed by later parsing.

      - strip (bool, optional) – If set, strip any inline funcs from string as if they were not there.

      - return_str (bool, optional) – If set (default), always convert the parse result to a string, otherwise return the result of the latest called inlinefunc (if called separately).

      - **reserved_kwargs – If given, these are guaranteed to _always_ pass as part of each parsed callable’s kwargs. These override same-named default options given in **__init__ as well as any same-named kwarg given in the string function. This is because it is often used by Evennia to pass necessary kwargs into each callable (like the current Session object for inlinefuncs).

    Returns

      str or any –

      The parsed string, or the same string on error (if

        raise_errors is False). This is always a string

    Raises

      ParsingError – If a problem is encountered and raise_errors is True.

  `parse_to_any`(string, raise_errors=False, **reserved_kwargs)

    This parses a string and if the string only contains a “$func(…)”, the return will be the return value of that function, even if it’s not a string. If mixed in with other strings, the result will still always be a string.

    Parameters

      - string (str) – The string to parse.

      - raise_errors (bool, optional) – If unset, leave a failing (or unrecognized) inline function as unparsed in the string. If set, raise an ParsingError.

      - **reserved_kwargs – If given, these are guaranteed to _always_ pass as part of each parsed callable’s kwargs. These override same-named default options given in **__init__ as well as any same-named kwarg given in the string function. This is because it is often used by Evennia to pass necessary kwargs into each callable (like the current Session object for inlinefuncs).

    Returns

      any –

      The return from the callable. Or string if the callable is not

        given alone in the string.

    Raises

      ParsingError – If a problem is encountered and raise_errors is True.

    Notes

    This is a convenience wrapper for self.parse(…, return_str=False) which accomplishes the same thing.

    Examples

        from ast import literal_eval
        from evennia.utils.funcparser import FuncParser

        def ret1(*args, **kwargs):
            return 1

        parser = FuncParser({"lit": lit})

        assert parser.parse_to_any("$ret1()" == 1
        assert parser.parse_to_any("$ret1() and text" == '1 and text'

`evennia.utils.funcparser.``funcparser_callable_eval`(*args, **kwargs)

  Funcparser callable. This will combine safe evaluations to try to parse the incoming string into a python object. If it fails, the return will be same as the input.

  Parameters

    string (str) – The string to parse. Only simple literals or operators are allowed.

  Returns

    any – The string parsed into its Python form, or the same as input.

  Examples

  - $py(1) -> 1

  - $py([1,2,3,4] -> [1, 2, 3]

  - $py(3 + 4) -> 7

`evennia.utils.funcparser.``funcparser_callable_toint`(*args, **kwargs)

  Usage: $toint(43.0) -> 43

`evennia.utils.funcparser.``funcparser_callable_int2str`(*args, **kwargs)

  Usage: $int2str(1) -> ‘one’ etc, up to 12->twelve.

  Parameters

    number (int) – The number. If not an int, will be converted.

  Uses the int2str utility function.

`evennia.utils.funcparser.``funcparser_callable_an`(*args, **kwargs)

  Usage: $an(thing) -> a thing

  Adds a/an depending on if the first letter of the given word is a consonant or not.

`evennia.utils.funcparser.``funcparser_callable_add`(*args, **kwargs)

  Usage: $add(val1, val2) -> val1 + val2

`evennia.utils.funcparser.``funcparser_callable_sub`(*args, **kwargs)

  Usage: **$sub(val1, val2) -> val1 - val2

`evennia.utils.funcparser.``funcparser_callable_mult`(*args, **kwargs)

  Usage: $mult(val1, val2) -> val1 * val2

`evennia.utils.funcparser.``funcparser_callable_div`(*args, **kwargs)

  Usage: $mult(val1, val2) -> val1 / val2

`evennia.utils.funcparser.``funcparser_callable_round`(*args, **kwargs)

  Funcparser callable. Rounds an incoming float to a certain number of significant digits.

  Parameters

    - inp (str or number) – If a string, it will attempt to be converted to a number first.

    - significant (int) – The number of significant digits. Default is None - this will turn the result into an int.

  Returns

    any – The rounded value or inp if inp was not a number.

  Examples

  - $round(3.5434343, 3) -> 3.543

  - $round($random(), 2) - rounds random result, e.g 0.22

`evennia.utils.funcparser.``funcparser_callable_random`(*args, **kwargs)

  Funcparser callable. Returns a random number between 0 and 1, from 0 to a maximum value, or within a given range (inclusive).

  Parameters

    - minval (str, optional) – Minimum value. If not given, assumed 0.

    - maxval (str, optional) – Maximum value.

  Notes

  If either of the min/maxvalue has a ‘.’ in it, a floating-point random value will be returned. Otherwise it will be an integer value in the given range.

  Examples

  - $random() - random value [0 .. 1) (float).

  - $random(5) - random value [0..5] (int)

  - $random(5.0) - random value [0..5] (float)

  - $random(5, 10) - random value [5..10] (int)

  - $random(5, 10.0) - random value [5..10] (float)

`evennia.utils.funcparser.``funcparser_callable_randint`(*args, **kwargs)

  Usage: $randint(start, end):

  Legacy alias - always returns integers.

`evennia.utils.funcparser.``funcparser_callable_choice`(*args, **kwargs)

  FuncParser callable. Picks a random choice from a list.

  Parameters

    listing (list) – A list of items to randomly choose between. This will be converted from a string to a real list.

  Returns

    any – The randomly chosen element.

  Example

  - $choice([key, flower, house])

  - $choice([1, 2, 3, 4])

`evennia.utils.funcparser.``funcparser_callable_pad`(*args, **kwargs)

  FuncParser callable. Pads text to given width, optionally with fill-characters

  Parameters

    - text (str) – Text to pad.

    - width (int) – Width of padding.

    - align (str, optional) – Alignment of padding; one of ‘c’, ‘l’ or ‘r’.

    - fillchar (str, optional) – Character used for padding. Defaults to a space.

  Example

  - $pad(text, 12, r, ‘ ‘) -> ” text”

  - $pad(text, width=12, align=c, fillchar=-) -> “—-text—-”

`evennia.utils.funcparser.``funcparser_callable_crop`(*args, **kwargs)

  FuncParser callable. Crops ingoing text to given widths.

  Parameters

    - text (str, optional) – Text to crop.

    - width (str, optional) – Will be converted to an integer. Width of crop in characters.

    - suffix (str, optional) – End string to mark the fact that a part of the string was cropped. Defaults to […].

  Example

  - $crop(A long text, 10, […]) -> “A lon[…]”

  - $crop(text, width=11, suffix=’[…]) -> “A long[…]”

`evennia.utils.funcparser.``funcparser_callable_space`(*args, **kwarg)

  Usage: $space(43)

  Insert a length of space.

`evennia.utils.funcparser.``funcparser_callable_justify`(*args, **kwargs)

  Justify text across a width, default across screen width.

  Parameters

    - text (str) – Text to justify.

    - width (int, optional) – Defaults to default screen width.

    - align (str, optional) – One of ‘l’, ‘c’, ‘r’ or ‘f’ for ‘full’.

    - indent (int, optional) – Intendation of text block, if any.

  Returns

    str – The justified text.

  Examples

  - $just(text, width=40)

  - $just(text, align=r, indent=2)

`evennia.utils.funcparser.``funcparser_callable_left_justify`(*args, **kwargs)

  Usage: $ljust(text)

`evennia.utils.funcparser.``funcparser_callable_right_justify`(*args, **kwargs)

  Usage: $rjust(text)

`evennia.utils.funcparser.``funcparser_callable_center_justify`(*args, **kwargs)

  Usage: $cjust(text)

`evennia.utils.funcparser.``funcparser_callable_clr`(*args, **kwargs)

  FuncParser callable. Colorizes nested text.

  Parameters

    - startclr (str, optional) – An ANSI color abbreviation without the prefix |, such as r (red foreground) or [r (red background).

    - text (str, optional) – Text

    - endclr (str, optional) – The color to use at the end of the string. Defaults to |n (reset-color).

  Kwargs:

    color (str, optional): If given,

  Example

  - $clr(r, text, n) -> “|rtext|n”

  - $clr(r, text) -> “|rtext|n

  - $clr(text, start=r, end=n) -> “|rtext|n”

`evennia.utils.funcparser.``funcparser_callable_pluralize`(*args, **kwargs)

  FuncParser callable. Handles pluralization of a word.

  Parameters

    - singular_word (str) – The base (singular) word to optionally pluralize

    - number (int) – The number of elements; if 1 (or 0), use singular_word as-is, otherwise use plural form.

    - plural_word (str, optional) – If given, this will be used if number is greater than one. If not given, we simply add ‘s’ to the end of singular_word.

  Example

  - $pluralize(thing, 2) -> “things”

  - $pluralize(goose, 18, geese) -> “geese”

`evennia.utils.funcparser.``funcparser_callable_search`(*args, caller=None, access='control', **kwargs)

  FuncParser callable. Finds an object based on name or #dbref. Note that this requries the parser be called with the caller’s Session for proper security. If called without session, the call is aborted.

  Parameters

    query (str) – The key or dbref to search for.

  Keyword Arguments

    - return_list (bool) – If set, return a list of objects with 0, 1 or more matches to query. Defaults to False.

    - type (str) – One of ‘obj’, ‘account’, ‘script’

    - caller (Entity) – Supplied to Parser. This is required and will be passed into the access check for the entity being searched for. The ‘control’ permission is required.

    - access (str) – Which locktype access to check. Unset to disable the security check.

  Returns

    any – An entity match or None if no match or a list if return_list is set.

  Raises

    ParsingError – If zero/multimatch and return_list is False, or caller was not passed into parser.

  Examples

  - “$search(#233)”

  - “$search(Tom, type=account)”

  - “$search(meadow, return_list=True)”

`evennia.utils.funcparser.``funcparser_callable_search_list`(*args, caller=None, access='control', **kwargs)

  Usage: $objlist(#123)

  Legacy alias for search with a return_list=True kwarg preset.

`evennia.utils.funcparser.``funcparser_callable_you`(*args, caller=None, receiver=None, mapping=None, capitalize=False, **kwargs)

  Usage: $you() or $you(key)

  Replaces with you for the caller of the string, with the display_name of the caller for others.

  Keyword Arguments

    - caller (Object) – The ‘you’ in the string. This is used unless another you-key is passed to the callable in combination with mapping.

    - receiver (Object) – The recipient of the string.

    - mapping (dict, optional) – This is a mapping {key:Object, …} and is used to find which object $you(key) refers to. If not given, the caller kwarg is used.

    - capitalize (bool) – Passed by the You helper, to capitalize you.

  Returns

    str – The parsed string.

  Raises

    ParsingError – If caller and receiver were not supplied.

  Notes

  The kwargs should be passed the to parser directly.

  Examples

  This can be used by the say or emote hooks to pass actor stance strings. This should usually be combined with the $conj() callable.

  - With a grin, $you() $conj(jump) at $you(tommy).

  The caller-object will see “With a grin, you jump at Tommy.” Tommy will see “With a grin, CharName jumps at you.” Others will see “With a grin, CharName jumps at Tommy.”

`evennia.utils.funcparser.``funcparser_callable_you_capitalize`(*args, you=None, receiver=None, mapping=None, capitalize=True, **kwargs)

  Usage: $You() - capitalizes the ‘you’ output.

`evennia.utils.funcparser.``funcparser_callable_conjugate`(*args, caller=None, receiver=None, **kwargs)

  Usage: $conj(word, [options])

  Conjugate a verb according to if it should be 2nd or third person.

  Keyword Arguments

    - caller (Object) – The object who represents ‘you’ in the string.

    - receiver (Object) – The recipient of the string.

  Returns

    str – The parsed string.

  Raises

    ParsingError – If you and recipient were not both supplied.

  Notes

  Note that the verb will not be capitalized. It also assumes that the active party (You) is the one performing the verb. This automatic conjugation will fail if the active part is another person than ‘you’. The caller/receiver must be passed to the parser directly.

  Examples

  This is often used in combination with the $you/You( callables.

  - With a grin, $you() $conj(jump)

  You will see “With a grin, you jump.” Others will see “With a grin, CharName jumps.”

`evennia.utils.funcparser.``funcparser_callable_pronoun`(*args, caller=None, receiver=None, capitalize=False, **kwargs)

  Usage: $pron(word, [options])

  Adjust pronouns to the expected form. Pronouns are words you use instead of a proper name, such as ‘him’, ‘herself’, ‘theirs’ etc. These look different depending on who sees the outgoing string.

  The parser maps between this table …

  1st/2nd person | Subject Pronoun | Object Pronoun | Possessive Adjective | Possessive Pronoun | Reflexive Pronoun
  --- | --- | --- | --- | --- | ---
  1st person | I | me | my | mine | myself
  1st person plural | we | us | our | ours | ourselves
  2nd person | you | you | your | yours | yourself
  2nd person plural | you | you | your | yours | yourselves

  … and this table (and vice versa).

  3rd person | Subject Pronoun | Object Pronoun | Possessive Adjective | Possessive Pronoun | Reflexive Pronoun
  --- | --- | --- | --- | --- | ---
  3rd person male | he | him | his | his | himself
  3rd person female | she | her | her | hers | herself
  3rd person neutral | it | it | its |  | itself
  3rd person plural | they | them | their | theirs | themselves

  This system will examine caller for either a property or a callable .gender to get a default gender fallback (if not specified in the call). If a callable, .gender will be called without arguments and should return a string male/female/neutral/plural (plural is considered a gender for this purpose). If no gender property/callable is found, neutral is used as a fallback.

  The pronoun-type default (if not specified in call) is subject pronoun.

  Parameters

    - pronoun (str) – Input argument to parsed call. This can be any of the pronouns in the table above. If given in 1st/second form, they will be mappped to 3rd-person form for others viewing the message (but will need extra input via the gender, see below). If given on 3rd person form, this will be mapped to 2nd person form for caller unless viewpoint is specified in options.

    - options (str, optional) –

      A space- or comma-separated string detailing pronoun_type, gender/plural and/or viewpoint to help the mapper differentiate between non-unique cases (such as if you should become him or they). Allowed values are:

      - subject pronoun/subject/sp (I, you, he, they)

      - object pronoun/object//op (me, you, him, them)

      - possessive adjective/adjective/pa (my, your, his, their)

      - possessive pronoun/pronoun/pp (mine, yours, his, theirs)

      - male/m

      - female/f

      - neutral/n

      - plural/p

      - 1st person/1st/1

      - 2nd person/2nd/2

      - 3rd person/3rd/3

  Keyword Arguments

    - caller (Object) – The object creating the string. If this has a property ‘gender’, it will be checked for a string ‘male/female/neutral’ to determine the 3rd person gender (but if pronoun_type contains a gender component, that takes precedence). Provided automatically to the funcparser.

    - receiver (Object) – The recipient of the string. This being the same as caller or not helps determine 2nd vs 3rd-person forms. This is provided automatically by the funcparser.

    - capitalize (bool) – The input retains its capitalization. If this is set the output is always capitalized.

  Examples

  Input | caller sees | others see
  --- | --- | ---
  $pron(I, m) | I | he
  $pron(you,fo) | you | her
  $pron(yourself) | yourself | itself
  $pron(its) | your | its
  $pron(you,op,p) | you | them

  Notes

  There is no option to specify reflexive pronouns since they are all unique and the mapping can always be auto-detected.

`evennia.utils.funcparser.``funcparser_callable_pronoun_capitalize`(*args, caller=None, receiver=None, capitalize=True, **kwargs)

  Usage: $Pron(word, [options]) - always maps to a capitalized word.