-
Notifications
You must be signed in to change notification settings - Fork 0
/
cstyle.pl
1557 lines (1295 loc) · 42.9 KB
/
cstyle.pl
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
#!/usr/bin/perl
#
# Copyright (c) 2001-2017 Grant Erickson
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Description:
# This program is used to flexibly and parametrically check for code
# formatting style compliance.
#
# Philosophically, this assumes it is working on compilable
# code. Consequently, this does not endeavor to be nor is it a
# grammatically-correct source code parser.
#
# Where possible, effort is expended to make the syntax, option
# invocation, and output familiar to users of compilers and other
# linting and formatting tools for ease of use and efficient
# system integration.
#
use strict 'refs';
use File::Basename;
use File::Path;
use Getopt::Long qw(:config gnu_getopt);
use POSIX;
# Global Variables
my($program);
# Default program options. Eventually, the vision is to allow these to
# be overridden by command-line options and via a global
# (e.g. /usr/local/etc/style.conf) or local (e.g. ~/.style) or
# arbitrary configuration file. However, at present, only command-line
# options are supported since loading and parsing configuration files
# will, undoubtably, slow the program down considerably.
my(%defaults) = ();
my(%options) = ();
my(%warnings) = ();
# Mappings of supported languages to style handlers. Supported
# languages as translated by file extension or via the '-x' option. In
# the absence of any better nomenclature, the language names from GCC
# are used.
my(%handlers) = (
"assembler", \&asmstyle,
"assembler-with-cpp", \&asmstyle,
"c", \&cstyle,
"c-header", \&cstyle,
"c++", \&cxxstyle,
"c++-header", \&cxxstyle,
"objective-c", \&objcstyle,
"objective-c-header", \&objcstyle,
"objective-c++", \&objcxxstyle,
"objective-c++-header", \&objcxxstyle
);
my(@languages) = sort(keys(%handlers));
# Mappings of file extensions to source language type. As with the list
# of supported languages, language names from GCC are used.
my(%extensions) = (
"C", "c++",
"H", "c++-header",
"M", "objective-c++",
"S", "assembler-with-cpp",
"c", "c",
"c++", "c++",
"cc", "c++",
"cp", "c++",
"cpp", "c++",
"cxx", "c++",
"h", "c-header",
"hh", "c++-header",
"hpp", "c++-header",
"m", "objective-c",
"mm", "objective-c++",
"s", "assembler"
);
# Some freqeuently-used, precompiled regular expression patterns.
my($storage_specifiers_re) = qr/((extern|static)\s+)/;
my($type_qualifiers_re) = qr/((const|volatile)\s+)/;
my($method_qualifiers_re) = qr/((const|volatile)\s*)/;
my($type_declarator_re) = qr/([_[:alpha:]][_[:alnum:]]*\s*)/;
my($type_re) = qr/$type_qualifiers_re*$type_declarator_re*\s*($type_qualifiers_re*[*&])*/;
my($function_declarator_re) = qr/([_~[:alpha:]][_[:alnum:]]*)/;
my($argument_declarator_re) = qr/([_[:alpha:]][_[:alnum:]]*)/;
my($array_declarator_re) = qr/(\[\w+\])/;
my($argument_re) = qr/$type_re\s*($argument_declarator_re\s*$array_declarator_re*)*/;
my($argument_list_re) = qr/(void|($argument_re\s*,*\s*)*)/;
my($function_declaration_re) = qr/$storage_specifiers_re*\s*$type_re\s*$function_declarator_re\s*\($argument_list_re\)\s*$method_qualifiers_re*;\s*/;
#
# usage()
#
# Description:
# This routine prints out the proper command line usage for this program
#
# Input(s):
# status - Flag determining what usage information will be printed and what
# the exit status of the program will be after the information is
# printed.
#
# Output(s):
# N/A
#
# Returns:
# This subroutine does not return.
#
sub usage {
my($status) = $_[0];
print(STDERR "Usage: style [ options... ] [ files... ]\n");
if ($status != 0) {
print(STDERR "Try `style --help' for more information.\n");
}
if ($status != 1) {
my($usage) =
"General Options:
-d, --debug Display debug execution information.
--help Display this information.
-v, --verbose Display verbose execution information.
--version Display version information.
-W<WARNING> Select a comma-separated WARNING option.
-x, --language=<LANGUAGE> Specify LANGUAGE as source language of input
files.
Language Options:
Permissible languages include:
%s
'none' means revert to the default behavior of guessing the language
based on the input file's extension.
Style Options:
--copyright=<PATTERN> Copyright pattern to search for.
--file-length=<LENGTH> Maximum file length is LENGTH lines.
--line-length=<LENGTH> Maximum line length is LENGTH characters.
--tab-size=<SIZE> Interpret tab characters as SIZE spaces.
--cpp-lines-between-conditionals=<LINES>
Initiate preprocessor conditional checks when
separation between conditionals is more than
LINES lines.
Warning Options:
-Wall Enable all warning options.
-Werror Make all warnings into errors.
-Wimplicit-void-declaration Warn about implicit void declarations [EXPERIMENTAL].
-Winterpolated-space Warn about interpolated spaces and tabs.
-Wfile-length Warn about long files.
-Wline-length Warn about long lines.
-Wtrailing-line Warn about blank line(s) at the end of a file.
-Wblank-trailing-space Warn about white space at the end of a blank line.
-Wtrailing-space Warn about white space at the end of a non-blank
line.
-Wmissing-cpp-conditional-labels
Warn about missing labels on conditionals.
-Wcpp-constant-conditionals
Warn about constant conditional expressions.
-Wcpp-directive-leading-space
Warn about leading space before directives.
-Wmultiple-returns
Warn about multiple return statements per function or method.
-Wmissing-copyright Warn about a missing copyright declaration.
-Wmissing-newline-at-eof Warn about missing new line at the end of a file.
-Wmissing-space-after-comma Warn about missing space after a comma.
-Wmissing-space-after-else-if Warn about missing space after the 'else if' keyword
-Wmissing-space-after-for Warn about missing space after the 'for' keyword
-Wmissing-space-after-if Warn about missing space after the 'if' keyword
-Wmissing-space-after-operator Warn about missing space after the 'operator' keyword.
-Wmissing-space-after-semicolon
Warn about missing space after a semicolon.
-Wmissing-space-after-switch Warn about missing space after the 'switch' keyword
-Wmissing-space-after-while Warn about missing space after the 'while' keyword
-Wmissing-space-around-binary-operators
Warn about missing space around binary operators [EXPERIMENTAL].
-Wmissing-space-around-braces Warn about missing space around braces.
-Wspace-around-unary-operators Warn about space around unary operators.
";
# Build up a string of the permissible languages
my($languages) = "'" . join("', '", @languages) . "' and 'none'";
# Display the usage, substituting in the permissible languages
printf(STDERR $usage, $languages);
}
exit($status);
}
#
# version()
#
# Description:
# This routine prints out program version information
#
# Input(s):
# N/A
#
# Output(s):
# N/A
#
# Returns:
# This subroutine does not return.
#
sub version {
print("cstyle Version 1.7.5d\n");
print("Copyright (c) 2001-2017 Grant Erickson\n");
exit (0);
}
#
# parse_warnings
#
# Description:
# This routine handles generating a quick-reference hash to all options
# invoked by the '-W' command line option.
#
# Input(s):
# option - This is the command option and should always be 'W'.
# argument - This is the command argument and may contain one or
# more comma-separated arguments.
#
# Output(s):
# N/A
#
# Returns:
# N/A
#
sub parse_warnings {
my($warning);
my($flag);
# Options are either going to be singly specified or comma-separated.
# In either case, split them up and add them to the warning hash.
foreach $warning (split(/,/, $_[1])) {
# Warning options may only use alphanumeric characters and the
# dash (-) or underscore (_) characters.
if ($warning =~ m/[^A-Za-z0-9_\-]/g) {
die("Unknown or invalid warning option: `$warning'");
}
# Warnings that are of the form 'no-<warning>' have the effect of
# disabling a warning (e.g. overrides -Wall or a previous enabling
# of that warning.
#
# Attempt to match and if it matches, delete, the leading 'no-' to
# a warning option and then deassert the warning. Otherwise, assert
# the warning.
if ($warning =~ s/^no-//g) {
$flag = 0;
} else {
$flag = 1;
}
# Set the warning hash to true for this warning key.
$warnings{$warning} = $flag;
}
}
#
# decode_options()
#
# Description:
# This routine steps through the command-line arguments, parsing out
# recognzied options.
#
# Input(s):
# N/A
#
# Output(s):
# N/A
#
# Returns:
# N/A
#
sub decode_options {
my($errors) = 0;
my(@dependencies);
if (!&GetOptions(\%options,
"W=s@" => \&parse_warnings,
"debug|d+",
"help",
"language|x=s",
"copyright=s",
"cpp-lines-between-conditionals=i",
"file-length=i",
"line-length|l=i",
"tab-size|ts=i",
"verbose|v+",
"version"
)) {
usage(1);
}
if ($options{"version"}) {
version();
}
if ($options{"help"}) {
usage(0);
}
# If -Wmissing-copyright was set, then so too must be --copyright.
@dependencies = ({ OPTION => "copyright",
DESCRIPTION => "copyright regular expression pattern" });
$errors += check_warning_deps("missing-copyright", \@dependencies);
# If -Wfile-length was set, then so too must be --file-length.
@dependencies = ({ OPTION => "file-length",
DESCRIPTION => "file length" });
$errors += check_warning_deps("file-length", \@dependencies);
# If -Wline-length was set, then so too must be --line-length and
# --tab-size.
@dependencies = ({ OPTION => "line-length",
DESCRIPTION => "line length" },
{ OPTION => "tab-size",
DESCRIPTION => "tab size" });
$errors += check_warning_deps("line-length", \@dependencies);
# If -Wmissing-cpp-conditional-labels was set, then so too must be
# --cpp-lines-between-conditionals.
@dependencies = ({ OPTION => "cpp-lines-between-conditionals",
DESCRIPTION => "maximum number of lines between " .
"preprocessor conditionals" });
$errors += check_warning_deps("missing-cpp-conditional-labels", \@dependencies);
# At this point, we either have a list of one or more files to process
# remaining in the argument list or we will process standard input. If
# we are processing standard input, then a language must be specified.
if ($#ARGV < 0 && !defined($options{"language"})) {
print(STDERR "A language must be specified when using standard input!\n");
$errors++;
}
usage(1) if ($errors);
return;
}
#
# line_violation_with_column()
#
# Description:
# This routine is used in response to line style violations and
# displays, to standard error, the file path, line number, column
# number, and line enforcement violation. If the verbose option flag
# is in effect, the actual text of the offending line is also
# displayed along with a leader indicating the position of the
# error, as specified by the provided column parameter.
#
# Input(s):
# file - Path name of the current input file being processed.
# message - Violation message to display.
# line - The current input line being processed, in its pristine,
# unmodified state.
# column - The column number (0-based) of the violation used to
# generate the indicative leader in verbose mode.
#
# Output(s):
# N/A
#
# Returns:
# N/A
#
sub line_violation_with_column {
my($file) = $_[0];
my($message) = $_[1];
my($line) = $_[2];
my($column) = $_[3];
my($format);
my($status) = ($warnings{"error"} ? "error" : "warning");
if ($options{"verbose"}) {
$format = "%s:%d:%d: %s: %s\n%s\n%s%s\n";
} else {
$format = "%s:%d:%d: %s: %s\n";
}
printf(STDERR $format, $file, $., $column + 1, $status, $message, $line,
'-' x $column, "^");
}
#
# line_violation()
#
# Description:
# This routine is used in response to line style violations and
# displays, to standard error, the file path, line number, column
# number, and line enforcement violation. If the verbose option flag
# is in effect, the actual text of the offending line is also
# displayed along with a leader indicating the position of the
# error. The column to generate the indicating leader is extraced
# from $-[1].
#
# Input(s):
# file - Path name of the current input file being processed.
# message - Violation message to display.
# line - The current input line being processed, in its pristine,
# unmodified state.
#
# Output(s):
# N/A
#
# Returns:
# N/A
#
sub line_violation {
my($file) = $_[0];
my($message) = $_[1];
my($line) = $_[2];
line_violation_with_column($file, $message, $line, $-[1]);
}
#
# file_violation()
#
# Description:
# This routine is used in response to file style violations and
# displays, to standard error, the file path, and file enforcement
# violation.
#
# Input(s):
# file - Path name of the current input file being processed.
# message - Violation message to display.
#
# Output(s):
# N/A
#
# Returns:
# N/A
#
sub file_violation {
my($file) = $_[0];
my($message) = $_[1];
my($format) = "%s: %s: %s\n";
my($status) = ($warnings{"error"} ? "error" : "warning");
printf(STDERR $format, $file, $status, $message);
}
#
# check_warning()
#
# Description:
# This routine checks whether or not the specified warning option has
# been set as well as checking the 'all' warning option which implicitly
# sets the specified warning.
#
# Input(s):
# warning - The name of the warning to be checked.
#
# Output(s):
# N/A
#
# Returns:
# TRUE (1) if the warning is set; otherwise, FALSE (0).
#
sub check_warning {
my($warning) = $_[0];
my($flag);
# A warning is considered enabled if: 1) The warning was
# independently asserted OR 2) The 'all' warning was asserted and
# the warning was not independently deasserted.
#
# So, if we are checking warning 'foo', the following truth table
# results:
#
# -> False
# -Wall -> True
# -Wall -Wfoo -> True
# -Wall -Wno-foo -> False
# -Wfoo -> True
# -Wno-foo -> False
if (defined($warnings{$warning}) && $warnings{$warning}) {
$flag = 1;
} elsif (defined($warnings{$warning}) && !$warnings{$warnings}) {
$flag = 0;
} else {
$flag = $warnings{'all'};
}
return ($flag);
}
#
# check_warning_deps()
#
# Description:
# This routine checks for interdependencies between a warning option
# and one or more style options settings by ensuring the if the
# warning option has been asserted that the style options on which
# it depends are defined.
#
# Input(s):
# warning - The name of the warning to be checked.
# depref - A reference to an array of dependency records, each
# record a hash reference containing the style option and
# description.
#
# Output(s):
# N/A
#
# Returns:
# The number of dependency errors encounterd.
#
sub check_warning_deps {
my($errors) = 0;
my($warning) = $_[0];
my($depref) = $_[1];
if (check_warning($warning)) {
my($warnings) = "`-Wall' or `-W$warning'";
foreach $dependency (@{$depref}) {
if (!defined($options{$dependency->{"OPTION"}})) {
printf(STDERR "The %s must be specified with " .
"`--%s' when used with %s!\n",
$dependency->{"DESCRIPTION"},
$dependency->{"OPTION"},
$warnings);
$errors++;
}
}
}
return ($errors);
}
#
# cppstyle()
#
# Description:
# This routine performs coding style checking for lines identified
# as C preprocessor input.
#
# At minimum, the following preprocessor directives are possible and
# expected:
#
# <null>
# assert <predicate> <answer>
# define <macro> [<expression>]
# elif <expression>
# else
# endif
# error <string>
# ident <string>
# if <expression>
# ifdef <macro>
# ifndef <expression>
# import <string>
# include <string>
# line [ (<number> [<string>]) | <expression> ]
# sccs <string>
# unassert <predicate>
# undef <macro>
# warning <string>
#
# Input(s):
# file - Path name of the current input file being processed.
# line - The current input line being processed, in its pristine,
# unmodified state.
# record - A reference to the record defining the current C preprocessor
# directive being checked.
# records - A stack of C preprocessor conditional directives
# encountered thus far in the input file. This is used as state
# for various checks.
#
# Output(s):
# records - The C preprocessor conditional directive stack, possibly with
# records pushed onto or popped off.
#
# Returns:
# The number of preprocessor violations encountered.
#
sub cppstyle {
my($file) = $_[0];
my($line) = $_[1];
my($record) = $_[2];
my($records) = $_[3];
my($violations) = 0;
# If enabled, check for leading white space before the
# preprocessor directive token ('#').
if (check_warning("cpp-directive-leading-space") &&
(length($record->{'LEADING'}) > 0)) {
line_violation($file, "leading space before preprocessor directive", $line);
$violations++;
}
# Perform directive-specific checking, accumulating state for those
# directives which have context-specific checks.
DIRECTIVE: for ($record->{'DIRECTIVE'}) {
/^(else|endif)$/ && do {
# Check to ensure that conditionals, separated by
# `cpp-lines-between-conditionals' lines or more have
# comment labels.
my($top) = pop(@{$records});
my($ifline) = $top->{'LINE'};
# If the directive is an 'else', put the line the matching
# 'if' directive was on back on the stack since we cannot
# permanently pop it until we see the matching 'endif'.
if ($_ =~ m/^else$/g) {
push(@{$records}, $top);
}
# Compute the distance from the last seen if/ifdef/ifndef
# directive.
my($distance) = $record->{'LINE'} - $ifline;
my($threshold) = $options{"cpp-lines-between-conditionals"};
# If the warning is asserted, the match to anything other than
# white space following the directive hits, and the distance
# exceeds the threshold, flag a violation.
if (check_warning("missing-cpp-conditional-labels") &&
($record->{'REST'} =~ m/^\s*$/g) && ($distance > $threshold)) {
# Rematch on the entire original line so that @- is set
# correctly and the '-v' leader behavior works to identify
# the offending column.
$line =~ m/^\s*#\s*(else|endif)\s*$/g;
line_violation($file,
"Missing preprocessor conditional comment label " .
"for '$_' matching '$top->{'DIRECTIVE'}' at line " .
"$ifline, which is more than $threshold line(s) away",
$line);
$violations++;
}
last DIRECTIVE;
};
/^(if|elif)$/ && do {
# Push the current line onto the if/ifdef/ifndef
# conditional stack so that it can be used for subsequent
# checks.
if ($_ =~ m/^if$/g) {
push(@{$records}, $record);
}
# Check for constant numeric conditional expressions which
# indicate that the code is being unconditionally compiled
# out or in. Any sequence of digits following the directive
# hits the match.
if (check_warning("cpp-constant-conditionals")) {
my($cpp_constant_conditional_re) = qr/[([:space:]]*(\d+)[)[:space:]]*/;
if ($record->{'REST'} =~ m/^$cpp_constant_conditional_re$/g) {
# Rematch on the entire original line so that @- is set
# correctly and the '-v' leader behavior works to identify
# the offending column.
$line =~ m/$cpp_constant_conditional_re$/g;
# Now flag the violation.
line_violation($file, "constant numeric preprocessor expression",
$line);
$violations++;
}
}
last DIRECTIVE;
};
/^if(n)*def$/ && do {
# Push the current line onto the if/ifdef/ifndef
# conditional stack so that it can be used for subsequent
# checks.
push(@{$records}, $record);
last DIRECTIVE;
};
# Default
last DIRECTIVE;
}
return ($violations);
}
#
# asmstyle()
#
# Description:
# This routine performs the actual coding style checking for assembler
# source files.
#
# Input(s):
# file - Path name of the current input file being processed.
#
# Output(s):
# N/A
#
# Returns:
# N/A
#
sub asmstyle {
my($file) = $_[0];
# In the absence of any language-specific checks, just call cstyle...
return (cstyle($file));
}
#
# objcstyle()
#
# Description:
# This routine performs the actual coding style checking for
# Objective C source files.
#
# Input(s):
# file - Path name of the current input file being processed.
#
# Output(s):
# N/A
#
# Returns:
# N/A
#
sub objcstyle {
my($file) = $_[0];
# In the absence of any language-specific checks, just call cstyle...
return (cstyle($file));
}
#
# objcxxstyle()
#
# Description:
# This routine performs the actual coding style checking for
# Objective C++ source files.
#
# Input(s):
# file - Path name of the current input file being processed.
#
# Output(s):
# N/A
#
# Returns:
# N/A
#
sub objcxxstyle {
my($file) = $_[0];
# In the absence of any language-specific checks, just call cstyle...
return (cstyle($file));
}
#
# is_function_or_method_declaration()
#
# Description:
# This routine attempts to perform a match on the current line ($_)
# and determines whether or not it contains a C or C++ function or
# method declaration.
#
# Input(s):
# N/A
#
# Output(s):
# N/A
#
# Returns:
# True (1) if the current line ($_) is thought to contain a C or C++
# function or method declaration; otherwise, false.
#
sub is_function_or_method_declaration {
return (/$function_declaration_re/);
}
#
# is_function_or_method_declaration()
#
# Description:
# This routine attempts to perform a match on the current line ($_)
# and determines whether or not it contains an implicit void (e.g. foo())
# C or C++ function or method declaration.
#
# Input(s):
# N/A
#
# Output(s):
# N/A
#
# Returns:
# True (1) if the current line ($_) is thought to contain an
# implicit void C or C++ function or method declaration; otherwise,
# false.
#
sub is_implicit_void_function_or_method_declaration {
my($virtual_specifier_re) = qr/((virtual)\s+)/;
my($implicit_void_function_declaration_re) = qr/($virtual_specifier_re|$storage_specifiers_re)*\s*$type_re\s*$function_declarator_re\s*\(\s*\)\s*$method_qualifiers_re*(\s*=\s*0)*;\s*/;
my($retval);
$retval = m/$implicit_void_function_declaration_re/gp;
# Filter out:
#
# - Any member pointer or member reference selection void method
# calls.
#
# - Any return statements embedding a void function or method
# call.
#
# - Any assignments with a void function or method call as an rvalue.
if ($retval) {
if ((${^PREMATCH} =~ m/(\.|->)$/gp) ||
(${^PREMATCH} =~ m/\s*return\s/gp) ||
(${^PREMATCH} =~ m/\s*=\s*/gp)) {
$retval = undef;
}
}
return ($retval);
}
#
# cstyle()
#
# Description:
# This routine performs the actual coding style checking for C source
# and header files.
#
# Input(s):
# file - Path name of the current input file being processed.
#
# Output(s):
# N/A
#
# Returns:
# N/A
#
sub cstyle {
my($file) = $_[0];
my($neolchars) = 0;
my($line, $prev);
my($violations) = 0;
my($return_count) = 0;
my(%state) = ();
my(@cppstack);
my(@bracestack);
my($in_function_at_depth) = -1;
my($in_comment) = 0;
my($saw_copyright) = 0;
LINE: while (<STDIN>) {
# Attempt to automatically detect end-of-line markers based on what is
# encountered on the first line.
if ($. == 1) {
if (m/(\015?\012?)$/) {
$/ = $1
}
}
# Strip the end-of-line marker. Note that chomp should always be
# used rather than chop, since chomp acts intelligently based on
# '$/' whereas chop just always consumes that last character on a
# line without regard to whether or not its actually a newline
# character at all.
$neolchars = chomp;
# Cache the input line in its pristine, unmodified state.
$line = $_;
# Clean-up and ignore things we don't want to further check:
#
# 1) Text, including escaped characters, w/i single ('') and double ("") quotes.
s/(["'])(?:(?=(\\?))\2.)*?\1/\1\1/g;
# 2) Trailing backslashes.
s/\s*\\$//;
# Check file length
if (check_warning("file-length")) {
if ($. > $options{"file-length"}) {
line_violation($file, "file > " .
$options{"file-length"} .
" lines", $line);
$violations++;
}
}
# Inline "/* *STYLE-OFF* */" or "// *STYLE-OFF*" directives on a
# line by themselves exempt subsequent lines from style checking
# until a similar "/* *STYLE-ON* */ or "// *STYLE-ON*" directive
# on a line by itself is encountered.
if ((/^\s*\/\*\s*\*STYLE-(ON|OFF)\*\s*\*\/$/) || # C-style directive
(/^\s*\/\/\s*\*STYLE-(ON|OFF)\*$/)) { # C++-style directive
# Set the state based on the positional match argument of "ON" or "OFF"
$state{"style-disable"} = ($1 eq "OFF") ? 1 : 0;
}
# If style checking has been disabled by a style directive, skip ahead
# to the next line.
if (defined($state{"style-disable"}) && $state{"style-disable"} == 1) {
$prev = $line;
next LINE;
}
#
# Check line length
#
if (check_warning("line-length")) {
# First, a quick check to see if there is any chance of being too long.
if ($line =~ tr/\t/\t/ *
($options{"tab-size"} - 1) +
length($line) > $options{"line-length"}) {
# Confirmed. Interpolate spaces for tabs and check again.
$eline = $line;
1 while $eline =~ s/\t+/" " x (length($&) *
$options{"tab-size"} - length($`) %
$options{"tab-size"})/e;
if (length($eline) > $options{"line-length"}) {
line_violation($file, "line > " .