Documentation

Filter Conspectus

Quick-reference tables for symbol filters, named filters, keywords, precedence, and order-of-evaluation rules.

List of Symbol Filters

Filter Type Brief Description
. Set Piece designator representing all 64 squares.
_ Set Piece designator for unoccupied squares.
- Numeric Unary negation or binary subtraction.
` Any Identity operator.
: Any Evaluate RHS filter in the context of the LHS position.
[] Set Piece designator representing no squares.
[] Varies String slicing or dictionary access.
~~ String Regular expression pattern matching and extraction.
\i String Text of the ith captured group.
\-i Numeric Starting index of the ith captured group.
\{name} String Text of the specified named captured group.
\-{name} Numeric Starting index of the specified named captured group.
\n String Predefined literal representing the newline character.
\r String Predefined literal representing the carriage return character.
\t String Predefined literal representing the tab character.
\" String Predefined literal representing the double quote character.
\\ String Predefined literal representing the backslash character.
~ Set Set complement of the Set operand.
& Set Set intersection of two Set operands.
& Set Positional intersection of two Positions.
| Set Set union of two Set operands.
+ Num/Str Numeric addition or string concatenation.
* Numeric Numeric multiplication.
/ Numeric Numeric division.
% Numeric Numeric remainder (modulus).
# Numeric Cardinality of a Set, String, or Dictionary operand.
== Varies Equality comparison.
!= Boolean Inequality comparison.
< Varies Less-than comparison.
<= Varies Less-than-or-equal comparison.
> Varies Greater-than comparison.
>= Varies Greater-than-or-equal comparison.
= Boolean Assign the RHS value to the LHS variable.
=? Boolean Assign RHS to LHS only if RHS is non-empty set.
+= Boolean Compound addition or concatenation assignment.
-= Boolean Compound subtraction assignment.
*= Boolean Compound multiplication assignment.
/= Boolean Compound division assignment.
%= Boolean Compound modulus assignment.
&= Boolean Compound intersection assignment.
|= Boolean Compound union assignment.
[]= Boolean String slice or dictionary entry assignment.
() Varies Parentheses used to modify filter precedence.

List of Named Filters

Filter Type Brief Description
abs Numeric Absolute value of provided argument.
ancestor Boolean Determine if one position is the ancestor of another.
and Boolean true if LHS and RHS filters both match the position.
anydirection Set Direction filter for rays of any direction.
ascii Num/Str Convert between an ASCII character and its numeric ordinal value.
assert Boolean Terminates processing if the provided condition does not match.
attackedby Set Set of squares attacked by the specified pieces.
attacks Set Set of pieces attacking the specified squares.
between Set Set of squares between squares in the specified sets.
black Numeric Always yields the numeric value -1.
btm Boolean true if it is Black to move.
check Boolean true if the current side is in check.
child Position The specified child position of the current position.
colortype Numeric Numeric representation of piece residing on the specified square.
commandpipe String Send a request to an external program and receive a response.
comment Boolean Add the specified PGN comment to the current position.
connectedpawns Set The set of connected pawns in the current position.
consecutivemoves Numeric Find the longest series of consecutive moves in two sequences.
currentfen String A normalized FEN representation of the current position.
currentmutation String Textual representation of imaginary position mutations in effect.
currentposition Position The current position.
currenttransform String Textual representation of transforms in effect.
cqlbegin Boolean Defines a block to run at the beginning of processing.
cqlend Boolean Defines a block to run at the end of processing.
dark Set The set of dark squares in the provided square set.
date String The value of the Date PGN tag, if present.
depth Numeric The variation depth of the current position.
descendant Boolean Determine if one position is the descendant of another.
diagonal Set Direction filter for diagonal rays.
dictionary Boolean Declares a dictionary variable.
distance Numeric The number of moves that separate two positions.
doubledpawns Set The set of doubled pawns in the current position.
down Set Direction filter for rays in the down direction.
echo Bool/Num Detect positions with a given relationship to the current position.
eco String The value of the ECO PGN tag, if present.
elo Numeric The rating of the specified player if provided in the PGN game.
event String The value of the Event PGN tag, if present.
eventdate String The value of the EventDate PGN tag, if present.
false Boolean The Boolean value false.
fen Boolean Compare the current position to a FEN-line pattern string.
file Numeric The index of the file component of the provided square.
find Bool/Num Search previous or future positions for target filter matches.
flip Varies Apply rotation and reflection transforms to a target filter.
flipcolor Varies Apply color transforms to a target filter.
fliphorizontal Varies Apply horizontal bisection reflection transforms to a target filter.
flipvertical Varies Apply vertical bisection reflection transforms to a target filter.
function Boolean Defines the specified function.
gamenumber Numeric The index of the current game in its containing PGN file.
halfmoveclock Numeric The number of half-moves since a capture or pawn move.
hascomment String Deprecated alias for originalcomment.
hhdb Varies Provides an interface for the HHdbVI and HHdbVII databases.
horizontal Set Squares in the horizontal rays emanating from the provided set.
if Any Conditionally execute a filter.
imagine Any Execute a filter on modified version of the current position.
in Boolean true if the LHS set or string exists in the RHS set or string filter.
indexof Numeric Obtain the index of one string in another string, if present.
initial Boolean true if the current position is the initial position.
initialposition Position The initial position for the current game.
int Numeric Attempts to convert a string to an integer value.
isbound Boolean true if the specified variable has a non-None value.
isolatedpawns Set The set of isolated pawns in the current position.
isunbound Boolean true if the specified variable has a value of None.
key Boolean Iterate over the keys in a dictionary.
lca Position The latest-common ancestor of two positions.
left Set Squares located along a ray moving left from the provided set.
legalposition Boolean Check if the board state represents a legal position.
light Set The set of light squares in the provided square set.
line Num/Pos Search for a sequence of positions matching a specified pattern.
loop Boolean Execute a target filter until it fails to match the position.
lowercase String Convert all uppercase characters to lowercase characters.
maindiagonal Set Squares in the maindiagonal rays emanating from the provided set.
mainline Boolean true if this position exists in the main line.
makesquare Set The square on the intersection of the given file and rank.
mate Boolean true if the current side is checkmated.
max Num/Str The largest of multiple Numeric or String values.
message Boolean Emit a message with the specified text.
min Num/Str The smallest of multiple Numeric or String values.
move Multiple Inspect played or hypothetical moves and resulting positions.
movenumber Numeric The current move number.
northeast Set Squares in the ray moving northeast from the provided set.
northwest Set Squares in the ray moving northwest from the provided set.
not Boolean false if the target filter matches the position, otherwise true.
notransform Any Suppress the effect of enclosing transforms on target filter.
offdiagonal Set Squares in the offdiagonal rays emanating from the provided set.
or Boolean true if either the LHS or RHS filter matches the position.
originalcomment String The original comment associated with the current position.
orthogonal Set Squares in the orthogonal rays emanating from the provided set.
parent Position The position that is the parent of the current position, if any.
passedpawns Set The set of passed pawns in the current position.
persistent Boolean Declares a persistent Numeric, Set, or String variable.
piece Bool/Set Declares a piece variable or iterates over pieces on squares.
pieceid Numeric The unique PieceID of the piece residing on the given square.
pin Bool/Set Find pins in the current position matching specified criteria.
player String The value of the specified player from the PGN file, if present.
ply Numeric The ply of the current position.
position Position The position corresponding to the provided position ID.
positionid Numeric The position ID of the current position.
power Numeric The combined value of the pieces occupying the given squares.
promotedpieces Set The squares occupied by promoted pieces.
rank Numeric The rank of the specified square.
ray Set Search for the specified pieces arranged along a ray.
reachableposition Boolean true if the current position is reachable in Standard chess.
readfile String The text contained in the specified file.
removecomment Boolean Remove original comments associated with the current position.
removetag Boolean Removes the specified tag from the current game.
replace String Replaces instances of matching pattern in a string.
result Boolean true if the game termination token matches the given result.
reversecolor Varies Apply reversed-color transform to a target filter.
right Set Squares located along a ray moving right from the provided set.
rotate45 Varies Apply 45°{} rotation transforms to a target filter.
rotate90 Varies Apply 90°{} transforms to a target filter.
saveposition Position Save the current imaginary position.
settag Boolean Set the specified PGN tag of the current game to the given value.
shift Varies Apply unrestricted shift transforms to a target filter.
shifthorizontal Varies Apply horizontal shift transforms to a target filter.
shiftvertical Varies Apply vertical shift transforms to a target filter.
sidetomove Numeric The numeric value associated with the color that has the move.
site String The value of the Site PGN tag, if present.
southeast Set Squares located along a southeast ray emanating from a given set.
southwest Set Squares located along a southwest ray emanating from a given set.
sqrt Numeric The integral portion of the square root of the given value.
square Bool/Set Iterate over the squares in the provided set.
stalemate Boolean true if the current side to move is stalemated.
standardfen String The standard FEN representation of the current position.
str String The concatenation of the stringized arguments provided.
string Boolean Iterate over the String keys in a dictionary.
tag String The original value of the specified PGN tag for the current game.
terminal Boolean true if this position does not have any children.
true Boolean The Boolean value true.
type Numeric Numeric value of piece type occupying the specified square.
unbind Boolean Remove the value associated with a variable making it None.
up Set Squares located along a ray moving up from the provided set.
uppercase String Convert all lowercase characters to uppercase characters.
variant Boolean true if this game is a non-standard chess variant.
variantdraw Boolean true if the game is a draw due to variant-specific criteria.
variantend Boolean true if the game is over due to a variant-specific condition.
variantloss Boolean true if the game is lost due to a variant-specific condition.
variantwin Boolean true if the game is won due to a variant-specific condition.
variation Boolean true if the current position is part of a variation.
vertical Set Squares in the vertical rays emanating from the provided set.
virtualmainline Boolean true if the current position is a virtual mainline position.
while Boolean Execute target filter while the specified condition is true.
white Numeric Always yields the numeric value 1.
writefile Boolean Write the specified string to the given file.
wtm Boolean true if it is White to move.
xray Set Search for x-rays involving the specified pieces.
year Numeric The year the current game was played, if available.
zobristkey String The Zobrist hash key of the current position.

List of Keywords

The table below lists all the keywords used by CQLi including non-filter keywords such as keyword parameters. Keywords marked with * are CQLi extensions. User-defined identifiers (variable and function names) may not have the name of a keyword.

abs doubledpawns lastposition pin southeast
all down lca place* southwest
ancestor drop left player sqrt
and echo legal ply square
anydirection eco legalposition* position stalemate
ascii elo light positionid standardfen*
assert else line power str
attacked enpassant loop previous string
attackedby enpassantsquare lowercase primary sum*
attacks event maindiagonal promote swap*
between eventdate mainline promotedpieces* tag
black false makesquare pseudolegal terminal
btm fen matchcount quiet then
by file matchstring rank through
capture find mate ray to
castle firstmatch max reachableposition* true
check flip message readfile type
child flipcolor min removecomment unbind
colortype fliphorizontal move removetag* up
commandpipe* flipvertical movenumber replace* uppercase
comment from nestban restrict* variant*
connectedpawns function noclobber* result variantdraw*
consecutivemoves gamenumber nolinearize* reverse* variantend*
count halfmoveclock* nonatomic* reversecolor variantloss*
cql hascomment northeast right variantwin*
cqlbegin hhdb northwest rotate45 variation
cqlend* horizontal not rotate90 variations
curpos* if notransform saveposition* vertical
currentfen* imagine* null secondary virtualmainline
currentmutation* in offdiagonal set* while
currentposition indexof or settag white
currenttransform initial originalcomment shift writefile
dark initialposition orthogonal shifthorizontal wtm
date input output shiftvertical xray
depth int parent sidetomove year
descendant isbound passedpawns silent zobristkey*
diagonal isolatedpawns persistent singlecolor
dictionary isunbound piece site
distance key* pieceid sort

Filter Precedence

The following table lists the precedence of CQLi filters. Filters with a smaller precedence number bind more tightly than filters with a higher precedence number. All filters have left-to-right associativity except for the with-position (:) filter and the relational operator filters which are right-to-left associative. Parentheses or braces may be used to modify filter precedence, e.g. 1 + 2 * 37 but (1 + 2) * 39. There is never an evaluation performance cost associated with parentheses or braces used in this way.

Precedence Filter Notes
1 -
`
tag
Unary minus
Identity operator
2 : (right-to-left associative)
3 [] (precedence of LHS)
4 ~~ (precedence of LHS)
5 dark
light
direction filters


