-
Notifications
You must be signed in to change notification settings - Fork 103
/
ScamlCodeGenerator.scala
673 lines (595 loc) · 20.4 KB
/
ScamlCodeGenerator.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
/**
* 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.scaml
import org.fusesource.scalate._
import collection.mutable.LinkedHashMap
import support.{ Text, Code, AbstractCodeGenerator }
import support.RenderHelper
import scala.util.parsing.input.OffsetPosition
import scala.language.implicitConversions
/**
* Generates a scala class given a HAML document
*
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
class ScamlCodeGenerator extends AbstractCodeGenerator[Statement] {
override val stratumName = "SCAML"
implicit def textToString(text: Text) = text.value
implicit def textOptionToString(text: Option[Text]): Option[String] = text match {
case None => None
case Some(x) => Some(x.value)
}
protected class SourceBuilder extends AbstractSourceBuilder[Statement] {
val text_buffer = new StringBuffer
var element_level = 0
var pending_newline = false
var suppress_indent = false
var in_html_comment = false
override def current_position = {
if (text_buffer.length == 0) {
super.current_position
} else {
super.current_position + ("$_scalate_$_context << ( " + asString(text_buffer.toString)).length
}
}
def write_indent() = {
if (pending_newline) {
text_buffer.append(ScamlOptions.nl)
pending_newline = false;
}
if (suppress_indent) {
suppress_indent = false
} else {
text_buffer.append(indent_string)
}
}
def indent_string() = {
val rc = new StringBuilder
for (i <- 0 until element_level) {
rc.append(ScamlOptions.indent)
}
rc.toString
}
def trim_whitespace() = {
pending_newline = false
suppress_indent = true
}
def write_text(value: String) = {
text_buffer.append(value)
}
def write_nl() = {
pending_newline = true
}
def flush_text() = {
if (pending_newline) {
text_buffer.append(ScamlOptions.nl)
pending_newline = false;
}
if (text_buffer.length > 0) {
this << "$_scalate_$_context << ( " + asString(text_buffer.toString) + " );"
text_buffer.setLength(0)
}
}
override def generateInitialImports = {
this << "import _root_.org.fusesource.scalate.support.RenderHelper.{sanitize=>$_scalate_$_sanitize, preserve=>$_scalate_$_preserve, indent=>$_scalate_$_indent, smart_sanitize=>$_scalate_$_smart_sanitize, attributes=>$_scalate_$_attributes}"
}
def generate(statements: List[Statement]): Unit = {
generate_with_flush(statements)
}
def generate_with_flush(statements: List[Statement]): Unit = {
generate_no_flush(statements)
flush_text
}
def generate_no_flush(statements: List[Statement]): Unit = {
var remaining = statements
while (remaining != Nil) {
val fragment = remaining.head
remaining = remaining.drop(1)
fragment match {
case attribute: Attribute =>
this << attribute.pos;
generateBindings(List(Binding(attribute.name.value, attribute.className.value, attribute.autoImport, attribute.defaultValue,
classNamePositional = Some(attribute.className), defaultValuePositional = attribute.defaultValue))) {
generate(remaining)
}
remaining = Nil
case _ =>
generate(fragment)
}
}
}
def generate(statement: Statement): Unit = {
statement match {
case s: Newline => {
}
case s: Attribute => {
}
case s: ScamlComment => {
generate(s)
}
case s: TextExpression => {
generateTextExpression(s, true)
}
case s: HtmlComment => {
generate(s)
}
case s: Element => {
generate(s)
}
case s: Executed => {
generate(s)
}
case s: FilterStatement => {
generate(s)
}
case s: Doctype => {
generate(s)
}
}
}
def generate(statement: Doctype): Unit = {
this << statement.pos;
write_indent
statement.line.map { _.value } match {
case List("XML") =>
write_text("<?xml version=\"1.0\" encoding=\"utf-8\" ?>")
case List("XML", encoding) =>
write_text("<?xml version=\"1.0\" encoding=\"" + encoding + "\" ?>")
case _ =>
ScamlOptions.format match {
case ScamlOptions.Format.xhtml =>
statement.line.map { _.value } match {
case List("Strict") =>
write_text("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">""")
case List("Frameset") =>
write_text("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">""")
case List("5") =>
write_text("""<!DOCTYPE html>""")
case List("1.1") =>
write_text("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">""")
case List("Basic") =>
write_text("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"> """)
case List("Mobile") =>
write_text("""<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">""")
case _ =>
write_text("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">""")
}
case ScamlOptions.Format.html4 =>
statement.line.map { _.value } match {
case List("Strict") =>
write_text("""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">""")
case List("Frameset") =>
write_text("""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">""")
case _ =>
write_text("""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">""")
}
case ScamlOptions.Format.html5 =>
write_text("""<!DOCTYPE html>""")
}
}
write_nl
}
def generate(statement: FilterStatement): Unit = {
def isEnabled(flag: String) = {
statement.flags.contains(Text(flag))
}
if (isEnabled("&") && isEnabled("!")) {
throw new InvalidSyntaxException("Cannot use both the '&' and '!' filter flags together.", statement.pos);
}
val preserve = isEnabled("~")
val interpolate = isEnabled("&") || isEnabled("!")
val sanitize = interpolate && isEnabled("&")
var content = statement.body.map { _.value }.mkString(ScamlOptions.nl)
var text: TextExpression = if (interpolate) {
val p = new ScamlParser(ScamlParser.UPTO_TYPE_MULTI_LINE)
try {
p.parse(p.literal_text(Some(sanitize)), content)
} catch {
case e: InvalidSyntaxException =>
val pos = statement.body.head.pos.asInstanceOf[OffsetPosition]
throw new InvalidSyntaxException(e.brief, OffsetPosition(pos.source, pos.offset + e.pos.column))
}
} else {
LiteralText(List(Text(content)), Some(sanitize))
}
var prefix = "$_scalate_$_context << ( "
var suffix = ");"
if (ScamlOptions.ugly) {
suppress_indent = true
} else if (preserve) {
prefix += " $_scalate_$_preserve ("
suffix = ") " + suffix;
} else {
prefix += "$_scalate_$_indent ( " + asString(indent_string()) + ", "
suffix = ") " + suffix;
}
for (f <- statement.filters) {
prefix += "$_scalate_$_context.value ( _root_.org.fusesource.scalate.filter.FilterRequest(" + asString(f) + ", "
suffix = ") ) " + suffix;
}
write_indent
flush_text
this << prefix + "$_scalate_$_context.capture { "
indent {
generateTextExpression(text, false)
flush_text
}
this << "} " + suffix
write_nl
}
def generateTextExpression(statement: TextExpression, is_line: Boolean): Unit = {
statement match {
case s: LiteralText => {
if (is_line) {
write_indent
}
var literal = true;
for (part <- s.text) {
// alternate between rendering literal and interpolated text
if (literal) {
write_text(part)
literal = false
} else {
flush_text
s.sanitize match {
case None =>
this << "$_scalate_$_context <<< ( " :: part :: " );" :: Nil
case Some(true) =>
this << "$_scalate_$_context.escape( " :: part :: " );" :: Nil
case Some(false) =>
this << "$_scalate_$_context.unescape( " :: part :: " );" :: Nil
}
literal = true
}
}
if (is_line) {
write_nl
}
}
case s: EvaluatedText => {
var prefix = "$_scalate_$_context << ("
var suffix = ");"
if (s.preserve || ScamlOptions.ugly) {
if (s.ugly || ScamlOptions.ugly) {
suppress_indent = true
} else {
prefix += " $_scalate_$_preserve ("
suffix = ") " + suffix;
}
} else {
prefix += " $_scalate_$_indent ( " + asString(indent_string()) + ","
suffix = ") " + suffix;
}
val method = s.sanitize match {
case Some(true) =>
"valueEscaped"
case Some(false) =>
"valueUnescaped"
case _ =>
"value"
}
prefix += " $_scalate_$_context." + method + "("
suffix = ") " + suffix;
if (is_line) {
write_indent
}
flush_text
if (s.body.isEmpty) {
this << prefix
indent {
this << s.code
}
this << suffix
} else {
this << prefix
indent {
this << s.code :: " {" :: Nil
indent {
generate_with_flush(s.body)
}
this << "}"
}
this << suffix
}
if (is_line) {
write_nl
}
}
}
}
def generate(statement: Executed): Unit = {
flush_text
if (statement.body.isEmpty) {
statement.code.foreach {
(line) =>
this << line :: Nil
}
} else {
statement.code.foreach {
(line) =>
if (line ne statement.code.last) {
this << line :: Nil
} else {
this << line :: "{" :: Nil
}
}
indent {
generate_no_flush(statement.body)
flush_text
}
this << "}"
}
}
def generate(statement: HtmlComment): Unit = {
// case class HtmlComment(conditional:Option[String], text:Option[String], body:List[Statement]) extends Statement
var prefix = "<!--"
var suffix = "-->"
if (statement.conditional.isDefined) {
prefix = "<!--[" + statement.conditional.get + "]>"
suffix = "<![endif]-->"
}
// To support comment within comment blocks.
if (in_html_comment) {
prefix = ""
suffix = ""
} else {
in_html_comment = true
}
statement match {
case HtmlComment(_, text, List()) => {
write_indent
this << statement.pos
write_text(prefix + " ")
if (text.isDefined) {
this << text.get.pos
write_text(text.get.trim)
}
write_text(" " + suffix)
write_nl
}
case HtmlComment(_, None, list) => {
write_indent
this << statement.pos;
write_text(prefix)
write_nl
element_level += 1
generate_no_flush(list)
element_level -= 1
write_indent
write_text(suffix)
write_nl
}
case _ => throw new InvalidSyntaxException("Illegal nesting: content can't be both given on the same line as html comment and nested within it", statement.pos);
}
if (prefix.length != 0) {
in_html_comment = false
}
}
def generate(statement: ScamlComment): Unit = {
this << statement.pos;
statement match {
case ScamlComment(text, List()) => {
this << "//" :: text.getOrElse("") :: Nil
}
case ScamlComment(text, list) => {
this << "/*" :: text.getOrElse("") :: Nil
list.foreach(x => {
this << " * " :: x :: Nil
})
this << " */"
}
}
}
def isAutoClosed(statement: Element) = {
statement.text == None && statement.body.isEmpty &&
statement.tag.isDefined && (ScamlOptions.autoclose == null || ScamlOptions.autoclose.contains(statement.tag.get.value))
}
def generate(statement: Element): Unit = {
var tag = statement.tag.getOrElse("div");
if (statement.text.isDefined && !statement.body.isEmpty) {
throw new InvalidSyntaxException("Illegal nesting: content can't be given on the same line as html element or nested within it if the tag is closed", statement.pos)
}
def write_start_tag = {
write_text("<" + tag)
write_attributes(statement.attributes)
if (statement.close || isAutoClosed(statement)) {
write_text("/>")
} else {
write_text(">")
}
}
def write_end_tag = {
if (statement.close || isAutoClosed(statement)) {
write_text("")
} else {
write_text("</" + tag + ">")
}
}
statement.trim match {
case Some(Trim.Outer) => {
}
case Some(Trim.Inner) => {}
case Some(Trim.Both) => {}
case _ => {}
}
def outer_trim = statement.trim match {
case Some(Trim.Outer) => { trim_whitespace; true }
case Some(Trim.Both) => { trim_whitespace; true }
case _ => { false }
}
def inner_trim = statement.trim match {
case Some(Trim.Inner) => { trim_whitespace; true }
case Some(Trim.Both) => { trim_whitespace; true }
case _ => { false }
}
outer_trim
this << statement.pos;
write_indent
write_start_tag
statement match {
case Element(_, _, text, List(), _, _) => {
generateTextExpression(text.getOrElse(LiteralText(List(Text("")), Some(false))), false)
write_end_tag
write_nl
outer_trim
}
case Element(_, _, None, list, _, _) => {
write_nl
if (!inner_trim) {
element_level += 1
}
generate_no_flush(list)
if (!inner_trim) {
element_level -= 1
}
write_indent
write_end_tag
write_nl
outer_trim
}
case _ => throw new InvalidSyntaxException("Illegal nesting: content can't be both given on the same line as html element and nested within it", statement.pos);
}
}
def write_attributes(entries: List[(Any, Any)]) = {
// Check to see if it's a dynamic attribute list
var dynamic = false
def check(n: Any): Unit = n match {
case x: EvaluatedText =>
dynamic = true
case x: LiteralText =>
if (x.text.length > 1) {
dynamic = true
}
case _ =>
}
for ((k, v) <- entries) {
check(k)
check(v)
}
if (dynamic) {
def write_expression(expression: Any) = {
expression match {
case s: String =>
this << asString(s)
case s: Text =>
this << s.pos
this << asString(s)
case s: LiteralText =>
this << s.pos
var literal = true;
val parts = s.text.map { part =>
// alternate between rendering literal and interpolated expression
if (literal) {
literal = !literal
asString(part) :: Nil
} else {
literal = !literal
List[AnyRef]("$_scalate_$_context.value(", part, ", false)")
}
}
this << parts.foldRight(List[AnyRef]()) {
case (prev, sum) =>
sum match {
case List() => prev
case _ => prev ::: " + " :: sum
}
}
flush_text
case s: EvaluatedText =>
if (s.body.isEmpty) {
this << s.code :: Nil
} else {
this << s.code :: " {" :: Nil
indent {
generate_with_flush(s.body)
}
this << "} "
}
case _ => throw new UnsupportedOperationException("don't know how to eval: " + expression);
}
}
flush_text
this << "$_scalate_$_context << $_scalate_$_attributes( $_scalate_$_context, List( ("
indent {
var first = true
entries.foreach {
(entry) =>
if (!first) {
this << "), ("
}
first = false
indent {
write_expression(entry._1)
}
this << ","
indent {
write_expression(entry._2)
}
}
}
this << ") ) )"
} else {
def value_of(value: Any): Text = {
value match {
case LiteralText(text, _) => text.head
case s: Text => s
case _ => throw new UnsupportedOperationException("don't know how to deal with: " + value);
}
}
val (entries_class, tmp) = entries.partition { x => { x._1 match { case "class" => true; case _ => false } } }
val (entries_id, entries_rest) = tmp.partition { x => { x._1 match { case "id" => true; case _ => false } } }
var map = LinkedHashMap[Text, Text]()
if (!entries_id.isEmpty) {
map += Text("id") -> value_of(entries_id.last._2)
}
if (!entries_class.isEmpty) {
var value: Option[Text] = None
value = entries_class.foldLeft(value) {
(rc, x) =>
rc match {
case None => Some(value_of(x._2))
case Some(y) => Some(y + " " + value_of(x._2))
}
}
map += Text("class") -> value.get
}
entries_rest.foreach { me => map += value_of(me._1) -> value_of(me._2) }
if (!map.isEmpty) {
map.foreach {
case (name, value) =>
write_text(" ")
this << name.pos
write_text(name)
write_text("=\"")
this << value.pos
write_text(RenderHelper.sanitize(value))
write_text("\"")
}
}
}
}
}
override def generate(engine: TemplateEngine, source: TemplateSource, bindings: Traversable[Binding]): Code = {
val uri = source.uri
val hamlSource = source.text
val statements = (new ScamlParser).parse(hamlSource)
val builder = new SourceBuilder()
builder.generate(engine, source, bindings, statements)
Code(source.className, builder.code, Set(uri), builder.positions)
}
}