1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// 3 Expressions
// 	3.1 Basics
// 	3.2 Function Calls
// 	3.3 Node-sets
// 	3.4 Booleans
// 	3.5 Numbers
// 	3.6 Strings
// 	3.7 Lexical Structure


// Expression evaluation occurs with respect to a context.
// XSLT and XPointer specify how the context is determined for XPath expressions used in XSLT and XPointer respectively.
// The context consists of:
//     a node (the context node)
//     a pair of non-zero positive integers (the context position and the context size)
//     a set of variable bindings
//     a function library
//     the set of namespace declarations in scope for the expression
// The context position is always less than or equal to the context size.

// Expressions are parsed by first dividing the character string to be parsed into tokens and then parsing the resulting sequence of tokens.
// Whitespace can be freely used between tokens.
// The tokenization process is described in [3.7 Lexical Structure].

use std::fmt;

use crate::functions;
use crate::{DEBUG, Value, Evaluation, Result, AxisName, Nodeset, NodeTest, Node};

pub type CallFunction = fn(ExpressionArg, ExpressionArg) -> ExpressionArg;
pub type ExpressionArg = Box<dyn Expression>;


pub trait Expression: fmt::Debug {
	fn eval(&self, eval: &Evaluation) -> Result<Value>;
}


// Operations

#[derive(Debug)]
pub struct Equal {
	left: ExpressionArg,
	right: ExpressionArg
}

impl Equal {
	pub fn new(left: ExpressionArg, right: ExpressionArg) -> Self {
		Self { left, right }
	}
}

impl Expression for Equal {
	fn eval(&self, eval: &Evaluation) -> Result<Value> {
		let left_value = self.left.eval(eval)?;
		let right_value = self.right.eval(eval)?;

		Ok(Value::Boolean(left_value == right_value))
	}
}


#[derive(Debug)]
pub struct NotEqual {
	left: ExpressionArg,
	right: ExpressionArg
}

impl NotEqual {
	pub fn new(left: ExpressionArg, right: ExpressionArg) -> Self {
		Self { left, right }
	}
}

impl Expression for NotEqual {
	fn eval(&self, eval: &Evaluation) -> Result<Value> {
		let left_value = self.left.eval(eval)?;
		let right_value = self.right.eval(eval)?;

		Ok(Value::Boolean(left_value != right_value))
	}
}


#[derive(Debug)]
pub struct And {
	left: ExpressionArg,
	right: ExpressionArg
}

impl And {
	pub fn new(left: ExpressionArg, right: ExpressionArg) -> Self {
		Self { left, right }
	}
}

impl Expression for And {
	fn eval(&self, eval: &Evaluation) -> Result<Value> {
		let left_value = self.left.eval(eval)?;
		let right_value = self.right.eval(eval)?;

		Ok(Value::Boolean(left_value.boolean()? && right_value.boolean()?))
	}
}



#[derive(Debug)]
pub struct Or {
	left: ExpressionArg,
	right: ExpressionArg
}

impl Or {
	pub fn new(left: ExpressionArg, right: ExpressionArg) -> Self {
		Self { left, right }
	}
}

impl Expression for Or {
	fn eval(&self, eval: &Evaluation) -> Result<Value> {
		let left_value = self.left.eval(eval)?;
		let right_value = self.right.eval(eval)?;

		Ok(Value::Boolean(left_value.boolean()? || right_value.boolean()?))
	}
}

// Primary Expressions

#[derive(Debug)]
pub struct Literal(Value);

impl From<Value> for Literal {
	fn from(value: Value) -> Self {
		Literal(value)
	}
}

impl Expression for Literal {
	fn eval(&self, _: &Evaluation) -> Result<Value> {
		Ok(self.0.clone())
	}
}


// Nodeset

#[derive(Debug)]
pub struct RootNode;

impl Expression for RootNode {
	fn eval(&self, eval: &Evaluation) -> Result<Value> {
		Ok(Value::Nodeset(vec![eval.root().clone()].into()))
	}
}


#[derive(Debug)]
pub struct ContextNode;

impl Expression for ContextNode {
	fn eval(&self, eval: &Evaluation) -> Result<Value> {
		// TODO: Figure out. Cannot clone an Rc
		Ok(Value::Nodeset(vec![eval.node.clone()].into()))
	}
}


#[derive(Debug)]
pub struct Path {
	pub start_pos: ExpressionArg,
	pub steps: Vec<Step>
}

impl Path {
	pub fn new(start_pos: ExpressionArg, steps: Vec<Step>) -> Self {
		Self {
			start_pos,
			steps
		}
	}
}

impl Expression for Path {
	fn eval(&self, eval: &Evaluation) -> Result<Value> {
		let result = self.start_pos.eval(eval)?;
		let mut set = result.into_nodeset()?;

		for step in &self.steps {
			set = step.evaluate(eval, set)?;
		}

		Ok(Value::Nodeset(set))
	}
}



#[derive(Debug)]
pub struct Step {
	axis: AxisName,
	node_test: Box<dyn NodeTest>, // A Step Test
	predicates: Vec<Predicate>
}

impl Step {
	pub fn new(
		axis: AxisName,
		node_test: Box<dyn NodeTest>,
		predicates: Vec<ExpressionArg>,
	) -> Step {
		let preds = predicates
			.into_iter()
			.map(|p| Predicate(p))
			.collect();

		Step {
			axis,
			node_test,
			predicates: preds,
		}
	}

	fn evaluate(
		&self,
		context: &Evaluation,
		starting_nodes: Nodeset,
	) -> Result<Nodeset> {
		// For every starting node, we collect new nodes based on the
		// axis and node-test. We evaluate the predicates on each node.

		// This seems like a likely place where we could differ from
		// the spec, so thorough testing is key.

		let mut unique = Nodeset::new();

		for node in starting_nodes.nodes {
			let child_context = context.new_evaluation_from(node);
			let nodes = child_context.find_nodes(&self.axis, self.node_test.as_ref());

			unique.extend(nodes);
		}

		if DEBUG && !self.predicates.is_empty() {
			println!("Pre Predicate:");
			println!("{:#?}", unique);
		}

		for predicate in &self.predicates {
			unique = predicate.select(&context, unique)?;
		}

		Ok(unique)
	}
}


// https://www.w3.org/TR/1999/REC-xpath-19991116/#predicates
#[derive(Debug)]
struct Predicate(ExpressionArg);

impl Predicate {
	fn select<'c>(
		&self,
		context: &Evaluation<'c>,
		nodes: Nodeset,
	) -> Result<Nodeset> {
		let found: Vec<Node> = context.new_evaluation_set_from(nodes)
			.filter_map(|ctx| {
				match self.matches_eval(&ctx) {
					Ok(true) => Some(Ok(ctx.node)),
					Ok(false) => None,
					Err(e) => Some(Err(e)),
				}
			})
			.collect::<Result<Vec<Node>>>()?;

		Ok(found.into())
	}

	fn matches_eval(&self, context: &Evaluation<'_>) -> Result<bool> {
		let value = self.0.eval(context)?;

		Ok(match value {
			// Is Node in the correct position? ex: //node[3]
			Value::Number(v) => context.position == v as usize,
			// Otherwise ensure a value properly exists.
			_ => value.exists()
		})
	}
}


#[derive(Debug)]
pub struct Function(Box<dyn functions::Function>);

impl Function {
	pub fn new(inner: Box<dyn functions::Function>) -> Function {
		Function(inner)
	}
}

impl Expression for Function {
	fn eval(&self, eval: &Evaluation) -> Result<Value> {
		self.0.exec(eval)
	}
}