up, down, left, right, northeast, northwest, southeast, southwest, diagonal, orthogonal, vertical, horizontal, maindiagonal, offdiagonal, anydirection
6 move
pin
(from, to, capture, enpassant, and ‘:’ parameters)
(from, to, and through parameters)
7 attacks
attackedby

8 ~
9 &
10 |
11 between
colortype
file
in parameters
lowercase
piece
pieceid
power
rank
type
uppercase
(each argument of the between filter)


The in parameters of the piece, square, and string filters

Piece assignment




12 / * % Division, multiplication, and remainder
13 + - Addition and subtraction
14 #
int
readfile
Set cardinality
15 abs
ascii
makesquare
position
sqrt
[]=
/=*=%=
+=-=
&=|==?





Dictionary/slice assignment

Compound assignment, conditional set assignment
16 <<===
>>=!=
Relational operator filters (right-to-left associative)
17 in set/string membership filter, not in parameter
18 not
19 and
20 or
21 find
=
transforms
The body of the find filter
RHS of simple assignment
The body of transform filters
22 {}
assert
comment
echo
if/then/else
imagine
line
message
persistent
sort
str
while
Constituents of a compound filter

Argument(s) of a comment filter
The body of echo
The condition of if and bodies of then and else
Body and set filters of an imagine filter
Constituents of a line filter
Argument(s) of a message filter

