lexer.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package ast
  2. import (
  3. "fmt"
  4. multierror "github.com/hashicorp/go-multierror"
  5. )
  6. // ============================================================================
  7. // This file contains:
  8. // Lexing (string -> []token) for V2 of allocation filters
  9. // ============================================================================
  10. //
  11. // See parser.go for a formal grammar and external links.
  12. type tokenKind int
  13. const (
  14. colon tokenKind = iota // ':'
  15. comma // ','
  16. plus // '+'
  17. or // '|'
  18. bangColon // '!:'
  19. tildeColon // '~:'
  20. bangTildeColon // '!~:'
  21. startTildeColon // '<~:'
  22. bangStartTildeColon // '!<~:'
  23. tildeEndColon // '~>:'
  24. bangTildeEndColon // '!~>:'
  25. parenOpen // '('
  26. parenClose // ')'
  27. str // '"foo"'
  28. filterField // 'namespace', 'cluster'
  29. mapField // 'label', 'annotation'
  30. keyedAccess // '[app]', '[foo]', etc.
  31. identifier // K8s valid name + sanitized Prom: 'app', 'abc_label'
  32. eof
  33. )
  34. func (tk tokenKind) String() string {
  35. switch tk {
  36. case colon:
  37. return "colon"
  38. case comma:
  39. return "comma"
  40. case plus:
  41. return "plus"
  42. case or:
  43. return "or"
  44. case bangColon:
  45. return "bangColon"
  46. case tildeColon:
  47. return "tildeColon"
  48. case bangTildeColon:
  49. return "bangTildeColon"
  50. case startTildeColon:
  51. return "startTildeColon"
  52. case bangStartTildeColon:
  53. return "bangStartTildeColon"
  54. case tildeEndColon:
  55. return "tildeEndColon"
  56. case bangTildeEndColon:
  57. return "bangTildeEndColon"
  58. case parenOpen:
  59. return "parenOpen"
  60. case parenClose:
  61. return "parenClose"
  62. case str:
  63. return "str"
  64. case filterField:
  65. return "filterField1"
  66. case mapField:
  67. return "filterField2"
  68. case keyedAccess:
  69. return "keyedAccess"
  70. case identifier:
  71. return "identifier"
  72. case eof:
  73. return "eof"
  74. default:
  75. return fmt.Sprintf("Unspecified: %d", tk)
  76. }
  77. }
  78. // ============================================================================
  79. // Lexer/Scanner
  80. //
  81. // Based on the Scanner class in Chapter 4: Scanning of Crafting Interpreters by
  82. // Robert Nystrom
  83. // ============================================================================
  84. type token struct {
  85. kind tokenKind
  86. s string
  87. }
  88. func (t token) String() string {
  89. return fmt.Sprintf("%s:%s", t.kind, t.s)
  90. }
  91. type scanner struct {
  92. source string
  93. tokens []token
  94. errors []error
  95. fields map[string]*Field
  96. mapFields map[string]*Field
  97. lexemeStartByte int
  98. nextByte int
  99. }
  100. func (s *scanner) scanTokens() {
  101. for !s.atEnd() {
  102. s.lexemeStartByte = s.nextByte
  103. s.scanToken()
  104. }
  105. s.tokens = append(s.tokens, token{kind: eof})
  106. }
  107. func (s scanner) atEnd() bool {
  108. return s.nextByte >= len(s.source)
  109. }
  110. // advance returns a byte because we only accept ASCII, which has to fit in a
  111. // byte
  112. //
  113. // TODO: If we add unicode support, advance() will probably have to return a
  114. // rune.
  115. func (s *scanner) advance() byte {
  116. b := s.source[s.nextByte]
  117. s.nextByte += 1
  118. return b
  119. }
  120. func (s *scanner) match(expected byte) bool {
  121. if s.atEnd() {
  122. return false
  123. }
  124. if s.source[s.nextByte] != expected {
  125. return false
  126. }
  127. s.nextByte += 1
  128. return true
  129. }
  130. func (s *scanner) addToken(kind tokenKind) {
  131. lexemeString := s.source[s.lexemeStartByte:s.nextByte]
  132. switch kind {
  133. // Eliminate surrounding characters like " and []
  134. case str, keyedAccess:
  135. lexemeString = lexemeString[1 : len(lexemeString)-1]
  136. }
  137. s.tokens = append(s.tokens, token{
  138. kind: kind,
  139. s: lexemeString,
  140. })
  141. }
  142. func (s *scanner) peek() byte {
  143. if s.atEnd() {
  144. return 0
  145. }
  146. return s.source[s.nextByte]
  147. }
  148. func (s *scanner) scanToken() {
  149. c := s.advance()
  150. switch c {
  151. case ':':
  152. s.addToken(colon)
  153. case ',':
  154. s.addToken(comma)
  155. case '+':
  156. s.addToken(plus)
  157. case '|':
  158. s.addToken(or)
  159. case '!':
  160. if s.match(':') {
  161. s.addToken(bangColon)
  162. } else if s.match('~') {
  163. if s.match(':') {
  164. s.addToken(bangTildeColon)
  165. } else if s.match('>') {
  166. if s.match(':') {
  167. s.addToken(bangTildeEndColon)
  168. } else {
  169. s.errors = append(s.errors, fmt.Errorf("Position %d: Unexpected '>'", s.nextByte-1))
  170. }
  171. } else {
  172. s.errors = append(s.errors, fmt.Errorf("Position %d: Unexpected '~'", s.nextByte-1))
  173. }
  174. } else if s.match('<') {
  175. if s.match('~') {
  176. if s.match(':') {
  177. s.addToken(bangStartTildeColon)
  178. } else {
  179. s.errors = append(s.errors, fmt.Errorf("Position %d: Unexpected '~'", s.nextByte-1))
  180. }
  181. } else {
  182. s.errors = append(s.errors, fmt.Errorf("Position %d: Unexpected '<'", s.nextByte-1))
  183. }
  184. } else {
  185. s.errors = append(s.errors, fmt.Errorf("Position %d: Unexpected '!'", s.nextByte-1))
  186. }
  187. case '(':
  188. s.addToken(parenOpen)
  189. case ')':
  190. s.addToken(parenClose)
  191. case '<':
  192. if s.match('~') {
  193. if s.match(':') {
  194. s.addToken(startTildeColon)
  195. } else {
  196. s.errors = append(s.errors, fmt.Errorf("Position %d: Unexpected '~'", s.nextByte-1))
  197. }
  198. } else {
  199. s.errors = append(s.errors, fmt.Errorf("Position %d: Unexpected '<'", s.nextByte-1))
  200. }
  201. case '~':
  202. if s.match(':') {
  203. s.addToken(tildeColon)
  204. } else if s.match('>') {
  205. if s.match(':') {
  206. s.addToken(tildeEndColon)
  207. } else {
  208. s.errors = append(s.errors, fmt.Errorf("Position %d: Unexpected '>'", s.nextByte-1))
  209. }
  210. } else {
  211. s.errors = append(s.errors, fmt.Errorf("Position %d: Unexpected '~'", s.nextByte-1))
  212. }
  213. // strings
  214. case '"':
  215. s.string()
  216. // keyed access
  217. case '[':
  218. s.keyedAccess()
  219. // Ignore whitespace chars outside of "" and [].
  220. case ' ', '\t', '\n', '\r':
  221. break
  222. default:
  223. // identifiers
  224. //
  225. // We can keep it simple and not _force_ the first character to be a
  226. // non-number because we don't need numbers in this language. If we need
  227. // to extend the language to support numbers, this has to become just
  228. // isAlpha() and then s.identifier() will use isIdentifierChar() in
  229. // its main loop.
  230. if isIdentifierChar(c) {
  231. s.identifier()
  232. break
  233. }
  234. // TODO: We could return a more exact error message for Unicode chars if
  235. // we added extra handling:
  236. // https://stackoverflow.com/questions/53069040/checking-a-string-contains-only-ascii-characters
  237. s.errors = append(s.errors, fmt.Errorf("unexpected character/byte at position %d. Please avoid Unicode.", s.nextByte-1))
  238. }
  239. }
  240. // isIdentifierChar should match Kubernetes-supported name characters.
  241. //
  242. // https://kubernetes.io/docs/concepts/overview/working-with-objects/names/
  243. //
  244. // TODO: This may not match all characters we support for cluster IDs (it may be
  245. // the case that cluster IDs can contain UTF-8 characters).
  246. func isIdentifierChar(b byte) bool {
  247. return (b >= '0' && b <= '9') || // 0-9
  248. (b >= 'A' && b <= 'Z') || // A-Z
  249. (b >= 'a' && b <= 'z') || // a-z
  250. b == '-' || // hyphens are allowed according to K8s spec
  251. b == '_' // underscores are allowed because of Prometheus sanitization
  252. }
  253. func (s *scanner) string() {
  254. for s.peek() != '"' && !s.atEnd() {
  255. s.advance()
  256. }
  257. if s.atEnd() {
  258. s.errors = append(s.errors, fmt.Errorf("unterminated string starting at %d", s.lexemeStartByte))
  259. return
  260. }
  261. // Consume closing '"'
  262. s.advance()
  263. s.addToken(str)
  264. }
  265. func (s *scanner) keyedAccess() {
  266. for s.peek() != ']' && !s.atEnd() {
  267. s.advance()
  268. }
  269. if s.atEnd() {
  270. s.errors = append(s.errors, fmt.Errorf("unterminated access starting at %d", s.lexemeStartByte))
  271. return
  272. }
  273. // Consume closing ']'
  274. s.advance()
  275. s.addToken(keyedAccess)
  276. }
  277. func (s *scanner) identifier() {
  278. for isIdentifierChar(s.peek()) {
  279. s.advance()
  280. }
  281. tokenText := s.source[s.lexemeStartByte:s.nextByte]
  282. if _, ok := s.fields[tokenText]; ok {
  283. s.addToken(filterField)
  284. } else if _, ok := s.mapFields[tokenText]; ok {
  285. s.addToken(mapField)
  286. } else {
  287. s.addToken(identifier)
  288. }
  289. }
  290. // lex will generate a slice of tokens provided a raw string and the filter field definitions
  291. func lex(raw string, fields map[string]*Field, mapFields map[string]*Field) ([]token, error) {
  292. s := scanner{
  293. source: raw,
  294. fields: fields,
  295. mapFields: mapFields,
  296. }
  297. s.scanTokens()
  298. if len(s.errors) > 0 {
  299. return s.tokens, multierror.Append(nil, s.errors...)
  300. }
  301. return s.tokens, nil
  302. }