1 | // Copyright (C) 2005 Google Inc. |
2 | // |
3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | // you may not use this file except in compliance with the License. |
5 | // You may obtain a copy of the License at |
6 | // |
7 | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | // |
9 | // Unless required by applicable law or agreed to in writing, software |
10 | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | // See the License for the specific language governing permissions and |
13 | // limitations under the License. |
14 | |
15 | package com.google.caja.parser.js; |
16 | |
17 | import com.google.caja.lexer.FilePosition; |
18 | import com.google.caja.parser.ParseTreeNode; |
19 | import com.google.caja.reporting.RenderContext; |
20 | import com.google.javascript.jscomp.jsonml.JsonML; |
21 | import com.google.javascript.jscomp.jsonml.TagType; |
22 | |
23 | import java.util.List; |
24 | |
25 | /** |
26 | * Encapsulates a value and the code to execute when the switch block is |
27 | * reached with that value. |
28 | * <p> |
29 | * When multiple cases are seen adjacent as in:{@code |
30 | * case FOO: |
31 | * case BAR: |
32 | * } |
33 | * each is a separate {@code CaseStmt} but the FOO case has a body which is |
34 | * a {@link Noop}. |
35 | * |
36 | * @author mikesamuel@gmail.com |
37 | */ |
38 | public final class CaseStmt extends SwitchCase { |
39 | private Expression caseValue; |
40 | private Block body; |
41 | |
42 | /** @param value unused. This ctor is provided for reflection. */ |
43 | @ReflectiveCtor |
44 | public CaseStmt( |
45 | FilePosition pos, Void value, List<? extends ParseTreeNode> children) { |
46 | this(pos, (Expression) children.get(0), (Block) children.get(1)); |
47 | } |
48 | |
49 | public CaseStmt(FilePosition pos, Expression caseValue, Block body) { |
50 | super(pos); |
51 | createMutation() |
52 | .appendChild(caseValue) |
53 | .appendChild(body) |
54 | .execute(); |
55 | } |
56 | |
57 | public Expression getCaseValue() { return caseValue; } |
58 | |
59 | @Override |
60 | public Block getBody() { return body; } |
61 | |
62 | @Override |
63 | protected void renderHead(RenderContext rc) { |
64 | rc.getOut().consume("case"); |
65 | caseValue.render(rc); |
66 | } |
67 | |
68 | @Override |
69 | protected void childrenChanged() { |
70 | super.childrenChanged(); |
71 | List<? extends ParseTreeNode> children = children(); |
72 | this.caseValue = (Expression) children.get(0); |
73 | this.body = (Block) children.get(1); |
74 | } |
75 | |
76 | @Override |
77 | public Object getValue() { return null; } |
78 | |
79 | public JsonML toJsonML() { |
80 | return JsonMLBuilder.builder(TagType.Case, getFilePosition()) |
81 | .addChild(caseValue) |
82 | .addChildren(body.children()) |
83 | .build(); |
84 | } |
85 | } |