Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 30d936d5669d16c534c6fca5f035b18059450e24 (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
/*******************************************************************************
 * Copyright (c) 2000, 2016 QNX Software Systems and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     QNX Software Systems - Initial API and implementation
 *     Sergey Prigogin (Google)
 *     Anton Leherbauer (Wind River Systems)
 *     IBM Corporation
 *******************************************************************************/
package org.eclipse.cdt.internal.formatter;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTFileLocation;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTNodeSelector;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroExpansion;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorStatement;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.gnu.cpp.GPPLanguage;
import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterOptions;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.core.parser.FileContent;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.IncludeFileContentProvider;
import org.eclipse.cdt.core.parser.ParserUtil;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.cdt.internal.core.dom.parser.ASTQueries;
import org.eclipse.cdt.internal.core.util.TextUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.text.edits.TextEdit;

public class CCodeFormatter extends CodeFormatter {
	private DefaultCodeFormatterOptions preferences;
	private Map<String, ?> options;

	public CCodeFormatter() {
		this(DefaultCodeFormatterOptions.getDefaultSettings());
	}

	public CCodeFormatter(DefaultCodeFormatterOptions preferences) {
		this(preferences, null);
	}

	public CCodeFormatter(DefaultCodeFormatterOptions defaultCodeFormatterOptions, Map<String, ?> options) {
		setOptions(options);
		if (defaultCodeFormatterOptions != null) {
			preferences.set(defaultCodeFormatterOptions.getMap());
		}
	}

	public CCodeFormatter(Map<String, ?> options) {
		this(null, options);
	}

	@Override
	public String createIndentationString(final int indentationLevel) {
		if (indentationLevel < 0) {
			throw new IllegalArgumentException();
		}

		int tabs= 0;
		int spaces= 0;
		switch (preferences.tab_char) {
		case DefaultCodeFormatterOptions.SPACE:
			spaces= indentationLevel * preferences.tab_size;
			break;

		case DefaultCodeFormatterOptions.TAB:
			tabs= indentationLevel;
			break;

		case DefaultCodeFormatterOptions.MIXED:
			int tabSize= preferences.tab_size;
			int spaceEquivalents= indentationLevel * preferences.indentation_size;
			tabs= spaceEquivalents / tabSize;
			spaces= spaceEquivalents % tabSize;
			break;

		default:
			return EMPTY_STRING;
		}

		if (tabs == 0 && spaces == 0) {
			return EMPTY_STRING;
		}
		StringBuilder buffer= new StringBuilder(tabs + spaces);
		for (int i= 0; i < tabs; i++) {
			buffer.append('\t');
		}
		for (int i= 0; i < spaces; i++) {
			buffer.append(' ');
		}
		return buffer.toString();
	}

	@Override
	public void setOptions(Map<String, ?> options) {
		if (options != null) {
			this.options= options;
			Map<String, String> formatterPrefs= new HashMap<String, String>(options.size());
			for (String key : options.keySet()) {
				Object value= options.get(key);
				if (value instanceof String) {
					formatterPrefs.put(key, (String) value);
				}
			}
			preferences= new DefaultCodeFormatterOptions(formatterPrefs);
		} else {
			this.options= CCorePlugin.getOptions();
			preferences= DefaultCodeFormatterOptions.getDefaultSettings();
		}
	}

	@Override
	public TextEdit format(int kind, String source, int offset, int length, int indentationLevel,
			String lineSeparator) {
		preferences.initial_indentation_level = indentationLevel;
		return format(kind, source, new IRegion[] { new Region(offset, length) }, lineSeparator)[0];
	}

	@Override
	public TextEdit[] format(int kind, String source, IRegion[] regions, String lineSeparator) {
		TextEdit[] edits= new TextEdit[regions.length];
		if (lineSeparator != null) {
			preferences.line_separator = lineSeparator;
		} else {
			preferences.line_separator = System.getProperty("line.separator"); //$NON-NLS-1$
		}

		ITranslationUnit tu = getTranslationUnit(source);
		if (tu != null) {
			IIndex index;
			try {
				index = CCorePlugin.getIndexManager().getIndex(tu.getCProject());
				index.acquireReadLock();
			} catch (CoreException e) {
				throw new AbortFormatting(e);
			} catch (InterruptedException e) {
				return null;
			}
			IASTTranslationUnit ast;
			try {
				try {
					ast= tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS);
				} catch (CoreException e) {
					throw new AbortFormatting(e);
				}
				formatRegions(source, regions, edits, ast);
			} finally {
				index.releaseReadLock();
			}
		} else {
			IncludeFileContentProvider contentProvider = IncludeFileContentProvider.getSavedFilesProvider();
			IScannerInfo scanInfo = new ScannerInfo();
			FileContent content = FileContent.create("<text>", source.toCharArray()); //$NON-NLS-1$
			
			ILanguage language= (ILanguage) options.get(DefaultCodeFormatterConstants.FORMATTER_LANGUAGE);
			if (language == null) {
				language= GPPLanguage.getDefault();
			}
			IASTTranslationUnit ast;
			try {
				ast= language.getASTTranslationUnit(content, scanInfo, contentProvider, null, 0,
						ParserUtil.getParserLogService());
				formatRegions(source, regions, edits, ast);
			} catch (CoreException e) {
				throw new AbortFormatting(e);
			}
		}
		return edits;
	}

	private void formatRegions(String source, IRegion[] regions, TextEdit[] edits,
			IASTTranslationUnit ast) {
		for (int i = 0; i < regions.length; i++) {
			IRegion region = regions[i];
			if (shouldFormatWholeStatements()) {
				// An empty region is replaced by the region containing the line corresponding to
				// the offset and all statements overlapping with that line.
				region = getLineOrStatementRegion(source, region, ast);
			}
			CodeFormatterVisitor codeFormatter =
					new CodeFormatterVisitor(preferences, region.getOffset(), region.getLength());
			edits[i] = codeFormatter.format(source, ast);
			IStatus status= codeFormatter.getStatus();
			if (!status.isOK()) {
				CCorePlugin.log(status);
			}
		}
	}

	private boolean shouldFormatWholeStatements() {
		Object obj = options.get(DefaultCodeFormatterConstants.FORMATTER_STATEMENT_SCOPE);
		return obj instanceof Boolean && ((Boolean) obj).booleanValue();
	}

	/**
	 * Returns the smallest region containing the lines overlapping with the given region and all
	 * statements overlapping with those lines.
	 */
	private IRegion getLineOrStatementRegion(String source, IRegion region, IASTTranslationUnit ast) {
		int start = TextUtil.getLineStart(source, region.getOffset());
		int end = TextUtil.skipToNextLine(source, region.getOffset() + region.getLength());
		IASTNode node = findOverlappingPreprocessorStatement(start, end, ast);
		if (node != null) {
			IASTFileLocation location = node.getFileLocation();
			int nodeOffset = location.getNodeOffset();
			if (nodeOffset < start)
				start = nodeOffset;
			int nodeEnd = nodeOffset + location.getNodeLength();
			if (nodeEnd > end)
				end = nodeEnd;
			return new Region(start, end - start);
		}
		IASTNodeSelector nodeSelector = ast.getNodeSelector(null);
		for (int pos = start; pos < end;) {
			node = nodeSelector.findFirstContainedNode(pos, end - pos);
			if (node != null) {
				IASTNode containedNode = node;
				node = ASTQueries.findAncestorWithType(containedNode, IASTStatement.class);
				if (node == null)
					node = ASTQueries.findAncestorWithType(containedNode, IASTDeclaration.class);
				if (node == null)
					node = ASTQueries.findAncestorWithType(containedNode, IASTPreprocessorMacroExpansion.class);
			}
			if (node == null)
				break;
			IASTFileLocation location = node.getFileLocation();
			int nodeOffset = location.getNodeOffset();
			if (nodeOffset < start)
				start = nodeOffset;
			int nodeEnd = nodeOffset + location.getNodeLength();
			if (nodeEnd > end)
				end = nodeEnd;
			pos = nodeEnd;
		}
		
		return new Region(start, end - start);
	}

	private IASTNode findOverlappingPreprocessorStatement(int start, int end, IASTTranslationUnit ast) {
		IASTPreprocessorStatement[] statements = ast.getAllPreprocessorStatements();
		int low = 0;
		int high = statements.length;
		while (low < high) {
			int mid = (low + high) >>> 1;
			IASTPreprocessorStatement statement = statements[mid];
			IASTFileLocation location = statement.getFileLocation();
			if (location == null) {
				low = mid + 1;
			} else {
				int statementOffset = location.getNodeOffset();
				if (statementOffset >= end) {
					high = mid;
				} else if (statementOffset + location.getNodeLength() <= start) {
					low = mid + 1;
				} else {
					return statement;
				}
			}
		}
		return null;
	}

	private ITranslationUnit getTranslationUnit(String source) {
		ITranslationUnit tu= (ITranslationUnit) options.get(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT);
		if (tu == null) {
			IFile file= (IFile) options.get(DefaultCodeFormatterConstants.FORMATTER_CURRENT_FILE);
			if (file != null) {
				tu= (ITranslationUnit) CoreModel.getDefault().create(file);
			}
		}
		if (tu != null && source != null) {
			try {
				// Create a private working copy and set it contents to source.
				if (tu.isWorkingCopy())
					tu = ((IWorkingCopy) tu).getOriginalElement();
				tu = tu.getWorkingCopy();
				tu.getBuffer().setContents(source);
			} catch (CModelException e) {
				throw new AbortFormatting(e);
			}
		}
		return tu;
	}
}

Back to the top