Debian Codegraph @

src/com/google/javascript/jscomp/deps/JsFileLineParser.java

raw symbols SCIP
1 /*
2 * Copyright 2008 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp.deps;
18
19 import com.google.common.collect.Lists;
20 import com.google.javascript.jscomp.CheckLevel;
21 import com.google.javascript.jscomp.DiagnosticType;
22 import com.google.javascript.jscomp.ErrorManager;
23 import com.google.javascript.jscomp.JSError;
24
25 import java.io.BufferedReader;
26 import java.io.IOException;
27 import java.io.Reader;
28 import java.util.List;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
31
32 /**
33 * Base class for classes that parse JavaScript sources on a line-by-line basis. Strips comments
34 * from files and records all parsing errors.
35 *
36 * @author [email protected] (Andrew Grieve)
37 */
38 public abstract class JsFileLineParser {
39
40 static final DiagnosticType PARSE_WARNING = DiagnosticType.warning(
41 "DEPS_PARSE_WARNING", "{0}\n{1}");
42 static final DiagnosticType PARSE_ERROR = DiagnosticType.error(
43 "DEPS_PARSE_ERROR", "{0}\n{1}");
44
45 boolean shortcutMode = false;
46
47 /**
48 * Thrown by base classes to signify a problem parsing a line.
49 */
50 static class ParseException extends Exception {
51 public static final long serialVersionUID = 1L;
52 private boolean fatal;
53
54 /**
55 * Constructor.
56 *
57 * @param message A description of what caused the exception.
58 * @param fatal Whether the exception is recoverable.
59 */
60 public ParseException(String message, boolean fatal) {
61 super(message);
62 this.fatal = fatal;
63 }
64
65 public boolean isFatal() {
66 return fatal;
67 }
68 }
69
70 /** Pattern for matching JavaScript string literals. */
71 private static final Pattern STRING_LITERAL_PATTERN = Pattern.compile(
72 "\\s*(?:'((?:\\\\'|[^'])*?)'|\"((?:\\\\\"|[^\"])*?)\")\\s*");
73
74 /** Matcher used in the parsing string literals. */
75 private Matcher valueMatcher = STRING_LITERAL_PATTERN.matcher("");
76
77 /** Path of the file currently being parsed. */
78 String filePath;
79 /** The line number of the line currently being parsed. */
80 int lineNum;
81 /** Handles error messages. */
82 ErrorManager errorManager;
83 /** Did our parse succeed. */
84 boolean parseSucceeded;
85
86 /**
87 * Constructor.
88 *
89 * @param errorManager Parse error handler.
90 */
91 public JsFileLineParser(ErrorManager errorManager) {
92 this.errorManager = errorManager;
93 }
94
95 /**
96 * In shortcut mode, the file line parser can stop reading early if
97 * it thinks it found enough information.
98 *
99 * For example, many parsers assume that dependency information never
100 * shows up after "real" code.
101 */
102 public void setShortcutMode(boolean mode) {
103 this.shortcutMode = mode;
104 }
105
106 public boolean didParseSucceed() {
107 return parseSucceeded;
108 }
109
110 /**
111 * Performs the line-by-line parsing of the given fileContents. This method
112 * strips out JavaScript comments and then uses the abstract parseLine()
113 * method to do the line parsing.
114 *
115 * @param filePath The path to the file being parsed. Used for reporting parse
116 * exceptions.
117 * @param fileContents A reader for the contents of the file.
118 */
119 void doParse(String filePath, Reader fileContents) {
120 this.filePath = filePath;
121 parseSucceeded = true;
122
123 BufferedReader lineBuffer = new BufferedReader(fileContents);
124
125 // Parse all lines.
126 String line = null;
127 lineNum = 0;
128 boolean inMultilineComment = false;
129
130 try {
131 while (null != (line = lineBuffer.readLine())) {
132 ++lineNum;
133 try {
134 String revisedLine = line;
135 if (inMultilineComment) {
136 int endOfComment = revisedLine.indexOf("*/");
137 if (endOfComment != -1) {
138 revisedLine = revisedLine.substring(endOfComment + 2);
139 inMultilineComment = false;
140 } else {
141 revisedLine = "";
142 }
143 }
144
145 if (!inMultilineComment) {
146 while (true) {
147 int startOfLineComment = revisedLine.indexOf("//");
148 int startOfMultilineComment = revisedLine.indexOf("/*");
149 if (startOfLineComment != -1 &&
150 (startOfMultilineComment == -1 ||
151 startOfLineComment < startOfMultilineComment)) {
152 revisedLine = revisedLine.substring(0, startOfLineComment);
153 break;
154 } else if (startOfMultilineComment != -1) {
155 int endOfMultilineComment = revisedLine.indexOf("*/",
156 startOfMultilineComment + 2);
157 if (endOfMultilineComment == -1) {
158 revisedLine = revisedLine.substring(
159 0, startOfMultilineComment);
160 inMultilineComment = true;
161 break;
162 } else {
163 revisedLine =
164 revisedLine.substring(0, startOfMultilineComment) +
165 revisedLine.substring(endOfMultilineComment + 2);
166 }
167 } else {
168 break;
169 }
170 }
171 }
172
173 if (!revisedLine.isEmpty()) {
174 // This check for shortcut mode should be redundant, but
175 // it's done for safety reasons.
176 if (!parseLine(revisedLine) && shortcutMode) {
177 break;
178 }
179 }
180 } catch (ParseException e) {
181 // Inform the error handler of the exception.
182 errorManager.report(
183 e.isFatal() ? CheckLevel.ERROR : CheckLevel.WARNING,
184 JSError.make(filePath, lineNum, 0 /* char offset */,
185 e.isFatal() ? PARSE_ERROR : PARSE_WARNING,
186 e.getMessage(), line));
187 parseSucceeded = parseSucceeded && !e.isFatal();
188 }
189 }
190 } catch (IOException e) {
191 errorManager.report(CheckLevel.ERROR,
192 JSError.make(filePath, 0, 0 /* char offset */,
193 PARSE_ERROR, "Error reading file: " + filePath));
194 parseSucceeded = false;
195 }
196 }
197
198 /**
199 * Called for each line of the file being parsed.
200 *
201 * @param line The line to parse.
202 * @return true to keep going, false otherwise.
203 * @throws ParseException Should be thrown to signify a problem with the line.
204 */
205 abstract boolean parseLine(String line) throws ParseException;
206
207 /**
208 * Parses a JS string literal.
209 *
210 * @param jsStringLiteral The literal. Must look like "asdf" or 'asdf'
211 * @throws ParseException Thrown if there is a string literal that cannot be
212 * parsed.
213 */
214 String parseJsString(String jsStringLiteral) throws ParseException {
215 valueMatcher.reset(jsStringLiteral);
216 if (!valueMatcher.matches()) {
217 throw new ParseException("Syntax error in JS String literal", true /* fatal */);
218 }
219 return valueMatcher.group(1) != null ? valueMatcher.group(1) : valueMatcher.group(2);
220 }
221
222 /**
223 * Parses a JavaScript array of string literals. (eg: ['a', 'b', "c"]).
224 * @param input A string containing a JavaScript array of string literals.
225 * @return A list of parsed string literals.
226 * @throws ParseException Thrown if there is a syntax error with the input.
227 */
228 List<String> parseJsStringArray(String input)
229 throws ParseException {
230 List<String> results = Lists.newArrayList();
231 int indexStart = input.indexOf('[');
232 int indexEnd = input.lastIndexOf(']');
233 if ((indexStart == -1) || (indexEnd == -1)) {
234 throw new ParseException("Syntax error when parsing JS array", true /* fatal */);
235 }
236 String innerValues = input.substring(indexStart + 1, indexEnd);
237
238 if (!innerValues.trim().isEmpty()) {
239 valueMatcher.reset(innerValues);
240 for (;;) {
241 // Parse the current string literal.
242 if (!valueMatcher.lookingAt()) {
243 throw new ParseException("Syntax error in JS String literal", true /* fatal */);
244 }
245 // Add it to the results.
246 results.add(valueMatcher.group(1) != null ?
247 valueMatcher.group(1) : valueMatcher.group(2));
248 if (valueMatcher.hitEnd()) {
249 break;
250 }
251 // Ensure there is a comma after the value.
252 if (innerValues.charAt(valueMatcher.end()) != ',') {
253 throw new ParseException("Missing comma in string array", true /* fatal */);
254 }
255 // Move to the next value.
256 valueMatcher.region(valueMatcher.end() + 1, valueMatcher.regionEnd());
257 }
258 }
259 return results;
260 }
261 }