|
| 1 | +import either, { type Either } from '@matt.kantor/either' |
| 2 | +import type { ElaborationError } from '../../errors.js' |
| 3 | +import type { Molecule } from '../../parsing.js' |
| 4 | +import { isSpecificExpression } from '../expression.js' |
| 5 | +import { keyPathFromObjectNodeOrMolecule } from '../key-path.js' |
| 6 | +import { |
| 7 | + isObjectNode, |
| 8 | + makeUnelaboratedObjectNode, |
| 9 | + type ObjectNode, |
| 10 | +} from '../object-node.js' |
| 11 | +import { type SemanticGraph, type unelaboratedKey } from '../semantic-graph.js' |
| 12 | +import { |
| 13 | + asSemanticGraph, |
| 14 | + readArgumentsFromExpression, |
| 15 | +} from './expression-utilities.js' |
| 16 | + |
| 17 | +export type IndexExpression = ObjectNode & { |
| 18 | + readonly 0: '@index' |
| 19 | + readonly object: ObjectNode | Molecule |
| 20 | + readonly query: ObjectNode | Molecule |
| 21 | +} |
| 22 | + |
| 23 | +export const readIndexExpression = ( |
| 24 | + node: SemanticGraph | Molecule, |
| 25 | +): Either<ElaborationError, IndexExpression> => |
| 26 | + isSpecificExpression('@index', node) |
| 27 | + ? either.flatMap( |
| 28 | + readArgumentsFromExpression(node, [ |
| 29 | + ['object', '1'], |
| 30 | + ['query', '2'], |
| 31 | + ]), |
| 32 | + ([o, q]) => { |
| 33 | + const object = asSemanticGraph(o) |
| 34 | + const query = asSemanticGraph(q) |
| 35 | + if (!isObjectNode(object)) { |
| 36 | + return either.makeLeft({ |
| 37 | + kind: 'invalidExpression', |
| 38 | + message: 'object must be an object', |
| 39 | + }) |
| 40 | + } else if (!isObjectNode(query)) { |
| 41 | + return either.makeLeft({ |
| 42 | + kind: 'invalidExpression', |
| 43 | + message: 'query must be an object', |
| 44 | + }) |
| 45 | + } else { |
| 46 | + return either.map( |
| 47 | + keyPathFromObjectNodeOrMolecule(query), |
| 48 | + _validKeyPath => makeIndexExpression({ object, query }), |
| 49 | + ) |
| 50 | + } |
| 51 | + }, |
| 52 | + ) |
| 53 | + : either.makeLeft({ |
| 54 | + kind: 'invalidExpression', |
| 55 | + message: 'not an expression', |
| 56 | + }) |
| 57 | + |
| 58 | +export const makeIndexExpression = ({ |
| 59 | + query, |
| 60 | + object, |
| 61 | +}: { |
| 62 | + readonly query: ObjectNode | Molecule |
| 63 | + readonly object: ObjectNode | Molecule |
| 64 | +}): IndexExpression & { readonly [unelaboratedKey]: true } => |
| 65 | + makeUnelaboratedObjectNode({ |
| 66 | + 0: '@index', |
| 67 | + object, |
| 68 | + query, |
| 69 | + }) |
0 commit comments