---
title: BQL grammar
summary: The Xtext grammar of BQL as shipped in this release.
order: 900
---

# BQL grammar

The Xtext grammar the BIM Query Language parser is generated from, exactly as shipped in this release. Rules read top-down; `=>` marks a syntactic predicate, `+=` collects a list, `?=` a boolean flag. Terminals not declared here (`ID`, `STRING`, `INT`, comments) come from the common Xtext terminals; the languages that build on BQL inherit every rule from it.

```text {#grammar}
grammar nl.bimbase.bimworks.Bql with org.eclipse.xtext.common.Terminals

import "http://www.eclipse.org/emf/2002/Ecore" as ecore

generate bql "http://www.bimbase.nl/bimworks/Bql"

// MODELS: a model search (BimRepository/docs/model-search-design.md §5.3) — the rows are the
// searched models, not their objects. The WHERE is a predicate over model terms
// (model.count(...), model.SUM(... WHERE ...), model.<attribute>), or — when it contains no model
// term at all — an object condition read as "models that have such objects". Only the model
// search (SearchModelsAdvanced) runs it; Query2 refuses it.
Bql:
	{Bql}
	((models?="MODELS" ("GET" features+=SingleFeature ("," features+=SingleFeature)*)? ("WHERE" where=BooleanExpression)?)
		| ("GET" features+=SingleFeature ("," features+=SingleFeature)* ("WHERE" where=BooleanExpression)?) | =>where=BooleanExpression)?
	(groupBy=GroupBy)?
	(orderBy=OrderBy)?
	("LIMIT" limit=LONG)?
	("OFFSET" offset=LONG)?
	("USING" using=Using)?
;

MinimalBql:
	{MinimalBql}
	(where=BooleanExpression)? 
	(groupBy=GroupBy)?
	(orderBy=OrderBy)?
	("LIMIT" limit=LONG)?
	("OFFSET" offset=LONG)?
;

Using:
	{Using}
	// Split keywords ("LENGTH_UNIT" "="), not glued ("LENGTH_UNIT="): whitespace around
	// the = is allowed, consistent with every other = in the language.
	// Unordered group (&) since 2026-07-23 (P10): the unit clauses may appear in any order,
	// each at most once — previously the fixed order length, area, volume, mass, temperature
	// was silently mandatory and "USING MASS_UNIT=kg LENGTH_UNIT=m" failed to parse.
	(
		("LENGTH_UNIT" "=" lengthUnit=LengthUnit)? &
		("AREA_UNIT" "=" areaUnit=AreaUnit)? &
		("VOLUME_UNIT" "=" volumeUnit=VolumeUnit)? &
		("MASS_UNIT" "=" massUnit=MassUnit)? &
		("TEMPERATURE_UNIT" "=" temperatureUnit=TemperatureUnit)?
	)
;

SingleFeature:
	// => commits to the alias whenever AS follows — safe because AS is used
	// nowhere else in the language (silences a phantom ANTLR ambiguity, same
	// as UNIT in FeatureWithOptionalUnit).
	feature=FeatureOrFunctionOverFeature (=>"AS" az=(ID | STRING))?
;

FeatureOrFunctionOverFeature:
	FeatureWithOptionalUnit | AggregateFunctionOverFeature 
;

FeatureWithOptionalUnit:
	// "UNIT" instead of "IN": distinct keyword for unit conversion, see
	// XTEXT-REGENERATION-ISSUES.md 3b. The => predicate commits to the unit
	// clause whenever UNIT follows — safe because UNIT is used nowhere else —
	// and silences a phantom ANTLR ambiguity at this decision.
	// The feature is a full GET-side arithmetic expression since docs/bql-expressions-design.md
	// §3.5 — "GET a / 2 UNIT m3 AS Half" reuses this wrapper, giving expressions UNIT and AS
	// for free. A bare feature keeps its exact AST; only the static type widened.
	feature=Expression (=>"UNIT" unit=Unit)?
;

enum LengthUnit:
	LENGTH_NONE |
	MM="mm" |
	CM="cm"	|
	DM="dm" |
	M="m" |
	KM="km" |
	IN="in" |
	FOOT="ft" |
	YARD="yd" |
	MILE="mi"
;

enum AreaUnit:
	AREA_NONE |
	MM2="mm2" |
	CM2="cm2" |
	DM2="dm2" |
	M2="m2" |
	KM2="km2" |
	INCH2="in2" |
	YARD2="yd2" |
	FOOT2="ft2" |
	ACRE="ac" |
	MILE2="mi2"
;

enum VolumeUnit:
	VOLUME_NONE |
	MM3="mm3" |
	CM3="cm3" |
	DM3="dm3" |
	M3="m3" |
	INCH3="in3" |
	FOOT3="ft3" |
	YARD3="yd3" |
	LITRE="l"
;

enum MassUnit:
	MASS_NONE |
	MG="mg" |
	CG="cg" |
	G="g" |
	KG="kg"
;

enum TemperatureUnit:
	TEMPERATURE_NONE |
	DC="dc"
;

// Plane angles (docs/model-compare-design.md §5.5: rotation tolerances such as WITHIN 0.5 deg).
// The FeatureDB keeps angles canonical in degrees (BasicUnit.toCanonical).
enum AngleUnit:
	ANGLE_NONE |
	DEG="deg" |
	RAD="rad"
;

Unit returns Unit:
	{Unit} (
		lengthUnit=LengthUnit |
		areaUnit=AreaUnit |
		volumeUnit=VolumeUnit |
		massUnit=MassUnit |
		temperatureUnit=TemperatureUnit |
		angleUnit=AngleUnit
	)
;

AggregateFunctionOverFeature:
	function=(AggregationFunction)
;

AggregationFunction:
	CountFunction | NumericAggregateFunction | CollectFunction | FirstFunction | ShapeAggregate
;

NumericAggregateFunction:
	MinFunction | MaxFunction | AvgFunction | MedianFunction | ModeFunction | RangeFunction | StdDevFunction | SumFunction
;

CountFunction:
	{CountFunction} "COUNT" "(" (feature=Feature) ")"
;

// The group's deterministic sample member (lowest version uuid, then lowest oid):
// FIRST(qid) in a GROUP BY query yields one representative per group — e.g. one
// preview render per unique geometry in BRL reports. v1 resolves only qid
// (BqlValidator warns on other features).
FirstFunction:
	{FirstFunction} "FIRST" "(" (feature=Feature) ")"
;

// The numeric aggregates take a full GET-side arithmetic expression since
// docs/bql-expressions-design.md §3.5 — "AVG(a / b)". A bare feature keeps its exact AST.
// COUNT/FIRST/COLLECT deliberately keep Feature arguments (counting an expression is
// meaningless — COUNT ignores its argument anyway).
MinFunction returns NumericAggregateFunction:
	{MinFunction} "MIN" "(" (feature=Expression) ")"
;

MaxFunction returns NumericAggregateFunction:
	{MaxFunction} "MAX" "(" (feature=Expression) ")"
;

MedianFunction returns NumericAggregateFunction:
	{MedianFunction} "MEDIAN" "(" (feature=Expression) ")"
;

RangeFunction returns NumericAggregateFunction:
	{RangeFunction} "RANGE" "(" (feature=Expression) ")"
;

StdDevFunction returns NumericAggregateFunction:
	{StdDevFunction} "STDDEV" "(" (feature=Expression) ")"
;

ModeFunction returns NumericAggregateFunction:
	{ModeFunction} "MODE" "(" (feature=Expression) ")"
;

AvgFunction returns NumericAggregateFunction:
	{AvgFunction} "AVG" "(" (feature=Expression) ")"
;

SumFunction returns NumericAggregateFunction:
	{SumFunction} "SUM" "(" feature=Expression ")"
;

// COLLECT(DISTINCT ...): every different value (or combination of values, for several features)
// once; objects without a value add nothing. A plain COLLECT has one entry per object: the type
// names of 88,000 objects were 29 MB of response for what are a few hundred names.
CollectFunction:
	{CollectFunction} "COLLECT" "(" (distinct?="DISTINCT")? (features+=GetFeature ("," features+=GetFeature)*) ")"
;

BinFunction:
	{BinFunction} "BIN" "(" feature=GetFeature "," size=DoubleWithUnitLiteralTyped ")"
;

// Arithmetic expressions (docs/bql-expressions-design.md §3.1). Two chains sharing the same
// operator AST classes (Addition, Subtraction, Multiplication, Division — one evaluator):
// the GET-side chain (`Expression`, also the BOX/CYLINDER/CONE/SPHERE arguments) whose
// operands are GetFeatures, and the WHERE-side chain (`WhereExpression`) whose operands are
// the TerminalExpression condition features. Two precedence levels, left-associative
// (restructured from the former four levels per docs/bql-language-analysis.md §7).
// Lexer caveat (bql-language-analysis.md 3.8): the sign lives inside the LONG/DOUBLE
// terminals, so `a -3` lexes as two literals — write `a - 3`.
Expression returns Expression:
	GetAddSub
;

GetAddSub returns Expression:
    GetMulDiv (=>({Addition.left=current} '+' | {Subtraction.left=current} '-') right=GetMulDiv)*;

GetMulDiv returns Expression:
    GetPrimary (=>({Multiplication.left=current} '*' | {Division.left=current} '/') right=GetPrimary)*;

GetPrimary returns Expression:
  // => commits integers to the long literal (the double literal also accepts LONG via DoubleOrLong)
  =>LongWithUnitLiteralTyped |
  DoubleWithUnitLiteralTyped |
  AbsFunction |
  ValueFunction |
  CaseExpression |
  GetFeature |
  "(" GetAddSub ")";

WhereExpression returns Expression:
	WhereAddSub
;

WhereAddSub returns Expression:
    WhereMulDiv (=>({Addition.left=current} '+' | {Subtraction.left=current} '-') right=WhereMulDiv)*;

WhereMulDiv returns Expression:
    WherePrimary (=>({Multiplication.left=current} '*' | {Division.left=current} '/') right=WherePrimary)*;

WherePrimary returns Expression:
  =>LongWithUnitLiteralTyped |
  DoubleWithUnitLiteralTyped |
  WhereAbsFunction |
  WhereValueFunction |
  WhereCaseExpression |
  RelationAggregate |
  ConditionFeature |
  "(" WhereAddSub ")";

// Relation aggregate as an expression operand (docs/bql-expressions-design.md §3.6): one
// numeric aggregate over the object's related set, optionally filtered —
//   calculated.quantity.floorArea * 0.1 > spaceBoundary(SUM(quantity.*.Area) WHERE type = IFCWINDOW)
// The aggregate's argument evaluates against each RELATED object; the outer object is not
// addressable inside (no correlation in v1). Same surface shape as the GET sub-feature form
// (children(SUM(x) WHERE ...)), deliberately restricted here: exactly one numeric aggregate,
// no GROUP BY/ORDER BY/LIMIT. COUNT stays with the path filters (children.count(...)).
// SUM over an empty related set is 0; the other aggregates have no value then. Reuses only
// existing keywords, so no new reserved words. After the relation keyword, "(" selects this
// rule while "." (or nothing) selects the path expressions — a two-token decision.
RelationAggregate returns Expression:
	{RelationAggregate} relation=MultiSubFeatureType "(" function=RelationAggregateFunction ("WHERE" where=BooleanExpression)? ")"
;

// A numeric aggregate, or a geometric one read through a numeric member (validated): what a
// relation operand of an expression can fold.
RelationAggregateFunction returns AggregationFunction:
	NumericAggregateFunction | ShapeAggregate
;

// Geometric aggregates (docs/bql-geometric-aggregates-design.md §4): the union of the geometry of
// the objects an aggregate ranges over — the matched objects of a GET, the related set of a
// relation — read through a member: allChildren(SLICE(0 mm).area WHERE type IN (IFCWALL, IFCSLAB)).
// SLICE cuts horizontally at a height, PROJECTION projects along a normal (the plan by default).
// Without a member (GET only) the shape's measures as one record. The options are keyword-led,
// in any order, each at most once (BqlValidator.checkShapeOptions): a list rather than an
// unordered group, which breaks the serializer with a leading action.
ShapeAggregate:
	{ShapeAggregate} shape=Shape (=>"." member=ShapeMember)?
;

// Member names are a closed list checked by BqlValidator (SHAPE_MEMBERS), not keywords: "wkt",
// "parts", "holes" and "geojson" stay usable as unquoted identifiers elsewhere. Those that already
// are keywords are listed. The optional CRS is for wkt and geojson: .wkt("EPSG:28992").
ShapeMember:
	{ShapeMember} name=(ID | "area" | "perimeter" | "length" | "width" | "figure") (=>"(" crs=STRING ")")?
;

Shape:
	SliceShape | ProjectionShape
;

// The heights take a parameter too (BqlParameterBinder, a number in mm): SLICE($height), ABOVE $ground
SliceShape:
	{SliceShape} "SLICE" "(" (height=NumericLengthLiteralWithUnit | heightParameter=Parameter) ("," options+=ShapeOption)* ")"
;

ProjectionShape:
	{ProjectionShape} "PROJECTION" "(" (options+=ShapeOption ("," options+=ShapeOption)*)? ")"
;

// FROM: what heights are measured from. TOLERANCE (slice): products ending this close to the plane
// are cut just inside. FILL_HOLES: outer rings only, or only holes smaller than an area.
// DIRECTION (projection): the plane's normal, world unless "local" (the scope object's frame) - a
// flag of its own rather than the clearance rule's DirectionSpace, whose default literal is LOCAL,
// so an unset space could not be told from a written "local".
// ABOVE / BELOW / BETWEEN (projection): clip to a height band before projecting.
// MINIMUM_RECTANGLE: the smallest rectangle around the shape instead of the shape (the one .length and
// .width measure), so every member applies to it: PROJECTION(MINIMUM_RECTANGLE).geojson("EPSG:4326").
ShapeOption:
	{ShapeReference} "FROM" reference=HeightReference |
	{ShapeTolerance} "TOLERANCE" tolerance=NumericLengthLiteralWithUnit |
	{ShapeFillHoles} "FILL_HOLES" (smallerThan=NumericLiteralWithUnit)? |
	{ShapeDirection} "DIRECTION" "(" x=NumericLiteral "," y=NumericLiteral "," z=NumericLiteral ("," local?="local")? ")" |
	{ShapeAbove} "ABOVE" (height=NumericLengthLiteralWithUnit | heightParameter=Parameter) |
	{ShapeBelow} "BELOW" (height=NumericLengthLiteralWithUnit | heightParameter=Parameter) |
	{ShapeBetween} "BETWEEN" (from=NumericLengthLiteralWithUnit | fromParameter=Parameter) "AND" (to=NumericLengthLiteralWithUnit | toParameter=Parameter) |
	{ShapeMinimumRectangle} "MINIMUM_RECTANGLE"
;

// SITE: the IfcSite placement (as GetFootprint); ABSOLUTE: the model's z = 0; LOWEST: the lowest
// point of the selected objects; ELEVATION: the scope object's elevation (relation positions only).
enum HeightReference:
	SITE | ABSOLUTE | LOWEST | ELEVATION
;

// Head-restricted WHERE chain: no leading "(". TerminalExpression's left side must keep a
// paren-free FIRST set — a syntactic predicate on the TerminalExpression alternative of
// ComparisonExpression collapses that 24-way decision to one-token lookahead (ANTLR hoists
// the synpred and stops LL(*) analysis for the later alternatives: error(201), PART_OF(GRAPH/
// nav:route), geoReference WITHIN_COUNTRY, the geometry: predicates and sem:isBoundedBy all
// became unreachable). Parens remain legal anywhere after the first token; a paren-LED
// condition parses via ParenCondition below.
WhereNoParenHeadExpression returns Expression:
    WhereNoParenHeadMulDiv (=>({Addition.left=current} '+' | {Subtraction.left=current} '-') right=WhereMulDiv)*;

WhereNoParenHeadMulDiv returns Expression:
    WhereNoParenHeadPrimary (=>({Multiplication.left=current} '*' | {Division.left=current} '/') right=WherePrimary)*;

WhereNoParenHeadPrimary returns Expression:
  =>LongWithUnitLiteralTyped |
  DoubleWithUnitLiteralTyped |
  WhereAbsFunction |
  WhereValueFunction |
  WhereCaseExpression |
  RelationAggregate |
  ConditionFeature;

// Paren-led head for ParenCondition — the tail rules are the shared full ones, so the AST
// classes and associativity are identical to the unrestricted chain.
WhereParenHeadExpression returns Expression:
    WhereParenHeadMulDiv (=>({Addition.left=current} '+' | {Subtraction.left=current} '-') right=WhereMulDiv)*;

WhereParenHeadMulDiv returns Expression:
    WhereParenHeadPrimary (=>({Multiplication.left=current} '*' | {Division.left=current} '/') right=WherePrimary)*;

WhereParenHeadPrimary returns Expression:
  "(" WhereAddSub ")";

// One EClass, two thin rules — each chain recurses into its own operand vocabulary
AbsFunction returns AbsFunction:
	{AbsFunction} "ABS" "(" expression=GetAddSub ")"
;

WhereAbsFunction returns AbsFunction:
	{AbsFunction} "ABS" "(" expression=WhereAddSub ")"
;

// Value functions and CASE (docs/virtual-features-design.md §5.1) — typed expression operands:
// unlike the arithmetic operators they may yield text or booleans, and COALESCE/CASE/GREATEST/
// LEAST tolerate operands without a value. One EClass per construct, two thin rules each (the
// AbsFunction idiom): each chain recurses into its own operand vocabulary. A single generic
// call rule keeps the grammar small — arity and argument types are checked by BqlValidator
// (checkValueFunction) and again by CompiledExpression at compile time.
// All names are new reserved words; an identically spelled unquoted identifier needs quotes.
ValueFunction returns ValueFunction:
	{ValueFunction} name=ValueFunctionName "(" (arguments+=ValueArgument ("," arguments+=ValueArgument)*)? ")"
;

WhereValueFunction returns ValueFunction:
	{ValueFunction} name=ValueFunctionName "(" (arguments+=WhereValueArgument ("," arguments+=WhereValueArgument)*)? ")"
;

// FUNCTION_NONE is the unset sentinel (first literal = EMF default), rejected by the validator
// like the *_NONE unit sentinels.
enum ValueFunctionName:
	FUNCTION_NONE |
	COALESCE | GREATEST | LEAST |
	ROUND | FLOOR | CEIL | POWER | SQRT | MOD |
	CONCAT | UPPER | LOWER | TRIM | LEFT | RIGHT | SUBSTRING | SPLIT_PART | REPLACE | REGEX_EXTRACT | CHAR_LENGTH |
	TO_NUMBER | TO_STRING |
	// Virtual feature definitions only (docs/virtual-features-design.md §5.1):
	// LOOKUP("<data file>", key [, "<key column>"], "<value column>") reads a crosswalk table;
	// REFERENCE(identification [, name]) is the value of a virtual classification
	LOOKUP | REFERENCE
;

// A function argument / CASE result: text, boolean or a unit (TO_NUMBER, TO_STRING) next to
// the arithmetic chain. First tokens are disjoint (STRING, true/false, unit keywords vs.
// number/feature/function starts), so the decision is LL(1). Text and boolean literals are
// deliberately NOT primaries of the arithmetic chains themselves: `= "x"` must keep parsing
// as the string comparator, not as an expression right side.
ValueArgument returns Expression:
	TextOperand | BooleanOperand | UnitOperand | GetAddSub
;

WhereValueArgument returns Expression:
	TextOperand | BooleanOperand | UnitOperand | WhereAddSub
;

TextOperand returns Expression:
	{StringLiteral} value=STRING
;

BooleanOperand returns Expression:
	{BooleanLiteral} value=Boolean
;

UnitOperand returns Expression:
	{UnitOperand} unit=Unit
;

// CASE WHEN <condition> THEN <value> ... [ELSE <value>] END — first matching branch wins; the
// conditions are full boolean expressions (evaluated through the same plans as a WHERE, so a
// condition on a feature without a value is false). Without ELSE an object matching no branch
// has no value.
// CASE ALL (docs/virtual-features-design.md §5.1, U10): every branch whose condition holds
// supplies a value, in order — for the multi-valued kinds (a classification with a code per
// level). ELSE only when no branch held. In a scalar position it is its first value.
CaseExpression returns CaseExpression:
	{CaseExpression} "CASE" (all?="ALL")? (branches+=CaseBranch)+ ("ELSE" otherwise=ValueArgument)? "END"
;

CaseBranch returns CaseBranch:
	"WHEN" condition=BooleanExpression "THEN" value=ValueArgument
;

WhereCaseExpression returns CaseExpression:
	{CaseExpression} "CASE" (all?="ALL")? (branches+=WhereCaseBranch)+ ("ELSE" otherwise=WhereValueArgument)? "END"
;

WhereCaseBranch returns CaseBranch:
	"WHEN" condition=BooleanExpression "THEN" value=WhereValueArgument
;

// The WHERE-side operand vocabulary — exactly the TerminalExpression feature list, extracted
// into a named rule (a down-payment on P11 of docs/bql-language-analysis.md). Deliberately
// NOT the full FinalFeature list: `type`, `qid`, `oid` and the model conditions keep their
// dedicated condition rules and must not be stolen by expression operands.
ConditionFeature returns Feature:
	AttributeFeature | PropertyFeature | QuantityFeature | CalculatedFeature | LayerFeature | RepresentationFeature | ClassificationFeature | NiceTypeFeature | SuggestionFeature | MaterialExpression | MaximumInscribedCircleFeature | MaximumInscribedSquareFeature | MaximumInscribedCylinderFeature | AabbFeature | DirectConnectionsTo | ModelFeature | CountSubQuery | GeometryClearance | NavRouteLength | HeadroomFeature | LinkedDataFeature
;
  
Feature:
	QidFeature | AttributeFeature | PropertyFeature | QuantityFeature | CalculatedFeature | TypeFeature | NiceTypeFeature | SuggestedTypeFeature | SuggestionFeature | ClassificationFeature | MaximumInscribedCircleFeature | MaximumInscribedCylinderFeature | MaximumInscribedSquareFeature | DirectConnectionsTo | ModelFeature | CountChildren | AabbFeature | LayerFeature | RepresentationFeature | MaterialFeature | DecompositionFeature | BoxFeature | CylinderFeature | ConeFeature | SphereFeature | ClashesWith | ConvertGeoReference | BooleanExpressionFeature | UseableAreaFeature | UseableAreaFactorFeature | GeometryClearance | NavRouteLength | GeometryFeature | LinkedDataFeature
;

// Linked data on the object (docs/linked-data-design.md §11.1): the files, links, texts and identifiers the server
// links to it on the version, read-only. `linkedData` is the records; `.any` and `.count` the object's; `.kind`,
// `.family`, `.extension`, `.category`, `.title`, `.validUntil`, `.expiresInDays` and `.state` one value per item,
// and a comparison on them holds when one of the object's items satisfies it. The field is an ID (checked by the validator), so no
// word but `linkedData` is reserved; `count` and `any` are keywords already.
LinkedDataFeature returns Feature:
	{LinkedDataFeature} "linkedData" ("." field=LinkedDataField)?
;

LinkedDataField:
	ID | "count" | "any"
;

GeometryFeature returns Feature:
	{GeometryFeature}
	"geometry"
;

ViewpointFeature returns Feature:
	{ViewpointFeature}
	"viewPoint" ("(" lookat=BooleanExpression ")")?
;

ConvertGeoReference returns Feature:
	// Split tokens, not a glued "gis:convertGeoReference" keyword: all three namespaces
	// (geometry:, gis:, sem:) tokenize alike and tolerate whitespace around the colon.
	// Cost, accepted: "gis" and the function name are reserved words shadowing
	// identically-spelled unquoted identifiers (quoted forms remain available).
	{ConvertGeoReference} "gis" ":" "convertGeoReference" "(" epsgCode=(ID | STRING) ")"
;

BooleanExpressionFeature:
	"eval" "(" expression = BooleanExpression ")"
;

BoxFeature returns Feature:
	Box
;

CylinderFeature returns Feature:
	Cylinder
;

ConeFeature returns Feature:
	Cone
;

SphereFeature returns Feature:
	Sphere
;

DecompositionFeature returns Feature:
	{DecompositionFeature} "decomposition"
;

ModelFeature returns Feature:
	{ModelFeature} "model" ("." modelSubFeature = ModelSubFeature)?
;

ModelSubFeature:
	IfcVersionSubFeature | DisciplineSubFeature | ModelName | ModelVersionId | ModelFileSize | ModelHeader | AllModelSubFeature | VersionUuidSubFeature
		| ModelAggregateSubFeature | ModelFilename | ModelPath | ModelUploadedOn | ModelUploadedBy
;

// A model-level aggregate (model search, docs/model-search-design.md §5.3): the value of
// `GET SUM(value) WHERE where` on one model. The function names are the aggregate keywords BQL
// already has, so no new word is reserved. COUNT stays model.count(<condition>).
ModelAggregateSubFeature:
	{ModelAggregateSubFeature} function=ModelAggregateFunction "(" value=Expression ("WHERE" where=BooleanExpression)? ")"
;

enum ModelAggregateFunction:
	SUM="SUM" | MIN="MIN" | MAX="MAX" | AVG="AVG" | MEDIAN="MEDIAN" | MODE="MODE" | RANGE="RANGE" | STDDEV="STDDEV"
;

// The version's file name, the node's path, and when and by whom the version was uploaded
ModelFilename:
	{ModelFilename} "filename"
;

ModelPath:
	{ModelPath} "path"
;

ModelUploadedOn:
	{ModelUploadedOn} "uploadedOn"
;

ModelUploadedBy:
	{ModelUploadedBy} "uploadedBy"
;

AllModelSubFeature:
	{AllModelSubFeature} "*"
;

VersionUuidSubFeature:
	{VersionUuidSubFeature} "versionUuid"
;

ModelHeader returns ModelHeader:
	{ModelHeader} "header" "." field=ModelHeaderField
;

enum ModelHeaderField:
	DESCRIPTIONS = "descriptions" |
	IMPLEMENTATION_LEVEL = "implementationLevel" |
	FILENAME = "filename" |
	TIME_STAMP = "timeStamp" |
	AUTHORS = "authors" |
	ORGANIZATIONS = "organizations" |
	PREPROCESSOR_VERSION = "preProcessorVersion" |
	ORIGINATING_SYSTEM = "originatingSystem" |
	AUTHORIZATION = "authorization" |
	SCHEMA_IDENTIFIERS = "schemaIdentifiers" |
	IFC_SCHEMA_VERSION = "ifcSchemaVersion"
;

IfcVersionSubFeature:
	{IfcVersionSubFeature} "ifcVersion"
;

DisciplineSubFeature:
	{DisciplineSubFeature} "discipline"
;

ModelName:
	{ModelName} "name"
;

ModelVersionId:
	{ModelVersionId} "id"
;

ModelFileSize:
	{ModelFileSize} "filesize"
;

QidFeature returns Feature:
	{QidFeature} "qid"
;

// Deliberately GET-only (FinalFeature) and not filterable: oids are mostly internal,
// GET oid exists for debugging purposes.
OidFeature returns Feature:
	{OidFeature} "oid"
;

MaximumInscribedCircleFeature returns Feature:
	{MaximumInscribedCircleFeature}
	"MAXIMUM_INSCRIBED_CIRCLE" "(" "geometry2d" ("," subtract=BooleanExpression)? ")"
	("." subFeature=CircleSubFeature)?
;

MaximumInscribedCylinderFeature:
	{MaximumInscribedCylinderFeature}"MAXIMUM_INSCRIBED_CYLINDER" "(" "geometry3d" "," height=DoubleWithUnitLiteralTyped ("," subtract=BooleanExpression)? ")"
	("." subFeature=CylinderSubFeature)?
;

CylinderSubFeature returns CylinderSubFeature:
	{CylinderSubFeature} sub=("diameter" | "radius" | "x" | "y" | "z" | "height")
;

CircleSubFeature returns CircleSubFeature:
	{CircleSubFeature} sub=("diameter" | "radius" | "x" | "y")
;

MaximumInscribedSquareFeature:
	{MaximumInscribedSquareFeature} "MAXIMUM_INSCRIBED_SQUARE" "(" "geometry2d" ")"
;

AttributeFeature returns Feature:
	({AttributeFeature} ("attribute" "." name=Attribute (sub=AttributeSubFeature)?)) |
	({AttributeAnyFeature} ("attribute" "." "*" (sub=AttributeSubFeature)?)) |
	({AttributeMetaFeature} "attribute" "." "meta")
;

// An attribute always starts with an upper case, these are equivalent to the attributes that exist in the IFC standard.
// Deliberately ID-only (no STRING form, unlike property/quantity names): IFC attribute names never
// contain characters that are illegal in an identifier, so quoting is never needed.
Attribute returns ecore::EString:
	ID
;

AttributeSubFeature:
	{AttributeSubFeature} "." type=(AttributeSubFeatureType)
;

enum AttributeSubFeatureType:
	NAME="name" | TYPE="type" | VALUE="value" | ALL="*"
;

BooleanExpression:
    OrExpression
;

OrExpression returns BooleanExpression:
    AndExpression ({OrExpression.left=current} "OR" right=AndExpression)*
;   

AndExpression returns BooleanExpression:
    (NotExpression ({AndExpression.left=current} "AND" right=NotExpression)*)
;

NotExpression returns BooleanExpression:
	ComparisonExpression | {NotExpression} "NOT" inner=ComparisonExpression
;

// TerminalExpression stays predicate-free and paren-free at its head (see the
// WhereNoParenHeadExpression comment); "("-led input goes through ParenCondition at the end,
// whose two-alternative decision safely carries the syntactic predicate that separates a
// parenthesised arithmetic left side ("(a + b) > c") from a parenthesised boolean
// ("(a AND b)").
ComparisonExpression returns BooleanExpression:
	PathExpression | TerminalExpression | QidExpression | AllExpression | TypeCondition | SuggestedTypeCondition | ModelCondition | PartOfPath | PartOfGraph | NavRoute | NavReachable | NavHasFallHazard | NavGuardsFall | ClashesWith | GeoReferenceWithinEpsg | GeoReferenceWithinCountry | ProvidesBoundariesFor | GeometryContainsFully | GeometryContainsPartially | GeometryContainedIn | GeometryTouches | IsBoundedBy | UseableAreaFactor | TextSearch | Done | ParenCondition
;

// "(a + b) > c" (arithmetic paren head, commits via the predicate) vs "(a AND b)" (boolean
// paren — the predicate fails on AND/OR/comparators inside and falls through). A bare "(a)"
// parses via the first alternative as a parenthesised bare-feature condition — the same
// has-value semantics and AST it had as a boolean paren.
ParenCondition returns BooleanExpression:
	=>TerminalExpressionParenHead | ("(" BooleanExpression ")")
;

TerminalExpressionParenHead returns TerminalExpression:
	{TerminalExpression} feature=WhereParenHeadExpression (comparator=Comparator)?
;

// Broad (model-wide) free-text search over the Lucene text index, e.g. TEXT_MATCHES("brandwerend deur") or TEXT_MATCHES("brandwerend", FUZZY)
// Requires text indexing to be enabled (BimWorksConfiguration features.text_indexing)
TextSearch returns BooleanExpression:
	{TextSearch} "TEXT_MATCHES" "(" query=STRING ("," fuzzy?="FUZZY" (maxEdits=LONG)?)? ")"
;

Done:
	{Done} "DONE"
;

AllExpression:
	{AllExpression} "ALL"
;

PathExpression:
	SinglePathExpression | MultiPathExpression
;

MultiPathExpression:
	SystemPath | ChildrenPath | ZonePath | PortPath | SpaceBoundaryPath
;

SystemPath returns MultiPathExpression:
	{SystemPath} "system" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression | filter=AllAnyCount))?
;

SpaceBoundaryPath returns MultiPathExpression:
	{SpaceBoundaryPath} "spaceBoundary" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression | filter=AllAnyCount))?
;

ZonePath returns MultiPathExpression:
	{ZonePath} "zone" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression | filter=AllAnyCount))?
;

PortPath returns MultiPathExpression:
	{PortPath} "port" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression | filter=AllAnyCount))?
;

ChildrenPath returns MultiPathExpression:
	{ChildrenPath} "children" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression | filter=AllAnyCount))?
;

AllAnyCount:
	All | Any | Count
;

All:
	"all" "(" expression=BooleanExpression ")"
;

Any:
	"any" "(" expression=BooleanExpression ")"
;

Count:
	"count" "(" expression=BooleanExpression ")" (comparator=Comparator)?
;

SinglePathExpression:
	ProjectPath | BuildingPath | BuildingStoreyPath | SitePath | SpacePath | RelatedBuildingElementPath | TypeObjectPath | ParentPath | DecomposesPath | ContainedInPath | OwnPath
;

ProjectPath returns SinglePathExpression:
	{ProjectPath} "project" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression))?
;

TypeObjectPath returns SinglePathExpression:
	{TypeObjectPath} "typeObject" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression))?
;

OwnPath returns SinglePathExpression:
	{OwnPath} "own" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression))?
;

ParentPath returns SinglePathExpression:
	{ParentPath} "parent" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression))?
;

DecomposesPath returns SinglePathExpression:
	{DecomposesPath} "decomposes" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression))?
;

ContainedInPath returns SinglePathExpression:
	{ContainedInPath} "containedIn" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression))?
;

SpacePath returns SinglePathExpression:
	{SpacePath} "space" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression))?
;

SitePath returns SinglePathExpression:
	{SitePath} "site" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression))?
;

BuildingPath returns SinglePathExpression:
	{BuildingPath} "building" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression))?
;

// To access the buildingStorey of an object this can be traversed
BuildingStoreyPath returns SinglePathExpression:
	{BuildingStoreyPath} "buildingStorey" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression))?
;

RelatedBuildingElementPath returns SinglePathExpression:
	{RelatedBuildingElementPath} "relatedBuildingElement" ("." (terminalExpression=NewTerminalExpression | subPath=PathExpression))?
;

NewTerminalExpression:
	TerminalExpression | TypeCondition | SuggestedTypeCondition | ModelCondition | PartOfPath | PartOfGraph | NavRoute | NavReachable | NavHasFallHazard | NavGuardsFall | ClashesWith | GeoReferenceWithinEpsg | GeoReferenceWithinCountry | ProvidesBoundariesFor | IsBoundedBy | QidExpression
;

ProvidesBoundariesFor returns BooleanExpression:
	// Split tokens, not glued — see ConvertGeoReference.
	{ProvidesBoundariesFor} "sem" ":" "providesBoundariesFor" "(" subExpression=BooleanExpressionOrQids ")"
;

BooleanExpressionOrQids:
	expression=BooleanExpression | qids=Qids | parameter=Parameter
;

// Reuses QidOrOids so real qids (QID_STRING/STRING/UUID[oids]) actually match; the old
// qids+=ID form could never lex a dashed qid and was dead in practice (see
// docs/bql-language-analysis.md 2.4). Type change: Qids.qids is now EList<QidOrOids>.
Qids:
	qids+=QidOrOids ("," qids+=QidOrOids)*
;

IsBoundedBy returns BooleanExpression:
	// Split tokens, not glued — see ConvertGeoReference.
	{IsBoundedBy} "sem" ":" "isBoundedBy" "(" subExpression=BooleanExpression ")"
;

GeoReferenceWithinCountry returns BooleanExpression:
	{GeoReferenceWithinCountry} "geoReference" "WITHIN_COUNTRY" "(" countryCode=CountryCode ")"
;

enum CountryCode:
	NL
;

GeoReferenceWithinEpsg returns BooleanExpression:
	{GeoReferenceWithinEpsg} "geoReference" "WITHIN_EPSG" "(" epsgCode=(ID | STRING) ")"
;

PartOfPath returns BooleanExpression:
	{PartOfPath} "PART_OF" "(" "SHORTEST_PATH" "(" from=BooleanExpression "," to=BooleanExpression ("," through=BooleanExpression)? ")" ")"
;

PartOfGraph returns BooleanExpression:
	{PartOfGraph} "PART_OF" "(" "GRAPH" "(" from=BooleanExpression "," maxSpan=LONG ")" ")"
;

// Metric routing over the walkable-surfaces span heightfield (docs/walkable-surfaces-design.md §6).
// SHORTEST_PATH above stays topological adjacency over spaces/doors; nav:route is measured in
// metres over the floors a person can actually walk. Selects the objects the cheapest route
// traverses (support products, doors, spaces along the corridor); per source, the route goes to
// the nearest reachable target. THROUGH restricts intermediate cells to the given spaces (door
// portals and stair cells between allowed spaces stay allowed, §6.3).
NavRoute returns BooleanExpression:
	{NavRoute} "PART_OF" "(" "nav:route" "(" from=NavRouteFrom "," to=BooleanExpressionOrQids
		("," "THROUGH" "(" through=BooleanExpression ")")?
		("," agent=AgentSpec)? ")" ")"
;

// nav:route's from-argument: BooleanExpressionOrQids, except a bare qid list is limited to a
// single QidOrOids. A multi-qid from was ambiguous with the "," separating from and to (ANTLR
// warning(200) on the Qids loop, docs/XTEXT-REGENERATION-ISSUES.md 3g): the greedy resolution
// made the from list swallow a bare-qid to, so nav:route("a", "b") could never parse. Only the
// from position conflicts — to is followed by keywords ("THROUGH"/"AGENT") or ")", so it keeps
// the full list form. A multi-source from stays expressible as an expression: qid IN ("a", "b").
NavRouteFrom returns BooleanExpressionOrQids:
	expression=BooleanExpression | qids=SingleQids | parameter=Parameter
;

SingleQids returns Qids:
	qids+=QidOrOids
;

// True for objects from which any target is reachable under the agent/THROUGH constraints.
NavReachable returns BooleanExpression:
	{NavReachable} "nav:reachable" "(" to=BooleanExpressionOrQids
		("," "THROUGH" "(" through=BooleanExpression ")")?
		("," agent=AgentSpec)? ")"
;

// Fall-hazard test (design §10): the object supports a walking surface with a drop edge higher
// than the given drop and a guard lower than the given guard (default 1 m).
NavHasFallHazard returns BooleanExpression:
	{NavHasFallHazard} "nav:hasFallHazard" "(" drop=NumericLengthLiteralWithUnit
		("," guard=NumericLengthLiteralWithUnit)? ")"
;

// The counterpart of nav:hasFallHazard: the objects guarding a fall from the walking surfaces
// supported by <surfaces> - standing in the guard zone (150 mm above the floor up to <guard>,
// default 1 m) of a drop edge deeper than <drop> whose guard is at least <guard> high. These are
// what make nav:hasFallHazard pass with the same thresholds (design §10, MKM check 66).
NavGuardsFall returns BooleanExpression:
	{NavGuardsFall} "nav:guardsFall" "(" surfaces=BooleanExpression "," drop=NumericLengthLiteralWithUnit
		("," guard=NumericLengthLiteralWithUnit)? ")"
;

// Runtime-configurable character: AGENT(height: 1.85 m, radius: 250mm, climb: 250mm) - entries
// in any order, defaults documented in BqlKeywordDocumentation (1800/250/250 mm).
AgentSpec:
	{AgentSpec} "AGENT" "(" (entries+=AgentEntry ("," entries+=AgentEntry)*)? ")"
;

AgentEntry:
	key=AgentKey ":" value=NumericLengthLiteralWithUnit
;

enum AgentKey:
	HEIGHT="height" |
	RADIUS="radius" |
	CLIMB="climb"
;

ModelCondition returns ModelCondition:
	"model" "." modelSubCondition=ModelSubCondition
;

ModelSubCondition:
	ModelIfcVersionCondition | ModelDisciplineCondition | ModelCountSubCondition
;

// NOT IN mirrors TypeCondition (P6 leftovers, docs/bql-language-analysis.md 3.5):
// complement semantics — every model has a version/discipline, so the has-value vs
// complement distinction vanishes here, exactly as it does for type.
ModelIfcVersionCondition returns ModelCondition:
	"ifcVersion"
	({ModelIfcVersionCondition} ("!=" notEquals=IfcSchema) |
	{ModelIfcVersionCondition} ("=" equals=IfcSchema) |
	{ModelIfcVersionCondition} ((not?="NOT")? "IN" "(" schemas+=IfcSchema ("," schemas+=IfcSchema)* ")"))
;

ModelDisciplineCondition returns ModelCondition:
	"discipline"
	({ModelDisciplineCondition} ("!=" notEquals=Discipline) |
	{ModelDisciplineCondition} ("=" equals=Discipline) |
	{ModelDisciplineCondition} ((not?="NOT")? "IN" "(" disciplines+=Discipline ("," disciplines+=Discipline)* ")"))
;

ModelCountSubCondition:
	{ModelCountSubCondition}
	"count" "(" expression=BooleanExpression ")" (comparator=Comparator)?
;

enum Discipline:
	UNKNOWN |
	ARCHITECTURAL |
	AIR_CONDITIONING |
	BUILDING_SERVICES |
	ELECTRICAL |
	HEATING |
	STRUCTURAL |
	VENTILATION |
	PLUMBING |
	SPRINKLER |
	INVENTORY |
	FACILITY_MANAGEMENT |
	LANDSCAPE |
	PREFAB_CONCRETE |
	STEEL_STRUCTURE |
	SITE_OPERATIONS |
	COOLING |
	SPECIAL_PIPING |
	PROCESS |
	HVAC |
	SPATIAL |
	GEOTECHNICAL |
	BRIDGE |
	ROAD |
	RAILWAY |
	PORTS_AND_WATERWAYS |
	TIMBER_STRUCTURE |
	VERTICAL_TRANSPORT |
	TUNNEL |
	SURVEY
;

enum IfcSchema:
	NONE |
	IFC2X3 |
	IFC4 |
	IFC4X3
;

// The former *FeatureComparator alternatives are absorbed by the expression right sides of
// the remaining comparators (docs/bql-expressions-design.md §3.3)
Comparator:
	SmallerThanComparator | SmallerThanOrEqualsComparator |
	LargerThanComparator | LargerThanOrEqualsComparator |
	EqualsComparator | NotEqualsComparator |
	// => tries the all-long list first and falls through to InDouble for mixed lists like
	// IN (1, 2.5) — possible since InDoubleComparator accepts dot-less values via DoubleOrLong
	=>InLongComparator | InDoubleComparator | InBooleanComparator | InParameter |
	BetweenNumericComparator | StringComparator
;

Parameter returns Parameter:
	{Parameter} "$" name=ID
;

// The IN comparators support NOT IN, mirroring TypeCondition. On the bitmap path this is
// complement semantics (masterBitSet andNot IN-set, like type NOT IN and !=); the per-object
// evaluation path returns false for objects without a value (same divergence as = / !=).
InParameter returns Comparator:
	{InParameter} (not?="NOT")? "IN" parameter=Parameter
;

StringComparator returns Comparator:
	InStringComparator |
	MatchesRegexComparator |
	StartsWithComparator |
	EndsWithComparator |
	ContainsComparator |
	MatchesComparator |
	StringLengthComparator |
	StringCaseSensitiveEqualsComparator |
	StringCaseSensitiveNotEqualsComparator
;

// Analyzed (tokenized, case-insensitive) text match against the Lucene text index, scoped to the feature it is applied to.
// Example: property.Pset_WallCommon.FireRating MATCHES "brandwerend" FUZZY 1
// Requires text indexing to be enabled (BimWorksConfiguration features.text_indexing)
MatchesComparator returns StringComparator:
	{MatchesComparator} "MATCHES" (literal=STRING | parameter=Parameter) (fuzzy?="FUZZY" (maxEdits=LONG)?)?
;

// No CS prefix: case sensitivity cannot affect a string's length (P9, removed 2026-07-23)
StringLengthComparator returns StringComparator:
	{StringLengthComparator} "LENGTH" operator=StringLengthOperator (value=LONG | parameter=Parameter)
;

enum StringLengthOperator:
	EQUAL_TO = "=" |
	NOT_EQUAL = "!=" |
	LARGER_THAN = ">" |
	LARGER_THAN_OR_EQUAL = ">=" |
	SMALLER_THAN = "<" |
	SMALLER_THAN_OR_EQUAL = "<="
;

StringCaseSensitiveEqualsComparator returns StringComparator:
	{StringCaseSensitiveEqualsComparator} caseSensitive?="CS" "=" (literal=STRING | parameter=Parameter)
;

StringCaseSensitiveNotEqualsComparator returns StringComparator:
	{StringCaseSensitiveNotEqualsComparator} caseSensitive?="CS" "!=" (literal=STRING | parameter=Parameter)
;

// BETWEEN is inclusive on both ends ([from, to]), matching SQL. Two equivalent spellings:
//   f BETWEEN 1 m AND 2 m   (SQL form)
//   f BETWEEN (1 m, 2 m)    (legacy call form)
// See docs/bql-language-analysis.md 6.4; interval-bracket forms for explicit inclusivity
// control can only be added once the legacy call form is dropped, because "(a, b)" would
// change meaning.
// Parameter support (docs/bql-parameter-binding-plan.md Phase 2): bounds may be parameters
// ($lo / $hi) in both spellings, and the whole pair may be one parameter (BETWEEN $range,
// bound from a 2-element numeric array). Both-bounds-parameterized and BETWEEN $range are
// treated as one logical range pair by the binder and the dual-handle slider UI. The =>
// predicate commits the AND spelling only when "AND" actually follows, so BETWEEN $range
// (no AND) falls through to the bare-parameter alternative (same idiom as Label, see
// XTEXT-REGENERATION-ISSUES.md 3d).
BetweenNumericComparator returns Comparator:
	{BetweenNumericComparator} "BETWEEN" (
		("(" (from=NumericLiteralWithUnit | fromParameter=Parameter) "," (to=NumericLiteralWithUnit | toParameter=Parameter) ")") |
		(=>((from=NumericLiteralWithUnit | fromParameter=Parameter) "AND") (to=NumericLiteralWithUnit | toParameter=Parameter)) |
		parameter=Parameter
	)
;

NumericLiteralWithUnit returns Literal:
	{NumericLiteralWithUnit} (literal=NumericLiteral (unit=Unit)?)
;

NumericLengthLiteralWithUnit returns NumericLengthLiteralWithUnit:
	{NumericLengthLiteralWithUnit} (literal=NumericLiteral (unit=LengthUnit)?)
;

// A double-typed value that also accepts dot-less input: LONG is lexed before DOUBLE, so "500"
// is always a LONG token and a plain value=DOUBLE assignment can never match it. Use this rule
// wherever a floating point value is expected, so integers work too ("BIN(x, 500 mm)" as well as
// "BIN(x, 500.0 mm)"). Converted via the EDouble datatype fallback — no custom value converter.
// See docs/bql-language-analysis.md 3.8/P8.
DoubleOrLong returns ecore::EDouble:
	DOUBLE | LONG
;

NumericLiteral:
	// => commits integers to LongLiteral (DoubleLiteral also accepts LONG via DoubleOrLong;
	// the greedy first choice is the intended one and this silences the ANTLR ambiguity)
	=>LongLiteral | DoubleLiteral
;

LongLiteral returns NumericLiteral:
	{LongLiteral} longValue=LONG
;

DoubleLiteral returns NumericLiteral:
	{DoubleLiteral} doubleValue=DoubleOrLong
;

InLongComparator returns Comparator:
	{InLongComparator} (not?="NOT")? "IN" "(" values+=LongWithUnitLiteralTyped ("," values+=LongWithUnitLiteralTyped)* ")"
;

InBooleanComparator returns Comparator:
	{InBooleanComparator} (not?="NOT")? "IN" "(" booleanValues+=BooleanLiteralTyped ("," booleanValues+=BooleanLiteralTyped)* ")"
;

InDoubleComparator returns Comparator:
	{InDoubleComparator} (not?="NOT")? "IN" "(" values+=DoubleWithUnitLiteralTyped ("," values+=DoubleWithUnitLiteralTyped)* ")"
;

InStringComparator returns StringComparator:
	{InStringComparator} (caseSensitive?="CS")? (not?="NOT")? "IN" "(" values+=STRING ("," values+=STRING)* ")"
;

StartsWithComparator returns StringComparator:
	{StartsWithComparator} (caseSensitive?="CS")? "STARTS_WITH" (literal=STRING | parameter=Parameter)
;

EndsWithComparator returns StringComparator:
	{EndsWithComparator} (caseSensitive?="CS")? "ENDS_WITH" (literal=STRING | parameter=Parameter)
;

MatchesRegexComparator returns StringComparator:
	{MatchesRegexComparator} (caseSensitive?="CS")? "MATCHES_REGEX" (literal=STRING | parameter=Parameter)
;

ContainsComparator returns StringComparator:
	{ContainsComparator} (caseSensitive?="CS")? "CONTAINS" (literal=STRING | parameter=Parameter)
;

// Relational comparators (docs/bql-expressions-design.md §3.3): the right side is a full
// WHERE-side arithmetic expression. The `literal` assignment kept its name and, for a plain
// numeric literal, its exact AST node — the type merely widened from Literal to Expression —
// so `< 5 m` parses byte-identically to before, and `< 2 * b` lands in the same assignment.
// The former *FeatureComparator twins are absorbed (they never worked: =/!= threw
// NOT_IMPLEMENTED and </> compared in the wrong direction without units).
SmallerThanComparator returns Comparator:
	{SmallerThanComparator} "<" (literal=WhereExpression | parameter=Parameter)
;

SmallerThanOrEqualsComparator returns Comparator:
	{SmallerThanOrEqualsComparator} "<=" (literal=WhereExpression | parameter=Parameter)
;

// Equality keeps its non-numeric literals under `literal` (their first tokens — true/false/
// null/STRING — are disjoint from expression starts, so the decision is LL(1)); all numerics
// go through `expression`. WITHIN attaches tolerance to the numeric and parameter forms only:
//   a = b WITHIN 5 %     — relative, |a-b| <= 0.05*|b| (reference = right-hand side)
//   a = b WITHIN 5 mm    — absolute, dimension must match the operands
//   a != b WITHIN 5 %    — deviates by more than the tolerance
// The => predicate follows the AS/UNIT phantom-ambiguity idiom (XRI 3a/3b) — WITHIN occurs
// nowhere else in the language.
EqualsComparator returns Comparator:
	{EqualsComparator} "=" ((literal=(BooleanLiteral | NullLiteral | StringLiteral)) | ((expression=WhereExpression | parameter=Parameter) (=>"WITHIN" tolerance=Tolerance)?))
;

NotEqualsComparator returns Comparator:
	{NotEqualsComparator} "!=" ((literal=(BooleanLiteral | NullLiteral | StringLiteral)) | ((expression=WhereExpression | parameter=Parameter) (=>"WITHIN" tolerance=Tolerance)?))
;

// A bare number is an absolute tolerance in the operands' own dimension (only meaningful
// when that is unitless — the validator warns otherwise); `%` is relative; a unit makes it
// absolute in that unit.
Tolerance:
	{Tolerance} value=DoubleOrLong (percent?="%" | unit=Unit)?
;

LargerThanComparator returns Comparator:
	{LargerThanComparator} ">" (literal=WhereExpression | parameter=Parameter)
;

LargerThanOrEqualsComparator returns Comparator:
	{LargerThanOrEqualsComparator} ">=" (literal=WhereExpression | parameter=Parameter)
;

QidExpression returns QidExpression:
	{QidExpression}
	"qid" comparator=QidComparator
;

QidComparator:
	QidEqualsComparator | QidInComparator | QidInParameterComparator 
;

QidEqualsComparator returns QidComparator:
	{QidEqualsComparator} "=" value=QidOrOids
;

// NOT IN completes the P6 sweep (docs/bql-language-analysis.md 3.5): complement
// semantics, like type NOT IN — every object has a qid.
QidInComparator returns QidComparator:
	{QidInComparator} (not?="NOT")? "IN" "(" values+=QidOrOids ("," values+=QidOrOids)* ")"
;

// P7 (docs/bql-language-analysis.md 3.5): reuses the Parameter rule instead of re-inlining
// "$" name=ID — one encoding of parameters everywhere. Model change: name:EString became
// parameter:Parameter (BqlParameterBinder and QueryHelper.mapParameters read parameter.name).
QidInParameterComparator returns QidComparator:
	{QidInParameterComparator} (not?="NOT")? "IN" parameter=Parameter
;

QidOrOids:
	Qid | QidString | VersionAndOids
;

VersionAndOids:
	{VersionAndOids}
	vid = UUID "[" oids += LONG ("," oids += LONG)* "]"
;

Qid:
	{Qid}
	qid = QID_STRING
;

QidString:
	qid = STRING
;

terminal fragment HEX:
    'a'..'f'|'A'..'F'|'0'..'9'
;   

terminal UUID returns ecore::EString:
    HEX HEX HEX HEX HEX HEX HEX HEX '-'
    HEX HEX HEX HEX '-'
    HEX HEX HEX HEX '-'
    HEX HEX HEX HEX '-'
    HEX HEX HEX HEX HEX HEX HEX HEX HEX HEX HEX HEX
;

terminal QID_STRING returns ecore::EString:
    HEX HEX HEX HEX HEX HEX HEX HEX '-'
    HEX HEX HEX HEX '-'
    HEX HEX HEX HEX '-'
    HEX HEX HEX HEX '-'
    HEX HEX HEX HEX HEX HEX HEX HEX HEX HEX HEX HEX '-'
    LONG
;

// When no comparator is defined, it is interpreted as "has a value for the given feature".
// The left side is a WHERE-side arithmetic expression (docs/bql-expressions-design.md §3.2)
// whose operand vocabulary is the extracted ConditionFeature rule — a bare feature parses to
// the identical AST as before (the chain rules only create operator nodes when an operator
// is present); only the static type of `feature` widened from Feature to Expression. The
// head may not be a "(" (see WhereNoParenHeadExpression); paren-led conditions parse via
// ParenCondition into the same TerminalExpression class.
TerminalExpression returns TerminalExpression:
    feature=WhereNoParenHeadExpression
	(comparator=Comparator)?
;

// Widened 2026-07-23 (docs/bql-parameter-binding-plan.md Phase 2 item 7): the argument is a
// BooleanExpressionOrQids so CLASHES_WITH($selected) and CLASHES_WITH(qid, qid, ...) work like
// the geometry: functions. Model change: expression is now BooleanExpressionOrQids — consumers
// route through QueryContext.expressionToBitSet(BooleanExpressionOrQids).
ClashesWith returns Feature:
	{ClashesWith} "CLASHES_WITH" "(" (virtualGeometry=VirtualGeometry ",")? expression=BooleanExpressionOrQids ")"
;

VirtualGeometry:
	Box | Cylinder | Cone
;

enum VirtualGeometrySource:
	THIS="this" |
	PARENT="parent"
;

Cylinder:
	{Cylinder} "CYLINDER" "(" source=VirtualGeometrySource "," offsetX=Expression "," offsetY=Expression "," offsetZ=Expression "," radius=Expression "," height=Expression ")"
;

Cone:
	{Cone} "CONE" "(" source=VirtualGeometrySource "," offsetX=Expression "," offsetY=Expression "," offsetZ=Expression "," radius=Expression "," height=Expression ")"
;

Sphere:
	{Sphere} "SPHERE" "(" source=VirtualGeometrySource "," offsetX=Expression "," offsetY=Expression "," offsetZ=Expression "," radius=Expression ")"
;

Box:
	{Box} "BOX" "(" source=VirtualGeometrySource "," offsetX=Expression "," offsetY=Expression "," offsetZ=Expression "," sizeX=Expression "," sizeY=Expression "," sizeZ=Expression ")"
;

GeometryContainsFully returns Feature:
	{GeometryContainsFully} "geometry" ":" "contains_fully" "(" expression=BooleanExpressionOrQids ")"
;

GeometryContainsPartially returns Feature:
	{GeometryContainsPartially} "geometry" ":" "contains_partially" "(" expression=BooleanExpressionOrQids ")"
;

GeometryContainedIn returns Feature:
	{GeometryContainedIn} "geometry" ":" "contained_in" "(" expression=BooleanExpressionOrQids ("," type=GeometricContainmentType)? ")"
;

GeometryTouches returns Feature:
	{GeometryTouches} "geometry" ":" "touches" "(" expression=BooleanExpressionOrQids ")"
;

// Minimum surface-to-surface distance (mm internally) from an object to the nearest object of the
// target sub-query; 0 when touching/penetrating, no value when the target set is empty.
// Used with the standard comparators: geometry:clearance(type = IFCBEAM) < 50mm
GeometryClearance returns Feature:
	{GeometryClearance} "geometry" ":" "clearance" "(" expression=BooleanExpressionOrQids ("," direction=ClearanceDirection)? ")"
;

// Walkable route length in mm to the nearest reachable target (walkable-surfaces design §6.2):
// GET nav:routeLength(...) or with comparators - nav:routeLength(...) < 30 m. No value when
// unreachable under the agent/THROUGH constraints.
NavRouteLength returns Feature:
	{NavRouteLength} "nav:routeLength" "(" to=BooleanExpressionOrQids
		("," "THROUGH" "(" through=BooleanExpression ")")?
		("," agent=AgentSpec)?
		("," "FROM" start=NavStart)? ")"
;

// Where a route starts in an object (docs/check-result-interaction-design.md §6.4): NEAREST (the
// default), its walkable span nearest to a target; CENTROID, the centre of its walkable floor,
// always inside the object
enum NavStart:
	NEAREST | CENTROID
;

// Direction vector for directional clearance; "local" (default) is transformed by the linear part
// of the object's product matrix, "world" is used as-is. Reserved for extension with symbolic
// directions (e.g. opening side) later.
ClearanceDirection:
	{ClearanceDirection} "DIRECTION" "(" x=NumericLiteral "," y=NumericLiteral "," z=NumericLiteral ("," space=DirectionSpace)? ")"
;

enum DirectionSpace:
	LOCAL="local" |
	WORLD="world"
;

enum GeometricContainmentType:
	FULLY_OR_PARTIALLY="fully_or_partially" |
	FULLY="fully" |
	PARTIALLY="partially"
;

CountChildren returns Feature:
	{CountChildren} "COUNT" "(" "children" ")"
;

CountSubQuery returns Feature:
	{CountSubQuery} "COUNT" "(" expression=BooleanExpression ")"
;

DirectConnectionsTo returns Feature:
	{DirectConnectionsTo} "DIRECT_CONNECTIONS_TO" "(" subQuery=BooleanExpression ("," viaQuery=BooleanExpression)? ")"
;

AabbFeature returns Feature:
	{AabbFeature} "aabb" ("." aabbSubFeature=AabbSubFeature)?
;

// P16 / design 6.2a (docs/bql-language-analysis.md): these are domain analysis functions and
// belong in the geometry: namespace. Dual-accept during the deprecation window: the old
// PascalCase spellings still parse (BqlValidator warns) and will be dropped in a later release.
// Note geometry:usableAreaFactor is ONE surface keyword serving both the WHERE form
// (UseableAreaFactor) and the GET form (UseableAreaFactorFeature) — context selects the class.

// TODO now it's a BooleanExpression, but it should become a value that can be compared with other values
UseableAreaFactor returns Feature:
	{UseableAreaFactor} (
	("geometry" ":" "usableAreaFactor" | "UseableAreaFactor") "(" requiredHeight=NumericLiteralWithUnit "," factor=DoubleLiteral ")"
	)
;

UseableAreaFeature returns Feature:
	{UseableAreaFeature}
	("geometry" ":" "usableArea" | "UseableAreaFeature") "(" height=NumericLiteralWithUnit ")"
;

UseableAreaFactorFeature returns Feature:
	{UseableAreaFactorFeature}
	("geometry" ":" "usableAreaFactor" | "UseableAreaFactorFeature") "(" requiredHeight=NumericLiteralWithUnit "," factor=DoubleLiteral ")"
;

enum AabbSubFeature:
	HEIGHT="height" |
	WIDTH="width" |
	DEPTH="depth" |
	MINX="minx" |
	MINY="miny" |
	MINZ="minz" |
	MAXX="maxx" |
	MAXY="maxy" |
	MAXZ="maxz" |
	X="x" |
	Y="y" |
	Z="z"
;

GetFeature returns Feature:
	MultiSubFeature | SubFeature | FinalFeature | BinFunction
;

MultiSubFeature returns Feature:
	ComplexMultiSubFeature | SimpleMultiSubFeature 
;

SimpleMultiSubFeature returns Feature:
	{MultiSubFeature}
	multiType=MultiSubFeatureType
	("." subFeatures += SingleFeature)?
;

ComplexMultiSubFeature returns Feature:
	{MultiSubFeature}
	multiType=MultiSubFeatureType
	"("
		subFeatures += SingleFeature ("," subFeatures += SingleFeature)*
		("WHERE" where=BooleanExpression)?
		(groupBy=GroupBy)?
		(orderBy=OrderBy)?
		("LIMIT" limit=LONG)?
	")"
;

SubFeature returns Feature:
	SimpleSubFeature | ComplexSubFeature
;

SimpleSubFeature returns Feature:
	{SubFeature}
	type=SubFeatureType
	("." subFeatures += GetFeature)?
;

ComplexSubFeature returns Feature:
	{SubFeature}
	type=SubFeatureType
	"("
		subFeatures += GetFeature ("," subFeatures += GetFeature)*
	")"	
;

FinalFeature returns Feature:
	OidFeature | QidFeature | AttributeFeature | PropertyFeature | QuantityFeature | CalculatedFeature | TypeFeature | NiceTypeFeature | SuggestedTypeFeature | SuggestionFeature | ClassificationFeature | MaximumInscribedCircleFeature | MaximumInscribedCylinderFeature | MaximumInscribedSquareFeature | DirectConnectionsTo | ModelFeature | CountChildren | AabbFeature | LayerFeature | RepresentationFeature | MaterialFeature | DecompositionFeature | BoxFeature | CylinderFeature | ConeFeature | SphereFeature | ClashesWith | UseableAreaFeature | UseableAreaFactorFeature | ConvertGeoReference | HeadroomFeature | BooleanExpressionFeature | GeometryClearance | NavRouteLength | ViewpointFeature | LinkedDataFeature
;

// P16 / design 6.2a: geometry:headroom; the PascalCase spelling is deprecated (dual-accept)
// Also a WHERE operand since 2026-10-05 (ConditionFeature, HeadroomExecutionPlan): compared in mm,
// e.g. geometry:headroom(type IN (IFCSLAB, IFCBEAM), 2300 mm) < 2300 mm (MKM checks 21/26 in BCL)
HeadroomFeature:
	{HeadroomFeature}
	("geometry" ":" "headroom" | "Headroom") "("
	expression=BooleanExpression "," requiredHeight=NumericLiteralWithUnit
	")"
;

enum MultiSubFeatureType:
	CHILDREN="children" |
	CONTAINMAINT_CHILDREN="containmentChildren" |
	DECOMPOSITION_CHILDREN="decompositionChildren" |
	ALL_CHILDREN="allChildren" |
	HAS_FILLINGS="hasFillings" |
	HAS_OPENINGS="hasOpenings" |
	FILLS="fills" |
	FILLINGS="fillings" |
	ZONE="zone"|
	PORT="port"|
	SYSTEM="system" |
	SPACE_BOUNDARY="spaceBoundary" |
	// The objects an IfcZone, IfcSystem or IfcGroup groups — the inverse of zone / system
	// (docs/virtual-features-design.md §5.1): members(COUNT(qid) WHERE type = IFCSPACE)
	MEMBERS="members"
;

enum SubFeatureType:
	BUILDING="building" |
	SITE="site"|
	PROJECT="project"|
	RELATED_BUILDING_ELEMENT="relatedBuildingElement"|
	BUILDING_STOREY="buildingStorey"|
	SPACE="space"|
	PORT_CONNECTED_TO="portConnectedTo" | 
	PORT_CONTAINED_IN="portContainedIn" | 
	PARENT="parent" | 
	TYPE_OBJECT="typeObject" | 
	DECOMPOSES="decomposes" | 
	CONTAINED_IN="containedIn" | 
	FILLS_VOID="fillsVoid" | 
	VOIDS_ELEMENT="voidsElement" |
	OWN="own"
;

NullLiteral returns Literal:
	{NullLiteral} "null"
;

StringLiteral returns Literal:
	{StringLiteral} value=STRING
;

enum Boolean:
	FALSE="false" | TRUE="true"
; 

BooleanLiteral returns Literal:
	{BooleanLiteral} value=Boolean
;

BooleanLiteralTyped returns BooleanLiteral:
	{BooleanLiteral} value=Boolean
;

LongWithUnitLiteral returns Literal:
	{LongWithUnitLiteral} value=LONG unit=(Unit)?
;

LongWithUnitLiteralTyped returns LongWithUnitLiteral:
	{LongWithUnitLiteral} value=LONG unit=(Unit)?
;

DoubleWithUnitLiteral returns Literal:
	{DoubleWithUnitLiteral} value=DOUBLE unit=(Unit)?
;

DoubleWithUnitLiteralTyped returns DoubleWithUnitLiteral:
	{DoubleWithUnitLiteral} value=DoubleOrLong unit=(Unit)?
;

DoubleWithLengthUnitLiteralTyped returns DoubleWithLengthUnitLiteralTyped:
	{DoubleWithLengthUnitLiteralTyped} value=DoubleOrLong unit=(LengthUnit)?
;

SignedDoubleWithUnitLiteralTyped returns SignedDoubleWithUnitLiteralTyped:
	{SignedDoubleWithUnitLiteralTyped} value=DoubleOrLong unit=(Unit)?
;

// Class names are plain IDs since 2026-07-23: the former IFCCLASS terminal ('IFC' ('A'..'Z')+)
// was lexed before ID and therefore shadowed every all-caps IFC-prefixed identifier in the whole
// language (e.g. a property set named IFCX was unaddressable as property.IFCX). Class-name
// validity is now checked by BqlValidator (with a did-you-mean for case mismatches) and enforced
// at runtime by TypeExecutionPlan (UNKNOWN_TYPE) — names remain strictly uppercase.
TypeCondition returns TypeCondition:
	"type"
	(noInheritance?="NI")?
	(
		("!=" notEqualsType=ID) |
	 	("=" equalsType=ID) |
	 	((not ?= "NOT")? "IN" "(" types+=ID ("," types+=ID)* ")") |
	 	// type IN $types — bound server-side from an array of class-name strings
	 	// (docs/bql-parameter-binding-plan.md Phase 2)
	 	((not ?= "NOT")? "IN" parameter=Parameter)
	)
;

TypeFeature returns Feature:
	{TypeFeature}"type"
;

NiceTypeFeature returns Feature:
	{NiceTypeFeature}"niceType"
;

// Per-object type suggestion, corrected view (docs/ifc-type-suggestion-design.md §11): a
// structural twin of TypeCondition over the TYPE_SUGGESTIONS_1 artifact. Subtype-inclusive
// like type (NI disables inheritance); class-name validity checked by BqlValidator and at
// runtime by the execution plan. Versions without suggestions match nothing.
SuggestedTypeCondition returns SuggestedTypeCondition:
	"suggestedType"
	(noInheritance?="NI")?
	(
		("!=" notEqualsType=ID) |
	 	("=" equalsType=ID) |
	 	((not ?= "NOT")? "IN" "(" types+=ID ("," types+=ID)* ")") |
	 	((not ?= "NOT")? "IN" parameter=Parameter)
	)
;

SuggestedTypeFeature returns Feature:
	{SuggestedTypeFeature}"suggestedType"
;

// suggestion.<kind> — the artifact-backed suggestion facets (§11.1): status/predefinedStatus
// are the precomputed cross-check strings (§4.3), confidence is calibrated P(top-1),
// candidateN/confidenceN the raw ranked top-3 ("IFCSLAB.ROOF" for predefined leaves).
SuggestionFeature returns Feature:
	{SuggestionFeature} "suggestion" "." kind=("status" | "confidence" | "predefinedType" | "predefinedStatus" | "candidate1" | "candidate2" | "candidate3" | "confidence1" | "confidence2" | "confidence3")
;

// Properties can be any value, but if possible refer to the default Psets in the IFC standard
PropertyFeature returns Feature:
	({PropertyFeature} ("property" "." propertySetName=(STRING | ID | "*") "." propertyNames += (STRING | ID | "*") ("." propertyNames += (STRING | ID | "*"))* ("." field=PropertyField)?)) |
	({AllPropertiesFeature}) ("property" "." "*") |
	({PropertyMetaFeature}) ("property" "." "meta")
;

PropertyField:
	name = ("name" | "description" | "value" | "type" | "classType" | "propertySetName" | "oid" | "unit" | "symbol")
;

// classification.meta (docs/bql-meta-features-plan.md): ClassificationMetaFeature is a
// SUBTYPE of ClassificationFeature (the rule keeps its return type so that
// MaterialClassificationFeature.getClassification() and other typed consumers keep their
// API). Consequence: a meta instance also matches instanceof ClassificationFeature and
// looks like the bare form (field == null, system == null) — every dispatch on
// ClassificationFeature must check the meta subtype FIRST (FeatureDescriptorFactory,
// BqlWriter). Filtering on meta is rejected by BqlValidator for all meta features.
// An object can carry several classification references. The optional entry filter selects
// among them BEFORE the field is read, which is what correlates two fields of one entry
// (docs/virtual-features-design.md §5.1):
//   classification[system.name CONTAINS "SfB"].identification
// is the code of the NL-SfB reference only — without the filter a condition holds when ANY
// entry satisfies it, and two conditions may be satisfied by two different entries. A filtered
// feature is never answered from the value index (the index knows values, not entries).
ClassificationFeature returns ClassificationFeature:
	{ClassificationFeature} "classification" ("[" filter=ClassificationEntryFilter "]")? ("." (
		(field = ("*" | "name" | "itemReference" | "location" | "identification" | "identity")) |
		(system = ClassificationSystem)
	))? |
	{ClassificationMetaFeature} "classification" "." "meta"
;

// One comparison on a field of the entry or of its system; any comparator that takes a text
// literal applies (=, !=, CS =, IN, STARTS_WITH, ENDS_WITH, CONTAINS, MATCHES_REGEX, LENGTH).
ClassificationEntryFilter:
	{ClassificationEntryFilter} (system?="system" ".")? field=("name" | "itemReference" | "location" | "identification" | "identity" | "edition" | "source") comparator=Comparator
;

ClassificationSystem:
	{ClassificationSystem} "system" ("." (
		 field = ("*" | "name" | "edition" | "editionDate" | "source")
	))?
;

LayerFeature returns Feature:
	{LayerFeature} "layer" "." (
		name=("*" | "name")
	) |
	{LayerMetaFeature} "layer" "." "meta"
;

// representation.* - the compact IFC representation summary (nl.bimbase.simplebim.RepresentationSummary,
// BimRepository/docs/features-representation-summary-plan.md): "*" is the array of per-representation
// summaries the features panel renders; type / identifier / item are the indexed terminals for WHERE
// and GROUP BY (the representation type "SweptSolid", the identifier "Body", the item entity
// "IfcFacetedBrep"). "identifier" and "item" become keywords, the same accepted cost as
// classification's "edition" / "source".
RepresentationFeature returns Feature:
	{RepresentationFeature} "representation" "." (
		name=("*" | "type" | "identifier" | "item")
	)
;

MaterialFeature returns Feature:
	// => commits 'material.*' to MaterialAllFeature; without it this collides
	// with MaterialSimpleMultiSubFeature ("." subFeatures) because a
	// MaterialSubFeature name can also be "*". The '*'-as-subfeature reading
	// stays available via the complex form: material.(*)
	// material.meta needs the same => commitment as material.*: MaterialSimpleMultiSubFeature
	// makes the sub-feature optional after a mandatory dot, so without the predicate the
	// dangling-dot form would consume the "." and strand the meta keyword.
	"material" (
		(=>({MaterialAllFeature} "." "*")) | (=>({MaterialMetaFeature} "." "meta")) | MaterialMultiSubFeature
	)
;

MaterialMultiSubFeature returns Feature:
	MaterialSimpleMultiSubFeature | MaterialComplexMultiSubFeature 
;

MaterialSimpleMultiSubFeature returns Feature:
	{MaterialMultiSubFeature}
	"."
	// => declares the greedy (and already chosen) reading: consume a subfeature
	// whenever one can start here. Needed since Brl: embedding queries as report
	// values enlarges this rule's FOLLOW set (a query can be followed by a BRL
	// element named 'type'/'name'/...), which resurrected the phantom 3c
	// ambiguity ('*' as subfeature vs '*' in follow) for InternalBrl only —
	// see XTEXT-REGENERATION-ISSUES.md 3f. Real "material.*" input never
	// reaches this decision (committed to MaterialAllFeature by the caller's
	// predicate). No parse behavior change.
	(=>(subFeatures += MaterialSubFeature))?
;

MaterialComplexMultiSubFeature returns Feature:
	{MaterialMultiSubFeature}
	"("
		subFeatures += MaterialSubFeature ("," subFeatures += MaterialSubFeature)*
		("WHERE" where=BooleanExpression)?
		(groupBy=GroupBy)?
		(orderBy=OrderBy)?
		("LIMIT" limit=LONG)?
	")"
;

MaterialExpression returns Feature:
	"material" "." MaterialSubFeature
;

MaterialSubFeature returns Feature:
	({MaterialFeature} (
		name=("*" | "name" | "color" | "layerThickness")
	)) |
	({MaterialClassificationFeature} classification=ClassificationFeature) |
	({MaterialPropertiesFeature} property=PropertyFeature)
;

QuantityFeature returns Feature:
	({QuantityFeature} ("quantity" "." quantitySetName=(STRING | ID | "*") "." quantityNames += (STRING | ID | "*") ("." quantityNames += (STRING | ID | "*"))* ("." field=QuantityField)?)) | 
	({AllQuantitiesFeature}) "quantity" "." "*" |
	({QuantityMetaFeature}) ("quantity" "." "meta")
;

QuantityField:
	name = ("name" | "description" | "value" | "type" | "classType" | "quantitySetName" | "oid")
;

CalculatedFeature returns Feature:
	({CalculatedFeature} "calculated" "." child=(CalculatedProperties | CalculatedQuantities | CalculatedGeometry | CalculatedConsistency | CalculatedAabb | CalculatedObb | CalculatedDetails | CalculatedFigures | AllCalculatedChildren)) |
	({CalculatedMetaFeature}) ("calculated" "." "meta")
;

CalculatedDetails returns CalculatedChild:
	{CalculatedDetails} "details"
;

// calculated.figures - every figure of the object (the verification geometry of its calculated
// quantities, docs/quantity-figures-design.md §7), an object keyed by figure name; GET-only, not part of
// calculated.*. One figure is calculated.quantity.<key>.figure below.
CalculatedFigures returns CalculatedChild:
	{CalculatedFigures} "figures"
;

CalculatedQuantities returns CalculatedChild:
	{CalculatedQuantities}
		"quantity" "."
		(field=("floorArea" | "volume" | "perimeter" | "boundaryArea" | "area" | "frontArea" | "backArea" | "topArea"
		| "length" | "width" | "height" | "thickness" | "footprintLength" | "footprintWidth" | "footprintArea"
		| "grossSurface" | "netSurface" | "grossVolume" | "netVolume" | "shortestLength" | "axisLength" | "longestLength"
		| "minThickness" | "maxThickness" | "sectionWidth" | "sectionHeight" | "diameter" | "outlineSurface" | "endsSurface"
		| "outerPerimeter" | "openingPerimeter" | "totalPerimeter" | "totalRise" | "riserCount" | "treadCount"
		| "riserHeight" | "minRiserHeight" | "maxRiserHeight" | "runWidth" | "runDepth" | "treadDepth"
		| "openingArea" | "openingDepth" | "openingVolume"))
		("." subField=("value" | "figure" | "measurement" | "quality"))?
;

CalculatedGeometry returns CalculatedChild:
	{CalculatedGeometry} (
		"geometry" "."
		(
			(
				field=("hasGeometry" | "hasOwnGeometry" | "childrenHaveGeometry" | "hasGeneratedGeometry" | "geometryId" | "reused" | "isReusedGpu" | "segmented" | "simplified" | "hasTransparency" | "twoSidedTriangles")
				("." subField=("value"))?
			) | 
			(counts=CalculatedGeometryCounts)
		)
	)
;

CalculatedConsistency returns CalculatedChild:
	{CalculatedConsistency} (
		"consistency" "."
		field=("bwOpenEdges" | "watertight" | "manifold" | "orientationConsistent" | "degenerateTriangles" | "repaired" | "repairArchetype"
			| "originalWatertight" | "originalVolume")
		("." subField=("value"))?
	)
;

AllCalculatedChildren returns CalculatedChild:
	{AllCalculatedChildren} "*"
;

// The "level" property can be used to evaluate the level of a buildingStorey
CalculatedProperties returns CalculatedChild:
	{CalculatedProperties} (
		"property" "." 
		(field=("level" | "isExternal" | "internalTriangles" | "externalTriangles" | "visibleFragments"))
		("." subField=("value"))?
	)
;

CalculatedGeometryCounts:
	"counts" "." countField=CalculatedGeometryCountType
;

enum CalculatedGeometryCountType:
	VERTICES = "vertices" |
	TRIANGLE_INDICES = "triangleIndices" |
	WIREFRAME_INDICES = "wireframeIndices" |
	NORMALS = "normals" |
	TRIANGLES = "triangles" |
	COLORS = "colors"
;

CalculatedAabb returns CalculatedChild:
	{CalculatedAabb} "aabb" "." aabbSubFeature=AabbSubFeature
;

CalculatedObb returns CalculatedChild:
	{CalculatedObb} "obb" ("." obbSubFeature=ObbSubFeature)?
;

enum ObbSubFeature:
	CENTER_X="centerX" |
	CENTER_Y="centerY" |
	CENTER_Z="centerZ" |
	HALF_EXTEND_X="halfExtentX" |
	HALF_EXTEND_Y="halfExtentY" |
	HALF_EXTEND_Z="halfExtentZ" |
	AXIS1_X="axis1X" |
	AXIS1_Y="axis1Y" |
	AXIS1_Z="axis1Z" |
	AXIS2_X="axis2X" |
	AXIS2_Y="axis2Y" |
	AXIS2_Z="axis2Z" |
	AXIS3_X="axis3X" |
	AXIS3_Y="axis3Y" |
	AXIS3_Z="axis3Z"
;

GroupBy:
	"GROUP" "BY" features+=GetFeature ("," features+=GetFeature)*
;

OrderBy:
	OrderByFeatures | OrderByOriginal | OrderByGeometry
;

OrderByGeometry:
	{OrderByGeometry}
	"ORDER" "BY" "GEOMETRY" "(" expression=BooleanExpression ")"
;

OrderByFeatures:
	{OrderByFeatures}
	"ORDER" "BY" features+=OrderByFeature ("," features+=OrderByFeature)*
;

OrderByOriginal:
	{OrderByOriginal}
	"ORDER" "BY" "ORIGINAL"
;

OrderByFeature:
	{OrderByFeature}
	feature = GetFeature
	(direction = OrderDirection)?
;

enum OrderDirection: 
	ASCENDING="ASC" |
	DESCENDING="DESC"
;

// Having LONG before DOUBLE IS important!
terminal LONG returns ecore::ELong: "-"?('0'..'9')+;
terminal DOUBLE returns ecore::EDouble : "-"?INT ("." INT)?;

```
