forked from qgis/QGIS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathastyle_main.cpp
1938 lines (1750 loc) · 56 KB
/
astyle_main.cpp
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* astyle_main.cpp
*
* This file is a part of "Artistic Style" - an indentation and
* reformatting tool for C, C++, C# and Java source files.
* http://astyle.sourceforge.net
*
* The "Artistic Style" project, including all files needed to
* compile it, is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this project; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
#include "astyle.h"
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <ctime>
// includes for recursive getFileNames() function
#ifdef _WIN32
#include <windows.h>
#else
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#ifdef __VMS
#include <unixlib.h>
#include <rms.h>
#include <ssdef.h>
#include <stsdef.h>
#include <lib$routines.h>
#include <starlet.h>
#endif /* __VMS */
#endif
#ifdef ASTYLE_JNI
#include <jni.h>
// ASTYLE_LIB must be defined for ASTYLE_JNI
#ifndef ASTYLE_LIB
#define ASTYLE_LIB
#endif
// Java variables
JNIEnv* g_env;
jobject g_obj;
jmethodID g_mid;
#endif
#ifndef ASTYLE_LIB // for console build only
#if defined(_MSC_VER) || defined(__DMC__)
#include <sys/utime.h>
#include <sys/stat.h>
#else
#include <utime.h>
#include <sys/stat.h>
#endif // end compiler checks
#endif // end ASTYLE_LIB
// for G++ implementation of string.compare:
#if defined(__GNUC__) && __GNUC__ < 3
#error - Use GNU C compiler release 3 or higher
#endif
// for namespace problem in version 5.0
#if defined(_MSC_VER) && _MSC_VER < 1200 // check for V6.0
#error - Use Microsoft compiler version 6 or higher
#endif
#define IS_OPTION(arg,op) ((arg).compare(op)==0)
#define IS_OPTIONS(arg,a,b) (IS_OPTION((arg),(a)) || IS_OPTION((arg),(b)))
#define GET_PARAM(arg,op) ((arg).substr(strlen(op)))
#define GET_PARAMS(arg,a,b) (isParamOption((arg),(a)) ? GET_PARAM((arg),(a)) : GET_PARAM((arg),(b)))
// astyle declarations
void error(const char *why, const char* what);
void getFileNames(const string &directory, const string &wildcard, vector<string> &filename);
void importOptions(istream &in, vector<string> &optionsVector);
void isOptionError(const string &arg, const string &errorInfo);
bool isParamOption(const string &arg, const char *option);
bool isParamOption(const string &arg, const char *option1, const char *option2);
bool parseOption(astyle::ASFormatter &formatter, const string &arg, const string &errorInfo);
template<typename ITER>
bool parseOptions(astyle::ASFormatter &formatter, const ITER &optionsBegin,
const ITER &optionsEnd, const string &errorInfo);
// astyle console declarations
bool formatFile(const string &fileName, astyle::ASFormatter &formatter);
string getCurrentDirectory(const string &fileName);
bool isPathExclued(const string &subPath);
void preserveFileDate(const char *oldFileName, const char *newFileName);
void printHelp();
void standardizePath(string &path, bool removeBeginningSeparator=false);
bool stringEndsWith(const string &str, const string &suffix);
int wildcmp(const char *wild, const char *data);
// astyle ASTYLE_LIB declarations
typedef void (STDCALL *fpError)(int, char*); // pointer to callback error handler
typedef char* (STDCALL *fpAlloc)(unsigned long); // pointer to callback memory allocation
extern "C" EXPORT char* STDCALL AStyleMain(const char*, const char*, fpError, fpAlloc);
extern "C" EXPORT const char* STDCALL AStyleGetVersion (void);
// astyle ASTYLE_JNI declarations
#ifdef ASTYLE_JNI
void STDCALL javaErrorHandler(int errorNumber, char* errorMessage);
char* STDCALL javaMemoryAlloc(unsigned long memoryNeeded);
// the following function names are constructed from method names in the calling java program
extern "C" EXPORT
jstring STDCALL Java_AStyleInterface_GetVersion(JNIEnv* env, jclass);
extern "C" EXPORT
jstring STDCALL Java_AStyleInterface_AStyleMain
(JNIEnv* env, jobject obj, jstring textInJava, jstring optionsJava);
#endif
using namespace astyle;
const char* _version = "1.22";
#ifdef _WIN32
char g_fileSeparator = '\\'; // file separator
bool g_isCaseSensitive = false;
#else
char g_fileSeparator = '/'; // file separator
bool g_isCaseSensitive = true;
#endif
#ifdef ASTYLE_LIB
// GUI variables
stringstream *_err = NULL;
#else
// console variables
ostream *_err = &cerr;
bool g_isRecursive = false;
bool g_hasWildcard = false;
bool g_noBackup = false;
bool g_preserveDate = false;
bool g_isVerbose = false;
bool g_isQuiet = false;
bool g_optionsFileRequired = false;
string g_origSuffix = ".orig";
vector<string> g_excludeVector; // exclude from wildcard hits
vector<bool> g_excludeHitsVector; // exclude flags for eror reporting
size_t g_mainDirectoryLength; // main directory name can be excluded for displays
// stringstream g_msg; // info messages are not printed until a file is read
int _CRT_glob = 0; // turn off MinGW automatic file globbing
#ifdef __VMS
string g_tempSuffix = "_tmp";
#else
string g_tempSuffix = ".tmp";
#endif /* __VMS */
#endif
bool g_modeManuallySet = false;
// typename will be istringstream for GUI and istream otherwise
template<typename T>
class ASStreamIterator :
public ASSourceIterator
{
public:
// function declarations
ASStreamIterator(T *in);
virtual ~ASStreamIterator();
string nextLine();
string peekNextLine();
void peekReset();
void saveLastInputLine();
// inline functions
bool compareToInputBuffer(const string &nextLine) const { return nextLine == prevBuffer; }
const char* getOutputEOL() const { return outputEOL; }
bool hasMoreLines() const { return !inStream->eof(); }
private:
T * inStream; // pointer to the input stream
string buffer; // current input line
string prevBuffer; // previous input line
int eolWindows; // number of Windows line endings (CRLF)
int eolLinux; // number of Linux line endings (LF)
int eolMacOld; // number of old Mac line endings (CR)
char outputEOL[4]; // output end of line char
int peekStart; // starting position for peekNextLine()
};
template<typename T>
ASStreamIterator<T>::ASStreamIterator(T *in)
{
inStream = in;
buffer.reserve(200);
eolWindows = eolLinux = eolMacOld = 0;
peekStart = 0;
}
template<typename T>
ASStreamIterator<T>::~ASStreamIterator()
{
}
// save the last input line after input has reached EOF
template<typename T>
void ASStreamIterator<T>::saveLastInputLine()
{
assert(inStream->eof());
prevBuffer = buffer;
}
/**
* read the input stream, delete any end of line characters,
* and build a string that contains the input line.
*
* @return string containing the next input line minus any end of line characters
*/
template<typename T>
string ASStreamIterator<T>::nextLine()
{
// verify that the current position is correct
assert (peekStart == 0);
// save the previous record for output comparison
prevBuffer = buffer;
// read the next record
buffer.clear();
char ch;
inStream->get(ch);
while (!inStream->eof() && ch != '\n' && ch != '\r')
{
buffer.append(1, ch);
inStream->get(ch);
}
if (inStream->eof())
{
return buffer;
}
int peekCh = inStream->peek();
// find input end-of-line characters
if (!inStream->eof())
{
if (ch == '\r') // CR+LF is windows otherwise Mac OS 9
{
if (peekCh == '\n')
{
inStream->get();
eolWindows++;
}
else
eolMacOld++;
}
else // LF is Linux, allow for improbable LF/CR
{
if (peekCh == '\r')
{
inStream->get();
eolWindows++;
}
else
eolLinux++;
}
}
else
{
inStream->clear();
}
// set output end of line characters
if (eolWindows >= eolLinux)
if (eolWindows >= eolMacOld)
strcpy(outputEOL, "\r\n"); // Windows (CR+LF)
else
strcpy(outputEOL, "\r"); // MacOld (CR)
else
if (eolLinux >= eolMacOld)
strcpy(outputEOL, "\n"); // Linux (LF)
else
strcpy(outputEOL, "\r"); // MacOld (CR)
return buffer;
}
// save the current position and get the next line
// this can be called for multiple reads
// when finished peeking you MUST call peekReset()
template<typename T>
string ASStreamIterator<T>::peekNextLine()
{
assert (hasMoreLines());
string nextLine;
char ch;
if (peekStart == 0)
peekStart = inStream->tellg();
// read the next record
inStream->get(ch);
while (!inStream->eof() && ch != '\n' && ch != '\r')
{
nextLine.append(1, ch);
inStream->get(ch);
}
if (inStream->eof())
{
return nextLine;
}
int peekCh = inStream->peek();
// remove end-of-line characters
if (!inStream->eof())
{
if (peekCh == '\n' || peekCh == '\r')
inStream->get();
}
return nextLine;
}
// reset current position and EOF for peekNextLine()
template<typename T>
void ASStreamIterator<T>::peekReset()
{
assert(peekStart != 0);
inStream->clear();
inStream->seekg(peekStart);
peekStart = 0;
}
/**
* parse the options vector
* ITER can be either a fileOptionsVector (options file) or an optionsVector (command line)
*
* @return true if no errors, false if errors
*/
template<typename ITER>
bool parseOptions(ASFormatter &formatter,
const ITER &optionsBegin,
const ITER &optionsEnd,
const string &errorInfo)
{
ITER option;
bool ok = true;
string arg, subArg;
for (option = optionsBegin; option != optionsEnd; ++option)
{
arg = *option;
if (arg.compare(0, 2, "--") == 0)
ok &= parseOption(formatter, arg.substr(2), errorInfo);
else if (arg[0] == '-')
{
size_t i;
for (i = 1; i < arg.length(); ++i)
{
if (isalpha(arg[i]) && i > 1)
{
ok &= parseOption(formatter, subArg, errorInfo);
subArg = "";
}
subArg.append(1, arg[i]);
}
ok &= parseOption(formatter, subArg, errorInfo);
subArg = "";
}
else
{
ok &= parseOption(formatter, arg, errorInfo);
subArg = "";
}
}
return ok;
}
void importOptions(istream &in, vector<string> &optionsVector)
{
char ch;
string currentToken;
while (in)
{
currentToken = "";
do
{
in.get(ch);
if (in.eof())
break;
// treat '#' as line comments
if (ch == '#')
while (in)
{
in.get(ch);
if (ch == '\n')
break;
}
// break options on spaces, tabs or new-lines
if (in.eof() || ch == ' ' || ch == '\t' || ch == '\n')
break;
else
currentToken.append(1, ch);
}
while (in);
if (currentToken.length() != 0)
optionsVector.push_back(currentToken);
}
}
bool isParamOption(const string &arg, const char *option)
{
bool retVal = arg.compare(0, strlen(option), option) == 0;
// if comparing for short option, 2nd char of arg must be numeric
if (retVal && strlen(option) == 1 && arg.length() > 1)
if (!isdigit(arg[1]))
retVal = false;
return retVal;
}
void isOptionError(const string &arg, const string &errorInfo)
{
#ifdef ASTYLE_LIB
if (_err->str().length() == 0)
{
(*_err) << errorInfo << endl; // need main error message
(*_err) << arg; // output the option in error
}
else
(*_err) << endl << arg; // put endl after previous option
#else
if (errorInfo.length() > 0) // to avoid a compiler warning
(*_err) << "Error in param: " << arg << endl;
#endif
}
bool isParamOption(const string &arg, const char *option1, const char *option2)
{
return isParamOption(arg, option1) || isParamOption(arg, option2);
}
bool parseOption(ASFormatter &formatter, const string &arg, const string &errorInfo)
{
if ( IS_OPTION(arg, "style=ansi") )
{
formatter.setSpaceIndentation(4);
formatter.setBracketFormatMode(BREAK_MODE);
formatter.setBracketIndent(false);
formatter.setClassIndent(false);
formatter.setSwitchIndent(false);
formatter.setNamespaceIndent(false);
}
else if ( IS_OPTION(arg, "style=gnu") )
{
formatter.setSpaceIndentation(2);
formatter.setBracketFormatMode(BREAK_MODE);
formatter.setBlockIndent(true);
formatter.setClassIndent(false);
formatter.setSwitchIndent(false);
formatter.setNamespaceIndent(false);
}
else if ( IS_OPTION(arg, "style=java") )
{
// formatter.setJavaStyle();
// g_modeManuallySet = true;
formatter.setSpaceIndentation(4);
formatter.setBracketFormatMode(ATTACH_MODE);
formatter.setBracketIndent(false);
formatter.setSwitchIndent(false);
}
else if ( IS_OPTION(arg, "style=kr") )
{
//manuallySetCStyle(formatter);
formatter.setSpaceIndentation(4);
formatter.setBracketFormatMode(ATTACH_MODE);
formatter.setBracketIndent(false);
formatter.setClassIndent(false);
formatter.setSwitchIndent(false);
formatter.setNamespaceIndent(false);
}
else if ( IS_OPTION(arg, "style=linux") )
{
formatter.setSpaceIndentation(8);
formatter.setBracketFormatMode(BDAC_MODE);
formatter.setBracketIndent(false);
formatter.setClassIndent(false);
formatter.setSwitchIndent(false);
formatter.setNamespaceIndent(false);
}
// must check for mode=cs before mode=c !!!
else if ( IS_OPTION(arg, "mode=cs") )
{
formatter.setSharpStyle();
g_modeManuallySet = true;
}
else if ( IS_OPTION(arg, "mode=c") )
{
formatter.setCStyle();
g_modeManuallySet = true;
}
else if ( IS_OPTION(arg, "mode=java") )
{
formatter.setJavaStyle();
g_modeManuallySet = true;
}
else if ( isParamOption(arg, "t", "indent=tab=") )
{
int spaceNum = 4;
string spaceNumParam = GET_PARAMS(arg, "t", "indent=tab=");
if (spaceNumParam.length() > 0)
spaceNum = atoi(spaceNumParam.c_str());
if (spaceNum < 1 || spaceNum > 20)
isOptionError(arg, errorInfo);
else
formatter.setTabIndentation(spaceNum, false);
}
else if ( isParamOption(arg, "T", "force-indent=tab=") )
{
int spaceNum = 4;
string spaceNumParam = GET_PARAMS(arg, "T", "force-indent=tab=");
if (spaceNumParam.length() > 0)
spaceNum = atoi(spaceNumParam.c_str());
if (spaceNum < 1 || spaceNum > 20)
isOptionError(arg, errorInfo);
else
formatter.setTabIndentation(spaceNum, true);
}
else if ( IS_OPTION(arg, "indent=tab") )
{
formatter.setTabIndentation(4);
}
else if ( isParamOption(arg, "s", "indent=spaces=") )
{
int spaceNum = 4;
string spaceNumParam = GET_PARAMS(arg, "s", "indent=spaces=");
if (spaceNumParam.length() > 0)
spaceNum = atoi(spaceNumParam.c_str());
if (spaceNum < 1 || spaceNum > 20)
isOptionError(arg, errorInfo);
else
formatter.setSpaceIndentation(spaceNum);
}
else if ( IS_OPTION(arg, "indent=spaces") )
{
formatter.setSpaceIndentation(4);
}
else if ( isParamOption(arg, "m", "min-conditional-indent=") )
{
int minIndent = 8;
string minIndentParam = GET_PARAMS(arg, "m", "min-conditional-indent=");
if (minIndentParam.length() > 0)
minIndent = atoi(minIndentParam.c_str());
if (minIndent > 40)
isOptionError(arg, errorInfo);
else
formatter.setMinConditionalIndentLength(minIndent);
}
else if ( isParamOption(arg, "M", "max-instatement-indent=") )
{
int maxIndent = 40;
string maxIndentParam = GET_PARAMS(arg, "M", "max-instatement-indent=");
if (maxIndentParam.length() > 0)
maxIndent = atoi(maxIndentParam.c_str());
if (maxIndent > 80)
isOptionError(arg, errorInfo);
else
formatter.setMaxInStatementIndentLength(maxIndent);
}
else if ( IS_OPTIONS(arg, "B", "indent-brackets") )
{
formatter.setBracketIndent(true);
}
else if ( IS_OPTIONS(arg, "G", "indent-blocks") )
{
formatter.setBlockIndent(true);
}
else if ( IS_OPTIONS(arg, "N", "indent-namespaces") )
{
formatter.setNamespaceIndent(true);
}
else if ( IS_OPTIONS(arg, "C", "indent-classes") )
{
formatter.setClassIndent(true);
}
else if ( IS_OPTIONS(arg, "S", "indent-switches") )
{
formatter.setSwitchIndent(true);
}
else if ( IS_OPTIONS(arg, "K", "indent-cases") )
{
formatter.setCaseIndent(true);
}
else if ( IS_OPTIONS(arg, "L", "indent-labels") )
{
formatter.setLabelIndent(true);
}
else if ( IS_OPTIONS(arg, "y", "brackets=break-closing") )
{
formatter.setBreakClosingHeaderBracketsMode(true);
}
else if ( IS_OPTIONS(arg, "b", "brackets=break") )
{
formatter.setBracketFormatMode(BREAK_MODE);
}
else if ( IS_OPTIONS(arg, "a", "brackets=attach") )
{
formatter.setBracketFormatMode(ATTACH_MODE);
}
else if ( IS_OPTIONS(arg, "l", "brackets=linux") )
{
formatter.setBracketFormatMode(BDAC_MODE);
}
else if ( IS_OPTIONS(arg, "O", "one-line=keep-blocks") )
{
formatter.setBreakOneLineBlocksMode(false);
}
else if ( IS_OPTIONS(arg, "o", "one-line=keep-statements") )
{
formatter.setSingleStatementsMode(false);
}
else if ( IS_OPTIONS(arg, "P", "pad=paren") )
{
formatter.setParensOutsidePaddingMode(true);
formatter.setParensInsidePaddingMode(true);
}
else if ( IS_OPTIONS(arg, "d", "pad=paren-out") )
{
formatter.setParensOutsidePaddingMode(true);
}
else if ( IS_OPTIONS(arg, "D", "pad=paren-in") )
{
formatter.setParensInsidePaddingMode(true);
}
else if ( IS_OPTIONS(arg, "U", "unpad=paren") )
{
formatter.setParensUnPaddingMode(true);
}
else if ( IS_OPTIONS(arg, "p", "pad=oper") )
{
formatter.setOperatorPaddingMode(true);
}
else if ( IS_OPTIONS(arg, "E", "fill-empty-lines") )
{
formatter.setEmptyLineFill(true);
}
else if ( IS_OPTIONS(arg, "w", "indent-preprocessor") )
{
formatter.setPreprocessorIndent(true);
}
else if ( IS_OPTIONS(arg, "c", "convert-tabs") )
{
formatter.setTabSpaceConversionMode(true);
}
else if ( IS_OPTIONS(arg, "F", "break-blocks=all") )
{
formatter.setBreakBlocksMode(true);
formatter.setBreakClosingHeaderBlocksMode(true);
}
else if ( IS_OPTIONS(arg, "f", "break-blocks") )
{
formatter.setBreakBlocksMode(true);
}
else if ( IS_OPTIONS(arg, "e", "break-elseifs") )
{
formatter.setBreakElseIfsMode(true);
}
#ifdef ASTYLE_LIB
// End of options used by GUI
else
isOptionError(arg, errorInfo);
#else
// Options used by only console
else if ( IS_OPTIONS(arg, "n", "suffix=none") )
{
g_noBackup = true;
}
else if ( isParamOption(arg, "suffix=") )
{
string suffixParam = GET_PARAM(arg, "suffix=");
if (suffixParam.length() > 0)
{
g_origSuffix = suffixParam;
}
}
else if ( isParamOption(arg, "exclude=") )
{
string suffixParam = GET_PARAM(arg, "exclude=");
if (suffixParam.length() > 0)
{
g_excludeVector.push_back(suffixParam);
g_excludeHitsVector.push_back(false);
}
}
else if ( IS_OPTIONS(arg, "r", "R") || IS_OPTION(arg, "recursive") )
{
g_isRecursive = true;
}
else if ( IS_OPTIONS(arg, "Z", "preserve-date") )
{
g_preserveDate = true;
}
else if ( IS_OPTIONS(arg, "v", "verbose") )
{
if (g_isQuiet)
error("Cannot use both verbose and quiet", "");
g_isVerbose = true;
}
else if ( IS_OPTIONS(arg, "q", "quiet") )
{
if (g_isVerbose)
error("Cannot use both verbose and quiet", "");
g_isQuiet = true;
}
else if ( IS_OPTIONS(arg, "X", "errors-to-stdout") )
{
_err = &cout;
}
else
{
(*_err) << errorInfo << arg << endl;
return false; // invalid option
}
#endif
// End of parseOption function
return true; //o.k.
}
#ifdef ASTYLE_JNI
// ************************* JNI functions *****************************************************
// called by a java program to get the version number
// the function name is constructed from method names in the calling java program
extern "C" EXPORT
jstring STDCALL Java_AStyleInterface_GetVersion(JNIEnv* env, jclass)
{
return env->NewStringUTF(_version);
}
// called by a java program to format the source code
// the function name is constructed from method names in the calling java program
extern "C" EXPORT
jstring STDCALL Java_AStyleInterface_AStyleMain(JNIEnv* env,
jobject obj,
jstring textInJava,
jstring optionsJava)
{
g_env = env; // make object available globally
g_obj = obj; // make object available globally
jstring textErr = env->NewStringUTF(""); // zero length text returned if an error occurs
// get the method ID
jclass cls = env->GetObjectClass(obj);
g_mid = env->GetMethodID(cls, "ErrorHandler","(ILjava/lang/String;)V");
if (g_mid == 0)
{
cout << "Cannot find java method ErrorHandler" << endl;
return textErr;
}
// convert jstring to char*
const char* textIn = env->GetStringUTFChars(textInJava, NULL);
const char* options = env->GetStringUTFChars(optionsJava, NULL);
// call the C++ formatting function
char* textOut = AStyleMain(textIn, options, javaErrorHandler, javaMemoryAlloc);
// if an error message occurred it was displayed by errorHandler
if (textOut == NULL)
return textErr;
// release memory
jstring textOutJava = env->NewStringUTF(textOut);
delete [] textOut;
env->ReleaseStringUTFChars(textInJava, textIn);
env->ReleaseStringUTFChars(optionsJava, options);
return textOutJava;
}
// Call the Java error handler
void STDCALL javaErrorHandler(int errorNumber, char* errorMessage)
{
jstring errorMessageJava = g_env->NewStringUTF(errorMessage);
g_env->CallVoidMethod(g_obj, g_mid, errorNumber, errorMessageJava);
}
// Allocate memory for the formatted text
char* STDCALL javaMemoryAlloc(unsigned long memoryNeeded)
{
// error condition is checked after return from AStyleMain
char* buffer = new(nothrow) char [memoryNeeded];
return buffer;
}
#endif
#ifdef ASTYLE_LIB
// ************************* GUI functions *****************************************************
/*
* IMPORTANT VC DLL linker must have the parameter /EXPORT:AStyleMain=_AStyleMain@16
* /EXPORT:AStyleGetVersion=_AStyleGetVersion@0
* For Dll only - "warning C4702: unreachable code" in the <vector> header
* is caused by using the Optimization options.
* /O2 Maximize speed
* /O1 Minimize size
* /Ob2 Inline Expansion
* This is a bug in the Microsoft compiler. The program runs about twice as fast
* with the options set. There haven't been any problems so far.
*/
extern "C" EXPORT char* STDCALL
AStyleMain(const char* pSourceIn, // pointer to the source to be formatted
const char* pOptions, // pointer to AStyle options, separated by \n
fpError fpErrorHandler, // pointer to error handler function
fpAlloc fpMemoryAlloc) // pointer to memory allocation function
{
if (fpErrorHandler == NULL) // cannot display a message if no error handler
return NULL;
if (pSourceIn == NULL)
{
fpErrorHandler(101, (char*)"No pointer to source input.");
return NULL;
}
if (pOptions == NULL)
{
fpErrorHandler(102, (char*)"No pointer to AStyle options.");
return NULL;
}
if (fpMemoryAlloc == NULL)
{
fpErrorHandler(103, (char*)"No pointer to memory allocation function.");
return NULL;
}
ASFormatter formatter;
string arg;
vector<string> optionsVector;
istringstream opt(pOptions);
_err = new stringstream;
g_modeManuallySet = false;
importOptions(opt, optionsVector);
parseOptions(formatter,
optionsVector.begin(),
optionsVector.end(),
"Invalid Artistic Style options.\n"
"The following options were not processed:");
if (_err->str().length() > 0)
fpErrorHandler(210, (char*) _err->str().c_str());
delete _err;
_err = NULL;
istringstream in(pSourceIn);
ASStreamIterator<istringstream> streamIterator(&in);
ostringstream out;
formatter.init(&streamIterator);
while (formatter.hasMoreLines())
{
out << formatter.nextLine();
if (formatter.hasMoreLines())
out << streamIterator.getOutputEOL();
}
unsigned long textSizeOut = out.str().length();
char* pTextOut = fpMemoryAlloc(textSizeOut + 1); // call memory allocation function
// pTextOut = NULL; // for testing
if (pTextOut == NULL)
{
fpErrorHandler(110, (char*)"Allocation failure on output.");
return NULL;
}
strcpy(pTextOut, out.str().c_str());
return pTextOut;
}
extern "C" EXPORT const char* STDCALL AStyleGetVersion (void)
{
return _version;
}
#else
// *********************** console functions ***************************************************
void preserveFileDate(const char *oldFileName, const char *newFileName)
{
struct stat stBuf;
bool statErr = false;
if (stat (oldFileName, &stBuf) == -1)
statErr = true;
else
{
struct utimbuf outBuf;
outBuf.actime = stBuf.st_atime;
// add 1 so 'make' will recoginze a change
outBuf.modtime = stBuf.st_mtime + 1;
if (utime (newFileName, &outBuf) == -1)
statErr = true;
}
if (statErr)
(*_err) << " Could not preserve file date" << endl;
}
bool stringEndsWith(const string &str, const string &suffix)
{
int strIndex = (int) str.length() - 1;
int suffixIndex = (int) suffix.length() - 1;
while (strIndex >= 0 && suffixIndex >= 0)
{
if (tolower(str[strIndex]) != tolower(suffix[suffixIndex]))
return false;
--strIndex;
--suffixIndex;
}
return true;
}
#ifdef _WIN32 // Windows specific
/**
* WINDOWS function to resolve wildcards and recurse into sub directories.
* The fileName vector is filled with the path and names of files to process.
*
* @param directory The path of the directory to be processed.
* @param wildcard The wildcard to be processed (e.g. *.cpp).
* @param filenam An empty vector which will be filled with the path and names of files to process.
*/
void getFileNames(const string &directory, const string &wildcard, vector<string> &fileName)
{
vector<string> subDirectory; // sub directories of directory
WIN32_FIND_DATA FindFileData; // for FindFirstFile and FindNextFile
// Find the first file in the directory
string firstFile = directory + "\\*";
HANDLE hFind = FindFirstFile(firstFile.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
error("Cannot open directory", directory.c_str());
// save files and sub directories
do
{
// skip hidden or read only
if (FindFileData.cFileName[0] == '.'
|| (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
|| (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
continue;
// if a sub directory and recursive, save sub directory
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && g_isRecursive)
{
string subDirectoryPath = directory + g_fileSeparator + FindFileData.cFileName;
if (isPathExclued(subDirectoryPath))
{
if (!g_isQuiet)
cout << "exclude " << subDirectoryPath.substr(g_mainDirectoryLength) << endl;
}
else
subDirectory.push_back(subDirectoryPath);