1 | // Copyright (C) 2008 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.quasiliteral; |
16 | |
17 | import com.google.caja.parser.AncestorChain; |
18 | import com.google.caja.parser.Visitor; |
19 | import com.google.caja.parser.js.Identifier; |
20 | import com.google.caja.parser.js.SyntheticNodes; |
21 | import com.google.caja.reporting.MessageQueue; |
22 | |
23 | /** |
24 | * Non-ASCII characters can change the semantics of a program depending on how |
25 | * they're rendered, so we forbid them outside of strings. |
26 | * |
27 | * @author metaweta@gmail.com (Mike Stay) |
28 | */ |
29 | public final class NonAsciiCheckVisitor implements Visitor { |
30 | private final MessageQueue mq; |
31 | |
32 | public NonAsciiCheckVisitor(MessageQueue mq) { |
33 | this.mq = mq; |
34 | } |
35 | |
36 | /** |
37 | * Add an error to the queue if an identifier contains non-ASCII characters. |
38 | */ |
39 | public boolean visit(AncestorChain<?> ac) { |
40 | if (!(ac.node instanceof Identifier)) { return true; } |
41 | Identifier ident = (Identifier) ac.node; |
42 | String name = ident.getName(); |
43 | if (!ident.getAttributes().is(SyntheticNodes.SYNTHETIC) |
44 | && name != null && !name.matches("^[a-zA-Z_$][a-zA-Z0-9_$]*$")) { |
45 | mq.addMessage( |
46 | RewriterMessageType.NONASCII_IDENTIFIER, |
47 | ac.node.getFilePosition(), ac.node); |
48 | } |
49 | return true; |
50 | } |
51 | } |