-
Notifications
You must be signed in to change notification settings - Fork 103
/
Scope.scala
388 lines (321 loc) · 10.6 KB
/
Scope.scala
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/**
* Copyright (C) 2009-2011 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.scalate.mustache
import org.fusesource.scalate.RenderContext
import org.fusesource.scalate.introspector.Introspector
import scala.collection.JavaConverters._
import java.{ lang => jl, util => ju }
import xml.{ NodeSeq, XML }
import org.fusesource.scalate.util.Log
object Scope extends Log {
def apply(context: RenderContext) = {
context.attributeOrElse[Scope]("scope", RenderContextScope(context))
}
}
/**
* Represents a variable scope
*
* @version $Revision : 1.1 $
*/
trait Scope {
import Scope._
def parent: Option[Scope]
def context: RenderContext
var implicitIterator: Option[String] = Some(".")
/**
* Renders the given variable name to the context
*/
def renderVariable(name: String, unescape: Boolean): Unit = {
val v = apply(name) match {
case Some(a) => a
case None =>
parent match {
case Some(p) => p.apply(name)
case _ => null
}
}
debug("renderVariable %s = %s on %s", name, v, this)
renderValue(v, unescape)
}
def renderValue(v: Any, unescape: Boolean = false): Unit = if (unescape) {
context.unescape(format(v))
} else {
context.escape(format(v))
}
/**
* Returns the variable of the given name looking in this scope or parent scopes to resolve the variable
*/
def apply(name: String): Option[Any] = {
val value = localVariable(name)
value match {
case Some(v) => value
case _ =>
if (implicitIterator.isDefined && implicitIterator.get == name) {
iteratorObject
} else {
parent match {
case Some(p) => p.apply(name)
case _ => None
}
}
}
}
/**
* Returns the current implicit iterator object
*/
def iteratorObject: Option[Any] = None
/**
* Returns the variable in the local scope if it is defined
*/
def localVariable(name: String): Option[Any]
def section(name: String)(block: Scope => Unit): Unit = {
apply(name) match {
case Some(t) =>
val v = toTraversable(t, block)
debug("section value " + name + " = " + v + " in " + this)
v match {
// TODO we have to be really careful to distinguish between collections of things
// such as Seq from objects / products / Maps / partial functions which act as something to lookup names
case FunctionResult(r) => renderValue(r)
case s: NodeSeq => childScope(name, s)(block)
case s: Seq[Any] => foreachScope(name, s)(block)
case Some(a) => childScope(name, a)(block)
case None =>
// lets treat empty maps as being empty collections
// due to bug in JSON parser returning Map() for JSON expression []
case s: collection.Map[_, _] => if (!s.isEmpty) childScope(name, s)(block)
// maps and so forth, treat as child scopes
case a: PartialFunction[_, _] => childScope(name, a)(block)
// any other traversable treat as a collection
case s: Traversable[Any] => foreachScope(name, s)(block)
case true => block(this)
case false =>
case null =>
// lets treat anything as an an object rather than a collection
case a => childScope(name, a)(block)
}
case None => parent match {
case Some(ps) => ps.section(name)(block)
case None => // do nothing, no value
debug("No value for " + name + " in " + this)
}
}
}
def invertedSection(name: String)(block: Scope => Unit): Unit = {
apply(name) match {
case Some(t) =>
val v = toTraversable(t, block)
debug("invertedSection value " + name + " = " + v + " in " + this)
v match {
// TODO we have to be really careful to distinguish between collections of things
// such as Seq from objects / products / Maps / partial functions which act as something to lookup names
case FunctionResult(r) =>
case s: NodeSeq => if (s.isEmpty) block(this)
case s: Seq[_] => if (s.isEmpty) block(this)
case Some(a) =>
case None => block(this)
case s: collection.Map[_, _] => if (s.isEmpty) block(this)
// maps and so forth, treat as child scopes
case a: PartialFunction[_, _] =>
// any other traversible treat as a collection
case s: Traversable[Any] => if (s.isEmpty) block(this)
case true =>
case false => block(this)
case null => block(this)
// lets treat anything as an an object rather than a collection
case a =>
}
case None => block(this)
}
}
def partial(name: String): Unit = {
context.withAttributes(Map("scope" -> this)) {
// TODO allow the extension to be overloaded
context.include(name + ".mustache")
}
}
def childScope(name: String, v: Any)(block: Scope => Unit): Unit = {
debug("Creating scope for: " + v)
val scope = createScope(name, v)
block(scope)
}
def foreachScope[T](name: String, s: Traversable[T])(block: Scope => Unit): Unit = {
for (i <- s) {
debug("Creating traversable scope for: " + i)
val scope = createScope(name, i)
block(scope)
}
}
def createScope(name: String, value: Any): Scope = {
value match {
case n: NodeSeq => new NodeScope(this, name, n)
case v: scala.collection.convert.Wrappers.JMapWrapper[_, _] =>
new MapScope(
this,
name,
v.asInstanceOf[scala.collection.convert.Wrappers.JMapWrapper[String, _]]
)
case v: scala.collection.Map[_, _] =>
new MapScope(
this,
name,
v.asInstanceOf[Map[String, _]]
)
case null => new EmptyScope(this)
case None => new EmptyScope(this)
case v: AnyRef => new ObjectScope(this, v)
case v =>
warn("Unable to process value: %s", v)
new EmptyScope(this)
}
}
def toTraversable(v: Any, block: Scope => Unit): Any = v match {
case t: Seq[_] => t
case t: Array[_] => t.toSeq
case t: ju.Map[_, _] => t.asScala
case f: Function0[_] => toTraversable(f(), block)
case f: Function1[_, _] =>
if (isParam1(f, classOf[Object])) {
// Java lambda support since 1.8
try {
val f2 = f.asInstanceOf[Function1[Scope, _]]
toTraversable(f2(this), block)
} catch {
case e: Exception =>
try {
val f2 = f.asInstanceOf[Function1[String, _]]
FunctionResult(f2(capture(block)))
} catch {
case e: Exception =>
f
}
}
} else {
f
}
case c: ju.Collection[_] => c.asScala
case i: ju.Iterator[_] => i.asScala
case i: jl.Iterable[_] => i.asScala
case _ => v
}
def format(v: Any): Any = v match {
case f: Function0[_] => format(f())
case f: Function1[_, _] if isParam1(f, classOf[Scope]) => format(f.asInstanceOf[Function1[Scope, _]](this))
case f: Function1[_, _] =>
try {
format(f.asInstanceOf[Function1[Object, _]](this))
} catch {
case e: ClassCastException =>
v
}
case _ => v
}
/**
* Captures the output of the given block
*/
def capture(block: Scope => Unit): String = {
def body(): Unit = block(this)
context.capture(body)
}
def isParam1[T](f: Function1[_, _], clazz: Class[T]): Boolean = {
try {
f.getClass.getMethod("apply", clazz)
true
} catch { case e: NoSuchMethodException => false }
}
}
/**
* Scope for the render context
*/
case class RenderContextScope(
context: RenderContext,
defaultObjectName: Option[String] = Some("it")
) extends Scope {
// lets create a parent scope which is the defaultObject scope so we look there last
val rootScope = MarkupAttributeContextScope(context, "html")
val _parent: Option[Scope] = defaultObjectName match {
case Some(name) => apply(name) match {
case Some(value) => Some(rootScope.createScope(name, value))
case _ => Some(rootScope)
}
case _ => Some(rootScope)
}
def parent: Option[Scope] = _parent
def localVariable(name: String): Option[Any] = context.attributes.get(name)
}
/**
* A context intended for use in layouts which looks up an attribute in the render context and if it exists
* returns a new child scope for walking the templates markup
*/
case class MarkupAttributeContextScope(
context: RenderContext,
attributeName: String
) extends Scope {
def parent = None
def localVariable(name: String) = if (name == attributeName) {
// lets get the context from the attributes
// by default this is stored in the 'body' attribute in the current
// layout mechanism
context.attributes.get("body") match {
case Some(t) =>
val text = t.toString
// lets create a markup scope
Some(XML.loadString(text))
case v =>
None
}
} else None
}
abstract class ChildScope(parentScope: Scope) extends Scope {
implicitIterator = parentScope.implicitIterator
def parent = Some(parentScope)
def context = parentScope.context
}
class MapScope(
parent: Scope,
name: String,
map: collection.Map[String, _]
) extends ChildScope(parent) {
def localVariable(name: String): Option[Any] = map.get(name)
}
class NodeScope(
parent: Scope,
name: String,
node: NodeSeq
) extends ChildScope(parent) {
def localVariable(name: String): Option[Any] = Some(node \ name)
}
class EmptyScope(
parent: Scope
) extends ChildScope(parent) {
def localVariable(name: String) = None
}
/**
* Constructs a scope for a non-null and not None value
*/
class ObjectScope[T <: AnyRef](
parent: Scope,
value: T
) extends ChildScope(parent) {
val introspector = Introspector[T](value.getClass.asInstanceOf[Class[T]])
def localVariable(name: String) = introspector.get(name, value)
override def iteratorObject = Some(value)
}
case class FunctionResult(
value: Any
)