Debian Codegraph @

CodeFormatter/PHPFormatterBuffer.cpp

raw
1 #include "PHPFormatterBuffer.h"
2
3 #include "PHPScannerTokens.h"
4
5 #include <wx/tokenzr.h>
6
7 struct PHPScannerCollectWhitespace {
8 phpLexerUserData* m_userdata;
9 bool m_oldState;
10
11 PHPScannerCollectWhitespace(PHPScanner_t scanner)
12 : m_userdata(NULL)
13 , m_oldState(false)
14 {
15 m_userdata = ::phpLexerGetUserData(scanner);
16 if(m_userdata) {
17 m_oldState = m_userdata->IsCollectingWhitespace();
18 m_userdata->SetCollectingWhitespace(true);
19 }
20 }
21
22 ~PHPScannerCollectWhitespace()
23 {
24 if(m_userdata) {
25 m_userdata->SetCollectingWhitespace(m_oldState);
26 }
27 }
28 };
29
30 PHPFormatterBuffer::PHPFormatterBuffer(const wxString& buffer, const PHPFormatterOptions& options)
31 : m_scanner(NULL)
32 , m_options(options)
33 , m_openTagWithEcho(false)
34 , m_forDepth(0)
35 , m_insideForStatement(false)
36 , m_insideHereDoc(false)
37 , m_depth(0)
38 , m_lastCommentLine(-1)
39 , m_parenDepth(0)
40 {
41 m_scanner = ::phpLexerNew(buffer, kPhpLexerOpt_ReturnComments | kPhpLexerOpt_ReturnAllNonPhp);
42 }
43
44 PHPFormatterBuffer::~PHPFormatterBuffer()
45 {
46 if(m_scanner) {
47 ::phpLexerDestroy(&m_scanner);
48 }
49 }
50
51 PHPFormatterBuffer& PHPFormatterBuffer::ProcessToken(const phpLexerToken& token)
52 {
53 if(::phpLexerIsPHPCode(m_scanner)) {
54
55 // Inside PHP tags
56 if(m_insideHereDoc) {
57 m_buffer << token.Text();
58 if(token.type == kPHP_T_END_HEREDOC) {
59 AppendEOL();
60 if(m_options.flags & kPFF_BreakAfterHeredoc) {
61 AppendEOL();
62 }
63 m_insideHereDoc = false;
64 }
65 } else if(token.type == kPHP_T_OPEN_TAG) {
66 m_openTagWithEcho = false;
67 m_buffer << token.Text();
68 AppendEOL();
69
70 } else if(token.type == kPHP_T_OPEN_TAG_WITH_ECHO) {
71 m_openTagWithEcho = true;
72 m_buffer << token.Text() << " ";
73
74 } else if(token.type == '{') {
75 HandleOpenCurlyBrace();
76
77 } else if(token.type == kPHP_T_VARIABLE) {
78 m_buffer << token.Text() << " ";
79
80 } else if(token.type == kPHP_T_FOREACH) {
81 m_buffer << token.Text() << " ";
82 if(m_options.flags & kPFF_BreakBeforeForeach) {
83 InsertSeparatorLine();
84 }
85 } else if(token.type == kPHP_T_ELSE || token.type == kPHP_T_ELSEIF) {
86 if(m_options.flags & kPFF_ElseOnSameLineAsClosingCurlyBrace && m_lastToken.type == '}') {
87 ReverseClearUntilFind("}");
88 m_buffer << " " << token.Text() << " ";
89 } else {
90 m_buffer << token.Text() << " ";
91 }
92
93 } else if(token.type == kPHP_T_WHILE) {
94 m_buffer << token.Text() << " ";
95 if(m_options.flags & kPFF_BreakBeforeWhile) {
96 InsertSeparatorLine();
97 }
98 } else if(token.type == kPHP_T_CLASS) {
99 if(m_options.flags & kPFF_BreakBeforeClass) {
100 InsertSeparatorLine();
101 }
102 m_buffer << token.Text() << " ";
103
104 } else if(token.type == kPHP_T_FUNCTION) {
105 // Found a function
106 m_buffer << token.Text() << " ";
107 if(m_lastCommentLine != token.lineNumber) {
108 // this function has no comment associated with it
109 if(m_options.flags & kPFF_BreakBeforeFunction) {
110 // But don't insert new line separator if this keyword
111 // was found in a statement like:
112 // use function A as B;
113 if(m_lastToken.type != kPHP_T_USE) {
114 // Look backward until we find the last EOL
115 // and insert another one...
116 InsertSeparatorLine();
117 }
118 }
119 }
120 } else if(token.type == kPHP_T_START_HEREDOC) {
121 RemoveLastSpace();
122 m_buffer << token.Text();
123 m_insideHereDoc = true;
124
125 } else if(token.type == kPHP_T_FOR) {
126 // for(;;) is a special case where
127 // we don't insert new line after semi-colon
128 m_insideForStatement = true;
129 m_buffer << token.Text();
130
131 } else if(token.type == '(' && m_insideForStatement) {
132 m_forDepth++;
133 m_buffer << token.Text();
134
135 } else if(token.type == ')' && m_insideForStatement) {
136 m_forDepth--;
137 if(m_forDepth == 0) {
138 m_insideForStatement = false;
139 }
140 m_buffer << token.Text();
141
142 } else if(token.type == '(' || token.type == '[') {
143 RemoveLastSpace();
144 m_buffer << token.Text();
145
146 if(m_options.flags & kPFF_VerticalArrays && token.type == '(' && m_lastToken.type == kPHP_T_ARRAY &&
147 m_parenDepth == 1) {
148 ProcessArray('(', ')');
149 }
150
151 } else if(token.type == ')') {
152 RemoveLastSpace();
153 m_buffer << token.Text();
154
155 } else if(token.type == ']') {
156 RemoveLastSpace();
157 m_buffer << token.Text() << " ";
158
159 } else if(token.type == ';') {
160 RemoveLastSpace();
161 m_buffer << token.Text();
162 AppendEOL();
163
164 } else if(token.type == '}') {
165 UnIndent();
166 m_buffer << token.Text();
167 AppendEOL(kDepthDec);
168
169 } else if(token.type == ',') {
170 RemoveLastSpace();
171 m_buffer << token.Text() << " ";
172
173 } else if(token.type == '.') {
174 m_buffer << token.Text() << " ";
175 if(m_options.flags & kPFF_BreakAfterStringConcatentation && (m_parenDepth == 1)) {
176 // inside a function call
177 wxString whitepace = GetIndentationToLast('(');
178 if(!whitepace.IsEmpty()) {
179 m_buffer << m_options.eol;
180 m_buffer << whitepace;
181 }
182 }
183 } else if(token.type == '&') {
184 // attach reference to the next token
185 m_buffer << token.Text();
186
187 } else if(token.type == kPHP_T_CXX_COMMENT) {
188 // C++ style comment ("//")
189 // AppendEOL();
190 m_buffer << token.Text();
191 AppendEOL();
192 m_lastCommentLine = token.lineNumber + 1;
193
194 } else if(token.type == kPHP_T_C_COMMENT) {
195 // Doxygen style comment: we first format it to match
196 // the current indentation + line ending before adding
197 // it to the current buffer
198 if(m_parenDepth == 0) {
199 AppendEOL();
200 m_buffer << FormatDoxyComment(token.Text());
201 AppendEOL();
202 m_lastCommentLine = token.endLineNumber + 1;
203 } else {
204 m_buffer << token.Text() << " ";
205 }
206
207 } else if(token.type == kPHP_T_OBJECT_OPERATOR || token.type == kPHP_T_PAAMAYIM_NEKUDOTAYIM) {
208 // -> operator or ::
209 RemoveLastSpace();
210 m_buffer << token.Text();
211
212 } else if(token.type == '!') {
213 // dont add extrace space after the NOT operator
214 m_buffer << token.Text();
215
216 } else if(token.type == kPHP_T_NS_SEPARATOR) {
217 if(m_lastToken.type == kPHP_T_IDENTIFIER) {
218 RemoveLastSpace();
219 }
220 m_buffer << token.Text();
221 } else {
222 // by default, add the token text and a space after it
223 m_buffer << token.Text() << " ";
224 }
225
226 m_lastToken = token;
227
228 } else {
229 if(token.type == kPHP_T_CLOSE_TAG && !m_openTagWithEcho) {
230 AppendEOL();
231 }
232 m_buffer << token.Text();
233 }
234 return *this;
235 }
236
237 void PHPFormatterBuffer::HandleOpenCurlyBrace()
238 {
239 RemoveLastSpace();
240 m_buffer << " {";
241 AppendEOL(kDepthInc);
242 }
243
244 void PHPFormatterBuffer::AppendEOL(eDepthCommand depth)
245 {
246 m_buffer << m_options.eol;
247 switch(depth) {
248 case kDepthDec:
249 --m_depth;
250 if(m_depth < 0)
251 m_depth = 0;
252 break;
253 case kDepthIncTemporarily:
254 case kDepthInc:
255 ++m_depth;
256 break;
257 default:
258 break;
259 }
260 m_buffer << GetIndent();
261 if(kDepthIncTemporarily == depth) {
262 --m_depth;
263 if(m_depth < 0)
264 m_depth = 0;
265 }
266 }
267
268 void PHPFormatterBuffer::UnIndent()
269 {
270
271 if(IsUseTabs() && !m_buffer.IsEmpty() && m_buffer.Last() == '\t') {
272 m_buffer.RemoveLast();
273
274 } else if(!IsUseTabs() && (m_buffer.length() >= m_options.indentSize) &&
275 m_buffer.Mid(m_buffer.length() - m_options.indentSize) == wxString(' ', m_options.indentSize)) {
276 m_buffer.RemoveLast(m_options.indentSize);
277 }
278 }
279
280 void PHPFormatterBuffer::RemoveLastSpace()
281 {
282 if(!m_buffer.IsEmpty() && m_buffer.Last() == ' ') {
283 m_buffer.RemoveLast();
284 }
285 }
286
287 wxString PHPFormatterBuffer::FormatDoxyComment(const wxString& comment)
288 {
289 if(m_parenDepth == 0) {
290 wxString formattedBlock;
291 wxString indent = GetIndent();
292 wxArrayString lines = ::wxStringTokenize(comment, "\n", wxTOKEN_STRTOK);
293 for(size_t i = 0; i < lines.GetCount(); ++i) {
294 lines.Item(i).Trim().Trim(false);
295 if(i) {
296 // preprend space + the indent string for every line except for the first line
297 lines.Item(i).Prepend(" ");
298 lines.Item(i).Prepend(indent);
299 }
300 formattedBlock << lines.Item(i) << m_options.eol;
301 }
302
303 formattedBlock.RemoveLast(m_options.eol.length());
304 return formattedBlock;
305 } else {
306 return comment;
307 }
308 }
309 wxString& PHPFormatterBuffer::GetIndent()
310 {
311 if(IsUseTabs()) {
312 m_indentString = wxString('\t', m_depth);
313 } else {
314 m_indentString = wxString(' ', m_depth * m_options.indentSize);
315 }
316 return m_indentString;
317 }
318
319 void PHPFormatterBuffer::InsertSeparatorLine()
320 {
321 size_t where = m_buffer.rfind(m_options.eol);
322 if(where != wxString::npos) {
323 m_buffer.insert(where, m_options.eol);
324 }
325 }
326
327 void PHPFormatterBuffer::ReverseClearUntilFind(const wxString& delim)
328 {
329 size_t where = m_buffer.rfind(delim);
330 if(where != wxString::npos) {
331 m_buffer = m_buffer.Mid(0, where + delim.length());
332 }
333 }
334
335 void PHPFormatterBuffer::format()
336 {
337 phpLexerToken token;
338 phpLexerToken::Vet_t sequence;
339 m_stack.push(sequence);
340 m_sequence = &m_stack.top();
341 while(NextToken(token)) {
342 phpLexerToken nextToken;
343 if(::phpLexerIsPHPCode(m_scanner)) {
344 ProcessToken(token);
345
346 //
347 // Special indentation cases
348 // Handle the following:
349 // for(..) <statement> -> for(..)
350 // <statement>
351 // if(..) <statement> -> if(..)
352 // <statement>
353 // etc.
354 // In addtion, we also handle here the following:
355 // if(something) {} else <statement> =>
356 // if(something) {
357 // } else
358 // <statement>
359 //
360
361 if(token.type == '(') {
362 // Create new stack
363 m_stack.push(phpLexerToken::Vet_t());
364 m_sequence = &m_stack.top();
365 }
366 if(token.type == ')') {
367 // switch back to the previous sequence
368 if(m_stack.size() >= 2) {
369 m_stack.pop();
370 m_sequence = &m_stack.top();
371 }
372
373 if(!m_sequence->empty()) {
374 phpLexerToken lastToken = m_sequence->at(m_sequence->size() - 1);
375 // The following tokens are usually followed by an open brace
376 if(lastToken.type == kPHP_T_IF || lastToken.type == kPHP_T_FOR || lastToken.type == kPHP_T_ELSEIF ||
377 lastToken.type == kPHP_T_FOREACH || lastToken.type == kPHP_T_WHILE) {
378 // Peek at the next char
379 if(PeekToken(nextToken)) {
380 if(nextToken.type != '{' && !nextToken.IsAnyComment()) {
381 // Increase the depth but only temporarily for the next statement
382 AppendEOL(kDepthIncTemporarily);
383 }
384 }
385 }
386 }
387 } else if(token.type == kPHP_T_ELSE) {
388 // Check for 'else <statement>' (without an open curly braces)
389 if(PeekToken(nextToken) && nextToken.type != '{' && nextToken.type != kPHP_T_IF) {
390 AppendEOL(kDepthIncTemporarily);
391 }
392
393 } else {
394 m_sequence->push_back(token);
395 }
396 } else {
397 ProcessToken(token);
398 }
399 }
400 }
401
402 bool PHPFormatterBuffer::NextToken(phpLexerToken& token)
403 {
404 if(m_tokensBuffer.empty()) {
405 bool res = ::phpLexerNext(m_scanner, token);
406 if(token.type == '(') {
407 ++m_parenDepth;
408 } else if(token.type == ')') {
409 --m_parenDepth;
410 }
411 return res;
412
413 } else {
414 token = *m_tokensBuffer.begin();
415 m_tokensBuffer.erase(m_tokensBuffer.begin());
416 return true;
417 }
418 }
419
420 bool PHPFormatterBuffer::PeekToken(phpLexerToken& token)
421 {
422 if(!::phpLexerNext(m_scanner, token))
423 return false;
424 m_tokensBuffer.push_back(token);
425 return true;
426 }
427
428 wxString PHPFormatterBuffer::GetIndentationToLast(wxChar ch)
429 {
430 wxString whitespace;
431 wxString workingBuffer = m_buffer;
432 if(ch != '\n') {
433 int startPos = m_buffer.Find(ch, true);
434 if(startPos != wxNOT_FOUND) {
435 workingBuffer = m_buffer.Mid(0, startPos + 1);
436 } else {
437 return GetIndent();
438 }
439 }
440 int where = workingBuffer.Find('\n', true);
441
442 // did we find our match on the previous line?
443 if(where != wxNOT_FOUND) {
444 // Build the whitespace
445 wxString buff = workingBuffer.Mid(where + 1);
446 while(!buff.IsEmpty()) {
447 if(buff.at(0) == '\t') {
448 // replace tab with 4 spaces
449 whitespace << wxString(' ', m_options.indentSize);
450 } else {
451 whitespace << " ";
452 }
453 buff.Remove(0, 1);
454 }
455 }
456
457 if(m_options.flags & kPFF_UseTabs) {
458 int tabsCount = (whitespace.length() / m_options.indentSize);
459 int extraSpaces = (whitespace.length() % m_options.indentSize);
460 whitespace.clear();
461 whitespace << wxString('\t', tabsCount);
462 whitespace << wxString(' ', extraSpaces);
463 }
464 return whitespace;
465 }
466
467 #define SQUEEZE_WHITESPACE() m_buffer.erase(m_buffer.find_last_not_of(" \t") + 1);
468
469 void PHPFormatterBuffer::ProcessArray(int openParen, int closingChar)
470 {
471 wxString whitespace = GetIndentationToLast('\n');
472 int depth = 1;
473 // we exit at depth 0
474 phpLexerToken token;
475 // PHPScannerCollectWhitespace whitespaceCollector(m_scanner);
476
477 while(NextToken(token)) {
478 if(::phpLexerIsPHPCode(m_scanner)) {
479 // inside PHP block
480 if(token.type == openParen) {
481 ++depth;
482 RemoveLastSpace();
483 m_buffer << token.Text();
484 } else if(token.type == closingChar) {
485 --depth;
486 RemoveLastSpace();
487 m_buffer << token.Text();
488 if(depth == 0)
489 break;
490
491 } else if(token.type == ',') {
492 // New line
493 RemoveLastSpace();
494 m_buffer << token.Text();
495 m_buffer << m_options.eol;
496 m_buffer << whitespace;
497
498 } else if(token.type == '(' || token.type == ')' || token.type == kPHP_T_OBJECT_OPERATOR ||
499 token.type == kPHP_T_PAAMAYIM_NEKUDOTAYIM || token.type == kPHP_T_NS_SEPARATOR ||
500 token.type == kPHP_T_VARIABLE || token.type == '[' || token.type == ']') {
501 RemoveLastSpace();
502 m_buffer << token.Text();
503
504 } else {
505 m_buffer << token.Text() << " ";
506 }
507
508 } else {
509 // Non PHP code, copy text as is
510 if(token.type == kPHP_T_CLOSE_TAG && !m_openTagWithEcho) {
511 AppendEOL();
512 }
513 m_buffer << token.Text();
514 }
515 }
516 }