ast.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // Copyright 2015 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package promql
  14. import (
  15. "time"
  16. "github.com/pkg/errors"
  17. "github.com/influxdata/promql/v2/pkg/labels"
  18. )
  19. // Node is a generic interface for all nodes in an AST.
  20. //
  21. // Whenever numerous nodes are listed such as in a switch-case statement
  22. // or a chain of function definitions (e.g. String(), expr(), etc.) convention is
  23. // to list them as follows:
  24. //
  25. // - Statements
  26. // - statement types (alphabetical)
  27. // - ...
  28. // - Expressions
  29. // - expression types (alphabetical)
  30. // - ...
  31. //
  32. type Node interface {
  33. // String representation of the node that returns the given node when parsed
  34. // as part of a valid query.
  35. String() string
  36. }
  37. // Statement is a generic interface for all statements.
  38. type Statement interface {
  39. Node
  40. // stmt ensures that no other type accidentally implements the interface
  41. stmt()
  42. }
  43. // EvalStmt holds an expression and information on the range it should
  44. // be evaluated on.
  45. type EvalStmt struct {
  46. Expr Expr // Expression to be evaluated.
  47. // The time boundaries for the evaluation. If Start equals End an instant
  48. // is evaluated.
  49. Start, End time.Time
  50. // Time between two evaluated instants for the range [Start:End].
  51. Interval time.Duration
  52. }
  53. func (*EvalStmt) stmt() {}
  54. // Expr is a generic interface for all expression types.
  55. type Expr interface {
  56. Node
  57. // Type returns the type the expression evaluates to. It does not perform
  58. // in-depth checks as this is done at parsing-time.
  59. Type() ValueType
  60. // expr ensures that no other types accidentally implement the interface.
  61. expr()
  62. }
  63. // Expressions is a list of expression nodes that implements Node.
  64. type Expressions []Expr
  65. // AggregateExpr represents an aggregation operation on a Vector.
  66. type AggregateExpr struct {
  67. Op ItemType // The used aggregation operation.
  68. Expr Expr // The Vector expression over which is aggregated.
  69. Param Expr // Parameter used by some aggregators.
  70. Grouping []string // The labels by which to group the Vector.
  71. Without bool // Whether to drop the given labels rather than keep them.
  72. }
  73. // BinaryExpr represents a binary expression between two child expressions.
  74. type BinaryExpr struct {
  75. Op ItemType // The operation of the expression.
  76. LHS, RHS Expr // The operands on the respective sides of the operator.
  77. // The matching behavior for the operation if both operands are Vectors.
  78. // If they are not this field is nil.
  79. VectorMatching *VectorMatching
  80. // If a comparison operator, return 0/1 rather than filtering.
  81. ReturnBool bool
  82. }
  83. // Call represents a function call.
  84. type Call struct {
  85. Func *Function // The function that was called.
  86. Args Expressions // Arguments used in the call.
  87. }
  88. // MatrixSelector represents a Matrix selection.
  89. type MatrixSelector struct {
  90. Name string
  91. Range time.Duration
  92. Offset time.Duration
  93. LabelMatchers []*labels.Matcher
  94. }
  95. // SubqueryExpr represents a subquery.
  96. type SubqueryExpr struct {
  97. Expr Expr
  98. Range time.Duration
  99. Offset time.Duration
  100. Step time.Duration
  101. }
  102. // NumberLiteral represents a number.
  103. type NumberLiteral struct {
  104. Val float64
  105. }
  106. // ParenExpr wraps an expression so it cannot be disassembled as a consequence
  107. // of operator precedence.
  108. type ParenExpr struct {
  109. Expr Expr
  110. }
  111. // StringLiteral represents a string.
  112. type StringLiteral struct {
  113. Val string
  114. }
  115. // UnaryExpr represents a unary operation on another expression.
  116. // Currently unary operations are only supported for Scalars.
  117. type UnaryExpr struct {
  118. Op ItemType
  119. Expr Expr
  120. }
  121. // VectorSelector represents a Vector selection.
  122. type VectorSelector struct {
  123. Name string
  124. Offset time.Duration
  125. LabelMatchers []*labels.Matcher
  126. }
  127. func (e *AggregateExpr) Type() ValueType { return ValueTypeVector }
  128. func (e *Call) Type() ValueType { return e.Func.ReturnType }
  129. func (e *MatrixSelector) Type() ValueType { return ValueTypeMatrix }
  130. func (e *SubqueryExpr) Type() ValueType { return ValueTypeMatrix }
  131. func (e *NumberLiteral) Type() ValueType { return ValueTypeScalar }
  132. func (e *ParenExpr) Type() ValueType { return e.Expr.Type() }
  133. func (e *StringLiteral) Type() ValueType { return ValueTypeString }
  134. func (e *UnaryExpr) Type() ValueType { return e.Expr.Type() }
  135. func (e *VectorSelector) Type() ValueType { return ValueTypeVector }
  136. func (e *BinaryExpr) Type() ValueType {
  137. if e.LHS.Type() == ValueTypeScalar && e.RHS.Type() == ValueTypeScalar {
  138. return ValueTypeScalar
  139. }
  140. return ValueTypeVector
  141. }
  142. func (*AggregateExpr) expr() {}
  143. func (*BinaryExpr) expr() {}
  144. func (*Call) expr() {}
  145. func (*MatrixSelector) expr() {}
  146. func (*SubqueryExpr) expr() {}
  147. func (*NumberLiteral) expr() {}
  148. func (*ParenExpr) expr() {}
  149. func (*StringLiteral) expr() {}
  150. func (*UnaryExpr) expr() {}
  151. func (*VectorSelector) expr() {}
  152. // VectorMatchCardinality describes the cardinality relationship
  153. // of two Vectors in a binary operation.
  154. type VectorMatchCardinality int
  155. const (
  156. CardOneToOne VectorMatchCardinality = iota
  157. CardManyToOne
  158. CardOneToMany
  159. CardManyToMany
  160. )
  161. func (vmc VectorMatchCardinality) String() string {
  162. switch vmc {
  163. case CardOneToOne:
  164. return "one-to-one"
  165. case CardManyToOne:
  166. return "many-to-one"
  167. case CardOneToMany:
  168. return "one-to-many"
  169. case CardManyToMany:
  170. return "many-to-many"
  171. }
  172. panic("promql.VectorMatchCardinality.String: unknown match cardinality")
  173. }
  174. // VectorMatching describes how elements from two Vectors in a binary
  175. // operation are supposed to be matched.
  176. type VectorMatching struct {
  177. // The cardinality of the two Vectors.
  178. Card VectorMatchCardinality
  179. // MatchingLabels contains the labels which define equality of a pair of
  180. // elements from the Vectors.
  181. MatchingLabels []string
  182. // On includes the given label names from matching,
  183. // rather than excluding them.
  184. On bool
  185. // Include contains additional labels that should be included in
  186. // the result from the side with the lower cardinality.
  187. Include []string
  188. }
  189. // Visitor allows visiting a Node and its child nodes. The Visit method is
  190. // invoked for each node with the path leading to the node provided additionally.
  191. // If the result visitor w is not nil and no error, Walk visits each of the children
  192. // of node with the visitor w, followed by a call of w.Visit(nil, nil).
  193. type Visitor interface {
  194. Visit(node Node, path []Node) (w Visitor, err error)
  195. }
  196. // Walk traverses an AST in depth-first order: It starts by calling
  197. // v.Visit(node, path); node must not be nil. If the visitor w returned by
  198. // v.Visit(node, path) is not nil and the visitor returns no error, Walk is
  199. // invoked recursively with visitor w for each of the non-nil children of node,
  200. // followed by a call of w.Visit(nil), returning an error
  201. // As the tree is descended the path of previous nodes is provided.
  202. func Walk(v Visitor, node Node, path []Node) error {
  203. var err error
  204. if v, err = v.Visit(node, path); v == nil || err != nil {
  205. return err
  206. }
  207. path = append(path, node)
  208. switch n := node.(type) {
  209. case *EvalStmt:
  210. if err := Walk(v, n.Expr, path); err != nil {
  211. return err
  212. }
  213. case Expressions:
  214. for _, e := range n {
  215. if err := Walk(v, e, path); err != nil {
  216. return err
  217. }
  218. }
  219. case *AggregateExpr:
  220. if n.Param != nil {
  221. if err := Walk(v, n.Param, path); err != nil {
  222. return err
  223. }
  224. }
  225. if err := Walk(v, n.Expr, path); err != nil {
  226. return err
  227. }
  228. case *BinaryExpr:
  229. if err := Walk(v, n.LHS, path); err != nil {
  230. return err
  231. }
  232. if err := Walk(v, n.RHS, path); err != nil {
  233. return err
  234. }
  235. case *Call:
  236. if err := Walk(v, n.Args, path); err != nil {
  237. return err
  238. }
  239. case *SubqueryExpr:
  240. if err := Walk(v, n.Expr, path); err != nil {
  241. return err
  242. }
  243. case *ParenExpr:
  244. if err := Walk(v, n.Expr, path); err != nil {
  245. return err
  246. }
  247. case *UnaryExpr:
  248. if err := Walk(v, n.Expr, path); err != nil {
  249. return err
  250. }
  251. case *MatrixSelector, *NumberLiteral, *StringLiteral, *VectorSelector:
  252. // nothing to do
  253. default:
  254. panic(errors.Errorf("promql.Walk: unhandled node type %T", node))
  255. }
  256. _, err = v.Visit(nil, nil)
  257. return err
  258. }
  259. type inspector func(Node, []Node) error
  260. func (f inspector) Visit(node Node, path []Node) (Visitor, error) {
  261. if err := f(node, path); err != nil {
  262. return nil, err
  263. }
  264. return f, nil
  265. }
  266. // Inspect traverses an AST in depth-first order: It starts by calling
  267. // f(node, path); node must not be nil. If f returns a nil error, Inspect invokes f
  268. // for all the non-nil children of node, recursively.
  269. func Inspect(node Node, f inspector) {
  270. //nolint: errcheck
  271. Walk(inspector(f), node, nil)
  272. }