Body of a sort filter
Argument(s) of a str filter
Condition of a while filter
iterator bodies The bodies of loop, piece, square, string, and while filters
user-defined functions The arguments of user-defined functions
arguments of function-like filters The parenthesized arguments of ancestor, child, consecutivemoves, descendant, distance, indexof, lca, makesquare, min, max, min, ray, settag, writefile, and xray

Type-induced Precedence Vitiation of Binary Infix Filters

When parsing using the precedence in the above table yields a LHS operand with a type that is not appropriate for a given binary infix filter, CQLi will attempt to expand the LHS argument to the next-highest grammar production in order to find a LHS filter with the appropriate type. This has the effect of causing the filter to bind less tightly than it normally would but only with regards to the LHS expression. This process of seeking a higher-order production will continue until there is no such production available at which point a syntax error will be issued. For example, using precedence vitiation, the query:

# str a1 * 5

is parsed as #( str a1 ) * 5 despite the precedence suggesting it should be parsed as #( str (a1 * 5) ) because a1 has Set type which is not a valid type for a LHS operand to *. In this example, when * receives a LHS operand of a1, it rejects it and instead receives the next-highest-order production of str a1. This operand has String type which is also inappropriate for * so it too is rejected and finally it receives # str a1 as a LHS operand which is the correct type for * so it becomes the LHS operand of * in the expression. This same mechanism is what allows position 0 : wtm to be parsed as (position 0) : wtm even though the LHS of : binds tighter than the RHS of position.

