Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 0fae880cebdea33f5c90d1cb4a9319945df7ec4a (plain) (blame)
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
/*******************************************************************************
 *  Copyright (c) 2005, 2015 IBM Corporation and others.
 *
 *  This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License 2.0
 *  which accompanies this distribution, and is available at
 *  https://www.eclipse.org/legal/epl-2.0/
 *
 *  SPDX-License-Identifier: EPL-2.0
 *
 *  Contributors:
 *     IBM Corporation - initial API and implementation
 *     Sergey Prigogin (Google)
 *     James Blackburn (Broadcom) - Bug 247838
 *     Andrew Gvozdev (Quoin Inc)
 *     Dmitry Kozlov (CodeSourcery) - Build error highlighting and navigation
 *******************************************************************************/
package org.eclipse.cdt.internal.autotools.core;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.eclipse.cdt.autotools.core.AutotoolsPlugin;
import org.eclipse.cdt.core.IErrorParser;
import org.eclipse.cdt.core.IErrorParser2;
import org.eclipse.cdt.core.IMarkerGenerator;
import org.eclipse.cdt.core.ProblemMarkerInfo;
import org.eclipse.cdt.internal.core.IErrorMarkeredOutputStream;
import org.eclipse.cdt.utils.EFSExtensionManager;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.URIUtil;

/**
 * The purpose of ErrorParserManager is to delegate the work of error parsing
 * build output to {@link IErrorParser}s, assist in finding {@link IResource}s, and
 * help create appropriate error/warning/info markers to be displayed
 * by the Problems view.
 *
 * @noextend This class is not intended to be subclassed by clients.
 */
@SuppressWarnings("restriction")
public class ErrorParserManager extends OutputStream {
	/**
	 * The list of error parsers stored in .project for 3.X projects
	 * as key/value pair with key="org.eclipse.cdt.core.errorOutputParser"
	 * @deprecated since CDT 4.0.
	 */

	/**
	 * Delimiter for error parsers presented in one string.
	 * @since 5.2
	 */
	public static final char ERROR_PARSER_DELIMITER = ';';

	private int nOpens;
	private int lineCounter = 0;

	private final IProject fProject;
	private final MarkerGenerator fMarkerGenerator;

	private Map<String, ErrorParser> fErrorParsers;
	private List<ProblemMarkerInfo> fErrors;

	private Vector<URI> fDirectoryStack;
	private final URI fBaseDirectoryURI;

	private String previousLine;
	private OutputStream outputStream;
	private final StringBuilder currentLine = new StringBuilder();

	/**
	 * Constructor.
	 *
	 * @param project - project being built.
	 * @param markerGenerator - marker generator able to create markers.
	 */
	public ErrorParserManager(IProject project, MarkerGenerator markerGenerator) {
		this(project, project.getLocationURI(), markerGenerator);
	}

	/**
	 * URI based constructor.
	 *
	 * @param project - project being built.
	 * @param baseDirectoryURI - absolute location URI of working directory of where the build is performed.
	 * @param markerGenerator - marker generator able to create markers.
	 * @since 2.0
	 */
	public ErrorParserManager(IProject project, URI baseDirectoryURI, MarkerGenerator markerGenerator) {
		fProject = project;
		fMarkerGenerator = markerGenerator;
		fDirectoryStack = new Vector<>();
		fErrors = new ArrayList<>();
		fErrorParsers = new LinkedHashMap<>();

		if (baseDirectoryURI != null)
			fBaseDirectoryURI = baseDirectoryURI;
		else
			fBaseDirectoryURI = project.getLocationURI();
	}

	public void addErrorParser(String id, ErrorParser parser) {
		fErrorParsers.put(id, parser);
	}

	/**
	 * @return current project.
	 */
	public IProject getProject() {
		return fProject;
	}

	/**
	 * @return the current URI location where the build is being performed
	 * @since 5.1
	 */
	public URI getWorkingDirectoryURI() {
		if (!fDirectoryStack.isEmpty())
			return fDirectoryStack.lastElement();

		// Fall back to the Project Location / Build directory
		return fBaseDirectoryURI;
	}

	/**
	 * {@link #pushDirectory} and {@link #popDirectory} are used to change working directory
	 * from where file name is searched (see {@link #findFileInWorkspace}).
	 * The intention is to handle make output of commands "pushd dir" and "popd".
	 *
	 * @param dir - another directory level to keep in stack -- corresponding to 'pushd'.
	 */
	public void pushDirectory(IPath dir) {
		if (dir != null) {
			URI uri;
			URI workingDirectoryURI = getWorkingDirectoryURI();
			if (!dir.isAbsolute())
				uri = URIUtil.append(workingDirectoryURI, dir.toString());
			else {
				uri = toURI(dir);
				if (uri == null) // Shouldn't happen; error logged
					return;
			}
			pushDirectoryURI(uri);
		}
	}

