parser.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import { RestrictedCelError, type ModelOptionName } from "./types.js";
  2. import type { RestrictedCelToken } from "./tokenizer.js";
  3. export type RestrictedCelExpression =
  4. | {
  5. readonly type: "literal";
  6. readonly value: string | number | boolean | null;
  7. readonly offset: number;
  8. }
  9. | { readonly type: "input"; readonly offset: number }
  10. | {
  11. readonly type: "array";
  12. readonly elements: readonly RestrictedCelExpression[];
  13. readonly offset: number;
  14. }
  15. | {
  16. readonly type: "object";
  17. readonly entries: readonly {
  18. readonly key: string;
  19. readonly value: RestrictedCelExpression;
  20. readonly offset: number;
  21. }[];
  22. readonly offset: number;
  23. }
  24. | {
  25. readonly type: "unary";
  26. readonly operator: "!" | "-" | "+";
  27. readonly operand: RestrictedCelExpression;
  28. readonly offset: number;
  29. }
  30. | {
  31. readonly type: "binary";
  32. readonly operator: string;
  33. readonly left: RestrictedCelExpression;
  34. readonly right: RestrictedCelExpression;
  35. readonly offset: number;
  36. }
  37. | {
  38. readonly type: "conditional";
  39. readonly condition: RestrictedCelExpression;
  40. readonly whenTrue: RestrictedCelExpression;
  41. readonly whenFalse: RestrictedCelExpression;
  42. readonly offset: number;
  43. };
  44. export function parseRestrictedCel(
  45. tokens: readonly RestrictedCelToken[],
  46. variableName: ModelOptionName,
  47. ): RestrictedCelExpression {
  48. return new Parser(tokens, variableName).parse();
  49. }
  50. class Parser {
  51. #index = 0;
  52. constructor(
  53. private readonly tokens: readonly RestrictedCelToken[],
  54. private readonly variableName: ModelOptionName,
  55. ) {}
  56. parse(): RestrictedCelExpression {
  57. const expression = this.parseConditional();
  58. const trailing = this.current();
  59. if (trailing.kind !== "eof") {
  60. if (trailing.value === ".") {
  61. throw new RestrictedCelError("member access is not supported", trailing.offset);
  62. }
  63. if (trailing.value === "(") {
  64. throw new RestrictedCelError("function calls are not supported", trailing.offset);
  65. }
  66. throw new RestrictedCelError(
  67. `unexpected token ${JSON.stringify(trailing.value)}`,
  68. trailing.offset,
  69. );
  70. }
  71. return expression;
  72. }
  73. private parseConditional(): RestrictedCelExpression {
  74. const condition = this.parseLogicalOr();
  75. if (!this.consume("?")) return condition;
  76. const whenTrue = this.parseConditional();
  77. this.expect(":");
  78. const whenFalse = this.parseConditional();
  79. return { type: "conditional", condition, whenTrue, whenFalse, offset: condition.offset };
  80. }
  81. private parseLogicalOr(): RestrictedCelExpression {
  82. return this.parseBinary(() => this.parseLogicalAnd(), new Set(["||"]));
  83. }
  84. private parseLogicalAnd(): RestrictedCelExpression {
  85. return this.parseBinary(() => this.parseEquality(), new Set(["&&"]));
  86. }
  87. private parseEquality(): RestrictedCelExpression {
  88. return this.parseBinary(() => this.parseRelational(), new Set(["==", "!="]));
  89. }
  90. private parseRelational(): RestrictedCelExpression {
  91. return this.parseBinary(() => this.parseAdditive(), new Set(["<", "<=", ">", ">="]));
  92. }
  93. private parseAdditive(): RestrictedCelExpression {
  94. return this.parseBinary(() => this.parseMultiplicative(), new Set(["+", "-"]));
  95. }
  96. private parseMultiplicative(): RestrictedCelExpression {
  97. return this.parseBinary(() => this.parseUnary(), new Set(["*", "/", "%"]));
  98. }
  99. private parseBinary(
  100. parseOperand: () => RestrictedCelExpression,
  101. operators: ReadonlySet<string>,
  102. ): RestrictedCelExpression {
  103. let expression = parseOperand();
  104. while (this.current().kind === "operator" && operators.has(this.current().value)) {
  105. const operator = this.advance();
  106. expression = {
  107. type: "binary",
  108. operator: operator.value,
  109. left: expression,
  110. right: parseOperand(),
  111. offset: operator.offset,
  112. };
  113. }
  114. return expression;
  115. }
  116. private parseUnary(): RestrictedCelExpression {
  117. const token = this.current();
  118. if (
  119. token.kind === "operator" &&
  120. (token.value === "!" || token.value === "-" || token.value === "+")
  121. ) {
  122. this.advance();
  123. return {
  124. type: "unary",
  125. operator: token.value,
  126. operand: this.parseUnary(),
  127. offset: token.offset,
  128. };
  129. }
  130. return this.parsePrimary();
  131. }
  132. private parsePrimary(): RestrictedCelExpression {
  133. const token = this.advance();
  134. if (token.kind === "number") {
  135. const value = Number(token.value);
  136. if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value))) {
  137. throw new RestrictedCelError("number literal is not JSON-safe", token.offset);
  138. }
  139. return { type: "literal", value, offset: token.offset };
  140. }
  141. if (token.kind === "string")
  142. return { type: "literal", value: token.value, offset: token.offset };
  143. if (token.kind === "identifier") {
  144. if (this.current().value === "(") {
  145. throw new RestrictedCelError("function calls are not supported", this.current().offset);
  146. }
  147. if (token.value === this.variableName) return { type: "input", offset: token.offset };
  148. if (token.value === "true" || token.value === "false") {
  149. return { type: "literal", value: token.value === "true", offset: token.offset };
  150. }
  151. if (token.value === "null") return { type: "literal", value: null, offset: token.offset };
  152. throw new RestrictedCelError(
  153. `unknown identifier ${JSON.stringify(token.value)}`,
  154. token.offset,
  155. );
  156. }
  157. if (token.value === "(") {
  158. const expression = this.parseConditional();
  159. this.expect(")");
  160. return expression;
  161. }
  162. if (token.value === "[") return this.parseArray(token.offset);
  163. if (token.value === "{") return this.parseObject(token.offset);
  164. throw new RestrictedCelError(`unexpected token ${JSON.stringify(token.value)}`, token.offset);
  165. }
  166. private parseArray(offset: number): RestrictedCelExpression {
  167. const elements: RestrictedCelExpression[] = [];
  168. if (!this.consume("]")) {
  169. do elements.push(this.parseConditional());
  170. while (this.consume(","));
  171. this.expect("]");
  172. }
  173. return { type: "array", elements: Object.freeze(elements), offset };
  174. }
  175. private parseObject(offset: number): RestrictedCelExpression {
  176. const entries: { key: string; value: RestrictedCelExpression; offset: number }[] = [];
  177. const keys = new Set<string>();
  178. if (!this.consume("}")) {
  179. do {
  180. const key = this.advance();
  181. if (key.kind !== "string") {
  182. throw new RestrictedCelError("object keys must be string literals", key.offset);
  183. }
  184. if (keys.has(key.value)) {
  185. throw new RestrictedCelError(
  186. `duplicate object key ${JSON.stringify(key.value)}`,
  187. key.offset,
  188. );
  189. }
  190. keys.add(key.value);
  191. this.expect(":");
  192. entries.push({ key: key.value, value: this.parseConditional(), offset: key.offset });
  193. } while (this.consume(","));
  194. this.expect("}");
  195. }
  196. return { type: "object", entries: Object.freeze(entries), offset };
  197. }
  198. private consume(value: string): boolean {
  199. if (this.current().value !== value) return false;
  200. this.#index += 1;
  201. return true;
  202. }
  203. private expect(value: string): RestrictedCelToken {
  204. const token = this.current();
  205. if (token.value !== value) {
  206. throw new RestrictedCelError(`expected ${JSON.stringify(value)}`, token.offset);
  207. }
  208. this.#index += 1;
  209. return token;
  210. }
  211. private advance(): RestrictedCelToken {
  212. const token = this.current();
  213. if (token.kind !== "eof") this.#index += 1;
  214. return token;
  215. }
  216. private current(): RestrictedCelToken {
  217. return this.tokens[this.#index] ?? this.tokens[this.tokens.length - 1]!;
  218. }
  219. }