This behavior is provided to support backwards compatibility with CQL 6.1 which behaves the same way. When this behavior is employed, an info message will be emitted by CQLi indicating that precedence vitiation is being employed to satisfy the type requirements of a binary filter. Use -w 3 to see such messages. Nodes that were subjected to precedence vitiation are also noted in the dumped AST.

The table below lists the binary infix filters that participate in this scheme in order to obtain an amenable LHS operand and the corresponding satisfactory LHS operand types.

Filter Expected LHS Type
attackedby Set
attacks Set
in Set or String
|& Set
~~ String
[] (string slicing) String
+ String or Numeric (see note below)
- Numeric
*/% Numeric
: Position
!=== Numeric, Set, String, or Position
<<=>>= Numeric, Set, String, or Position

Finally, the + filter also exhibits the above-described precedence vitiating behavior when the LHS and RHS expressions are not the same type. This allows e.g. both int "24" + 1 and int "24" + "1" to be parsed without error, the former being interpreted as (int "24") + 1 despite the fact that + binds more tightly than int.

Order of Evaluation

The precedence rules dictate that e.g. x + y * z is processed as x + (y * z) but they do not prescribe an evaluation order, e.g. which of x, y, or z is evaluated first. The evaluation order may influence the result for filters that have side effects (such as issuing a message, adding a comment, changing a variable value, or writing to a file). The architecture of the CQL language does not lend itself to many situations where this is a practical concern but it should be noted that unless otherwise specified in the description of a filter, the evaluation order of filters is unspecified. For example, in the below query:

$result = ""
function foo($value) { $result += str(value) value }
foo(foo(1) + foo(2))

the function foo takes a value, appends the string representation of the value to $result, and then returns the same value. After the call foo(foo(1) + foo(2)), $result will contain the digits 123 but the order of these digits is not specified. In particular, the last digit will be 3 (because the inner calls must be evaluated to determine the value that the outer call receives) but it is not specified whether the LHS or RHS operand to the + filter is evaluated first so $result may be either 123 or 213 after the call. It is recommended to avoid combining multiple filters containing side effects in a larger filter where the order of evaluation may influence the final result.