	/**
	 * {@link #pushDirectoryURI} and {@link #popDirectoryURI} are used to change working directory
	 * from where file name is searched (see {@link #findFileInWorkspace}).
	 * The intention is to handle make output of commands "pushd dir" and "popd".
	 *
	 * @param dir - another directory level to keep in stack -- corresponding to 'pushd'.
	 * @since 5.1
	 */
	public void pushDirectoryURI(URI dir) {
		if (dir != null) {
			if (dir.isAbsolute())
				fDirectoryStack.addElement(dir);
			else
				fDirectoryStack.addElement(URIUtil.makeAbsolute(dir, getWorkingDirectoryURI()));
		}
	}

	/**
	 * {@link #pushDirectoryURI(URI)} and {@link #popDirectoryURI()} are used to change working directory
	 * from where file name is searched (see {@link #findFileInWorkspace(IPath)}).
	 * The intention is to handle make output of commands "pushd" and "popd".
	 *
	 * @return previous build directory location corresponding 'popd' command.
	 * @since 5.1
	 */
	public URI popDirectoryURI() {
		int i = fDirectoryStack.size();
		if (i != 0) {
			URI dir = fDirectoryStack.lastElement();
			fDirectoryStack.removeElementAt(i - 1);
			return dir;
		}
		return fBaseDirectoryURI;
	}

	/**
	 * @return number of directories in the stack.
	 */
	public int getDirectoryLevel() {
		return fDirectoryStack.size();
	}

	/**
	 * Parses the input and tries to generate error or warning markers
	 */
	private void processLine(String line) {
		String lineTrimmed = line.trim();
		lineCounter++;

		ProblemMarkerInfo marker = null;

		for (ErrorParser parser : fErrorParsers.values()) {
			ErrorParser curr = parser;
			int types = IErrorParser2.NONE;
			if (curr instanceof IErrorParser2) {
				types = ((IErrorParser2) curr).getProcessLineBehaviour();
			}
			if ((types & IErrorParser2.KEEP_LONGLINES) == 0) {
				// long lines are not given to parsers, unless it wants it
				if (lineTrimmed.length() > 1000)
					continue;
			}
			// standard behavior (pre 5.1) is to trim the line
			String lineToParse = lineTrimmed;
			if ((types & IErrorParser2.KEEP_UNTRIMMED) != 0) {
				// untrimmed lines
				lineToParse = line;
			}

			boolean consume = false;
			// Protect against rough parsers who may accidentally
			// throw an exception on a line they can't handle.
			// It should not stop parsing of the rest of output.
			try {
				consume = curr.processLine(lineToParse, this);
			} catch (Exception e) {
				AutotoolsPlugin.log(e);
			} finally {
				if (fErrors.size() > 0) {
					if (marker == null)
						marker = fErrors.get(0);
					fErrors.clear();
				}
			}

			if (consume)
				break;
		}
		outputLine(line, marker);
	}

	/**
	 * Conditionally output line to outputStream. If stream
	 * supports error markers, use it, otherwise use conventional stream
	 */
	private void outputLine(String line, ProblemMarkerInfo marker) {
		String l = line + '\n';
		if (outputStream == null) {
			return;
		}
		try {
			if (marker != null) {
				if (outputStream instanceof IErrorMarkeredOutputStream) {
					IErrorMarkeredOutputStream mos = (IErrorMarkeredOutputStream) outputStream;
					mos.write(l, marker);
				}
			}
			byte[] b = l.getBytes();
			outputStream.write(b, 0, b.length);
		} catch (IOException e) {
			AutotoolsPlugin.log(e);
		}
	}

	/**
	 * @return counter counting processed lines of output
	 * @since 5.2
	 */
	public int getLineCounter() {
		return lineCounter;
	}

	/**
	 * Add marker to the list of error markers.
	 *
	 * @param file - resource to add the new marker.
	 * @param lineNumber - line number of the error.
	 * @param desc - description of the error.
	 * @param severity - severity of the error.
	 * @param varName - variable name.
	 */
	public void generateMarker(IResource file, int lineNumber, String desc, int severity, String varName,
			AutotoolsProblemMarkerInfo.Type type) {
		generateExternalMarker(file, lineNumber, desc, severity, varName, null, null, type);
	}

	/**
	 * Add marker to the list of error markers.
	 *
	 * @param file - resource to add the new marker.
	 * @param lineNumber - line number of the error.
	 * @param desc - description of the error.
	 * @param severity - severity of the error, one of
	 *        <br>{@link IMarkerGenerator#SEVERITY_INFO},
	 *        <br>{@link IMarkerGenerator#SEVERITY_WARNING},
	 *        <br>{@link IMarkerGenerator#SEVERITY_ERROR_RESOURCE},
	 *        <br>{@link IMarkerGenerator#SEVERITY_ERROR_BUILD}
	 * @param varName - variable name.
	 * @param externalPath - external path pointing to a file outside the workspace.
	 */
	public void generateExternalMarker(IResource file, int lineNumber, String desc, int severity, String varName,
			IPath externalPath, String libraryInfo, AutotoolsProblemMarkerInfo.Type type) {
		AutotoolsProblemMarkerInfo problemMarkerInfo = new AutotoolsProblemMarkerInfo(file, lineNumber, desc, severity,
				varName, externalPath, libraryInfo, type);
		addProblemMarker(problemMarkerInfo);
	}

	/**
	 * Add the given marker to the list of error markers.
	 *
	 * @param problemMarkerInfo - The marker to be added
	 */
	public void addProblemMarker(AutotoolsProblemMarkerInfo problemMarkerInfo) {
		fErrors.add(problemMarkerInfo.getMarker());
		fMarkerGenerator.addMarker(problemMarkerInfo);
	}

	/**
	 * Called by the error parsers.
	 * @return the previous line, save in the working buffer.
	 */
	public String getPreviousLine() {
		return previousLine == null ? "" : previousLine; //$NON-NLS-1$
	}

	/**
	 * Method setOutputStream.
	 * Note: you have to close this stream explicitly
	 * don't rely on ErrorParserManager.close().
	 * @param os - output stream
	 */
	public void setOutputStream(OutputStream os) {
		outputStream = os;
	}

	/**
	 * Method getOutputStream.
	 * Note: you have to close this stream explicitly
	 * don't rely on ErrorParserManager.close().
	 * @return OutputStream
	 */
	public OutputStream getOutputStream() {
		nOpens++;
		return this;
	}

	/**
	 * @see java.io.OutputStream#close()
	 * Note: don't rely on this method to close underlying OutputStream,
	 * close it explicitly
	 */
	@Override
	public synchronized void close() {
		if (nOpens > 0 && --nOpens == 0) {
			checkLine(true);
			fDirectoryStack.removeAllElements();
		}
	}

	/**
	 * @see java.io.OutputStream#flush()
	 */
	@Override
	public void flush() throws IOException {
		if (outputStream != null)
			outputStream.flush();
	}

	@Override
	public synchronized void write(int b) {
		currentLine.append((char) b);
		checkLine(false);
	}

	@Override
	public synchronized void write(byte[] b, int off, int len) {
		if (b == null) {
			throw new NullPointerException();
		} else if (off != 0 || (len < 0) || (len > b.length)) {
			throw new IndexOutOfBoundsException();
		} else if (len == 0) {
			return;
		}
		currentLine.append(new String(b, 0, len));
		checkLine(false);
	}

	// This method examines contents of currentLine buffer
	// if it contains whole line this line is checked by error
	// parsers (processLine method).
	// If flush is true rest of line is checked by error parsers.
	private void checkLine(boolean flush) {
		String buffer = currentLine.toString();
		int i = 0;
		while ((i = buffer.indexOf('\n')) != -1) {
			String line = buffer.substring(0, i);
			// get rid of any trailing '\r'
			if (line.endsWith("\r")) //$NON-NLS-1$
				line = line.substring(0, line.length() - 1);
			processLine(line);
			previousLine = line;
			buffer = buffer.substring(i + 1); // skip the \n and advance
		}
		currentLine.setLength(0);
		if (flush) {
			if (buffer.length() > 0) {
				processLine(buffer);
				previousLine = buffer;
			}
		} else {
			currentLine.append(buffer);
		}
	}

	/**
	 * Converts a location {@link IPath} to an {@link URI}. Contrary to
	 * {@link URIUtil#toURI(IPath)} this method does not assume that the path belongs
	 * to local file system.
	 *
	 * The returned URI uses the scheme and authority of the current working directory
	 * as returned by {@link #getWorkingDirectoryURI()}
	 *
	 * @param path - the path to convert to URI.
	 * @return URI
	 * @since 5.1
	 */
	private URI toURI(IPath path) {
		//		try {
		URI baseURI = getWorkingDirectoryURI();
		String uriString = path.toString();

		// On Windows "C:/folder/" -> "/C:/folder/"
		if (path.isAbsolute() && uriString.charAt(0) != IPath.SEPARATOR)
			uriString = IPath.SEPARATOR + uriString;

		return EFSExtensionManager.getDefault().createNewURIFromPath(baseURI, uriString);
	}

	/**
	 * @param ids - array of error parser IDs
	 * @return error parser IDs delimited with error parser delimiter ";"
	 * @since 5.2
	 */
	public static String toDelimitedString(String[] ids) {
		String result = ""; //$NON-NLS-1$
		for (String id : ids) {
			if (result.length() == 0) {
				result = id;
			} else {
				result += ERROR_PARSER_DELIMITER + id;
			}
		}
		return result;
	}
}

Back to the top