Debian Codegraph @

lib/cmock_header_parser.rb

raw symbols SCIP
1 # ==========================================
2 # CMock Project - Automatic Mock Generation for C
3 # Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
4 # [Released under MIT License. Please refer to license.txt for details]
5 # ==========================================
6
7 class CMockHeaderParser
8 attr_accessor :funcs, :c_attr_noconst, :c_attributes, :treat_as_void, :treat_externs, :treat_inlines, :inline_function_patterns
9
10 def initialize(cfg)
11 @c_strippables = cfg.strippables
12 @c_attr_noconst = cfg.attributes.uniq - ['const']
13 @c_attributes = ['const'] + c_attr_noconst
14 @c_calling_conventions = cfg.c_calling_conventions.uniq
15 @treat_as_array = cfg.treat_as_array
16 @treat_as_void = (['void'] + cfg.treat_as_void).uniq
17 @function_declaration_parse_base_match = '([\w\s\*\(\),\[\]]*?\w[\w\s\*\(\),\[\]]*?)\(([\w\s\*\(\),\.\[\]+\-\/]*)\)'
18 @declaration_parse_matcher = /#{@function_declaration_parse_base_match}$/m
19 @standards = (%w[int short char long unsigned signed] + cfg.treat_as.keys).uniq
20 @array_size_name = cfg.array_size_name
21 @array_size_type = (%w[int size_t] + cfg.array_size_type).uniq
22 @when_no_prototypes = cfg.when_no_prototypes
23 @local_as_void = @treat_as_void
24 @verbosity = cfg.verbosity
25 @treat_externs = cfg.treat_externs
26 @treat_inlines = cfg.treat_inlines
27 @inline_function_patterns = cfg.inline_function_patterns
28 @c_strippables += ['extern'] if @treat_externs == :include # we'll need to remove the attribute if we're allowing externs
29 @c_strippables += ['inline'] if @treat_inlines == :include # we'll need to remove the attribute if we're allowing inlines
30 end
31
32 def parse(name, source)
33 parse_project = {
34 :module_name => name.gsub(/\W/, ''),
35 :typedefs => [],
36 :functions => [],
37 :normalized_source => nil
38 }
39
40 function_names = []
41
42 all_funcs = parse_functions(import_source(source, parse_project)).map { |item| [item] }
43 all_funcs += parse_cpp_functions(import_source(source, parse_project, true))
44 all_funcs.map do |decl|
45 func = parse_declaration(parse_project, *decl)
46 unless function_names.include? func[:name]
47 parse_project[:functions] << func
48 function_names << func[:name]
49 end
50 end
51
52 parse_project[:normalized_source] = if @treat_inlines == :include
53 transform_inline_functions(source)
54 else
55 ''
56 end
57
58 { :includes => nil,
59 :functions => parse_project[:functions],
60 :typedefs => parse_project[:typedefs],
61 :normalized_source => parse_project[:normalized_source] }
62 end
63
64 private if $ThisIsOnlyATest.nil? ################
65
66 # Remove C/C++ comments from a string
67 # +source+:: String which will have the comments removed
68 def remove_comments_from_source(source)
69 # remove comments (block and line, in three steps to ensure correct precedence)
70 source.gsub!(/(?<!\*)\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '') # remove line comments that comment out the start of blocks
71 source.gsub!(/\/\*.*?\*\//m, '') # remove block comments
72 source.gsub!(/\/\/.*$/, '') # remove line comments (all that remain)
73 end
74
75 def remove_nested_pairs_of_braces(source)
76 # remove nested pairs of braces because no function declarations will be inside of them (leave outer pair for function definition detection)
77 if RUBY_VERSION.split('.')[0].to_i > 1
78 # we assign a string first because (no joke) if Ruby 1.9.3 sees this line as a regex, it will crash.
79 r = '\\{([^\\{\\}]*|\\g<0>)*\\}'
80 source.gsub!(/#{r}/m, '{ }')
81 else
82 while source.gsub!(/\{[^\{\}]*\{[^\{\}]*\}[^\{\}]*\}/m, '{ }')
83 end
84 end
85
86 source
87 end
88
89 # Return the number of pairs of braces/square brackets in the function provided by the user
90 # +source+:: String containing the function to be processed
91 def count_number_of_pairs_of_braces_in_function(source)
92 is_function_start_found = false
93 curr_level = 0
94 total_pairs = 0
95
96 source.each_char do |c|
97 if c == '{'
98 curr_level += 1
99 total_pairs += 1
100 is_function_start_found = true
101 elsif c == '}'
102 curr_level -= 1
103 end
104
105 break if is_function_start_found && curr_level == 0 # We reached the end of the inline function body
106 end
107
108 if curr_level != 0
109 total_pairs = 0 # Something is fishy about this source, not enough closing braces?
110 end
111
112 total_pairs
113 end
114
115 # Transform inline functions to regular functions in the source by the user
116 # +source+:: String containing the source to be processed
117 def transform_inline_functions(source)
118 inline_function_regex_formats = []
119 square_bracket_pair_regex_format = /\{[^\{\}]*\}/ # Regex to match one whole block enclosed by two square brackets
120
121 # Convert user provided string patterns to regex
122 # Use word bounderies before and after the user regex to limit matching to actual word iso part of a word
123 @inline_function_patterns.each do |user_format_string|
124 user_regex = Regexp.new(user_format_string)
125 word_boundary_before_user_regex = /\b/
126 cleanup_spaces_after_user_regex = /[ ]*\b/
127 inline_function_regex_formats << Regexp.new(word_boundary_before_user_regex.source + user_regex.source + cleanup_spaces_after_user_regex.source)
128 end
129
130 # let's clean up the encoding in case they've done anything weird with the characters we might find
131 source = source.force_encoding('ISO-8859-1').encode('utf-8', :replace => nil)
132
133 # Comments can contain words that will trigger the parser (static|inline|<user_defined_static_keyword>)
134 remove_comments_from_source(source)
135
136 # smush multiline macros into single line (checking for continuation character at end of line '\')
137 # If the user uses a macro to declare an inline function,
138 # smushing the macros makes it easier to recognize them as a macro and if required,
139 # remove them later on in this function
140 source.gsub!(/\s*\\\s*/m, ' ')
141
142 # Just looking for static|inline in the gsub is a bit too aggressive (functions that are named like this, ...), so we try to be a bit smarter
143 # Instead, look for an inline pattern (f.e. "static inline") and parse it.
144 # Below is a small explanation on how the general mechanism works:
145 # - Everything before the match should just be copied, we don't want
146 # to touch anything but the inline functions.
147 # - Remove the implementation of the inline function (this is enclosed
148 # in square brackets) and replace it with ";" to complete the
149 # transformation to normal/non-inline function.
150 # To ensure proper removal of the function body, we count the number of square-bracket pairs
151 # and remove the pairs one-by-one.
152 # - Copy everything after the inline function implementation and start the parsing of the next inline function
153 # There are ofcourse some special cases (inline macro declarations, inline function declarations, ...) which are handled and explained below
154 inline_function_regex_formats.each do |format|
155 inspected_source = ''
156 regex_matched = false
157 loop do
158 inline_function_match = source.match(/#{format}/) # Search for inline function declaration
159
160 if inline_function_match.nil? # No inline functions so nothing to do
161 # Join pre and post match stripped parts for the next inline function detection regex
162 source = inspected_source + source if regex_matched == true
163 break
164 end
165
166 regex_matched = true
167 # 1. Determine if we are dealing with a user defined macro to declare inline functions
168 # If the end of the pre-match string is a macro-declaration-like string,
169 # we are dealing with a user defined macro to declare inline functions
170 if /(#define\s*)\z/ =~ inline_function_match.pre_match
171 # Remove the macro from the source
172 stripped_pre_match = inline_function_match.pre_match.sub(/(#define\s*)\z/, '')
173 stripped_post_match = inline_function_match.post_match.sub(/\A(.*[\n]?)/, '')
174 inspected_source += stripped_pre_match
175 source = stripped_post_match
176 next
177 end
178
179 # 2. Determine if we are dealing with an inline function declaration iso function definition
180 # If the start of the post-match string is a function-declaration-like string (something ending with semicolon after the function arguments),
181 # we are dealing with a inline function declaration
182 if /\A#{@function_declaration_parse_base_match}\s*;/m =~ inline_function_match.post_match
183 # Only remove the inline part from the function declaration, leaving the function declaration won't do any harm
184 inspected_source += inline_function_match.pre_match
185 source = inline_function_match.post_match
186 next
187 end
188
189 # 3. If we get here, we found an inline function declaration AND inline function body.
190 # Remove the function body to transform it into a 'normal' function declaration.
191 if /\A#{@function_declaration_parse_base_match}\s*\{/m =~ inline_function_match.post_match
192 total_pairs_to_remove = count_number_of_pairs_of_braces_in_function(inline_function_match.post_match)
193
194 break if total_pairs_to_remove == 0 # Bad source?
195
196 inline_function_stripped = inline_function_match.post_match
197
198 total_pairs_to_remove.times do
199 inline_function_stripped.sub!(/\s*#{square_bracket_pair_regex_format}/, ';') # Remove inline implementation (+ some whitespace because it's prettier)
200 end
201 inspected_source += inline_function_match.pre_match
202 source = inline_function_stripped
203 next
204 end
205
206 # 4. If we get here, it means the regex match, but it is not related to the function (ex. static variable in header)
207 # Leave this code as it is.
208 inspected_source += inline_function_match.pre_match + inline_function_match[0]
209 source = inline_function_match.post_match
210 end
211 end
212
213 source
214 end
215
216 def import_source(source, parse_project, cpp = false)
217 # let's clean up the encoding in case they've done anything weird with the characters we might find
218 source = source.force_encoding('ISO-8859-1').encode('utf-8', :replace => nil)
219
220 # void must be void for cmock _ExpectAndReturn calls to process properly, not some weird typedef which equates to void
221 # to a certain extent, this action assumes we're chewing on pre-processed header files, otherwise we'll most likely just get stuff from @treat_as_void
222 @local_as_void = @treat_as_void
223 void_types = source.scan(/typedef\s+(?:\(\s*)?void(?:\s*\))?\s+([\w]+)\s*;/)
224 if void_types
225 @local_as_void += void_types.flatten.uniq.compact
226 end
227
228 # If user wants to mock inline functions,
229 # remove the (user specific) inline keywords before removing anything else to avoid missing an inline function
230 if @treat_inlines == :include
231 @inline_function_patterns.each do |user_format_string|
232 source.gsub!(/#{user_format_string}/, '') # remove user defined inline function patterns
233 end
234 end
235
236 # smush multiline macros into single line (checking for continuation character at end of line '\')
237 source.gsub!(/\s*\\\s*/m, ' ')
238
239 remove_comments_from_source(source)
240
241 # remove assembler pragma sections
242 source.gsub!(/^\s*#\s*pragma\s+asm\s+.*?#\s*pragma\s+endasm/m, '')
243
244 # remove gcc's __attribute__ tags
245 source.gsub!(/__attribute(?:__)?\s*\(\(+.*\)\)+/, '')
246
247 # remove preprocessor statements and extern "C"
248 source.gsub!(/extern\s+\"C\"\s*\{/, '')
249 source.gsub!(/^\s*#.*/, '')
250
251 # enums, unions, structs, and typedefs can all contain things (e.g. function pointers) that parse like function prototypes, so yank them
252 # forward declared structs are removed before struct definitions so they don't mess up real thing later. we leave structs keywords in function prototypes
253 source.gsub!(/^[\w\s]*struct[^;\{\}\(\)]+;/m, '') # remove forward declared structs
254 source.gsub!(/^[\w\s]*(enum|union|struct|typedef)[\w\s]*\{[^\}]+\}[\w\s\*\,]*;/m, '') # remove struct, union, and enum definitions and typedefs with braces
255 # remove problem keywords
256 source.gsub!(/(\W)(?:register|auto|restrict)(\W)/, '\1\2')
257 source.gsub!(/(\W)(?:static)(\W)/, '\1\2') unless cpp
258
259 source.gsub!(/\s*=\s*['"a-zA-Z0-9_\.]+\s*/, '') # remove default value statements from argument lists
260 source.gsub!(/^(?:[\w\s]*\W)?typedef\W[^;]*/m, '') # remove typedef statements
261 source.gsub!(/\)(\w)/, ') \1') # add space between parenthese and alphanumeric
262 source.gsub!(/(^|\W+)(?:#{@c_strippables.join('|')})(?=$|\W+)/, '\1') unless @c_strippables.empty? # remove known attributes slated to be stripped
263
264 # scan standalone function pointers and remove them, because they can just be ignored
265 source.gsub!(/\w+\s*\(\s*\*\s*\w+\s*\)\s*\([^)]*\)\s*;/, ';')
266
267 # scan for functions which return function pointers, because they are a pain
268 source.gsub!(/([\w\s\*]+)\(*\(\s*\*([\w\s\*]+)\s*\(([\w\s\*,]*)\)\)\s*\(([\w\s\*,]*)\)\)*/) do |_m|
269 functype = "cmock_#{parse_project[:module_name]}_func_ptr#{parse_project[:typedefs].size + 1}"
270 unless cpp # only collect once
271 parse_project[:typedefs] << "typedef #{Regexp.last_match(1).strip}(*#{functype})(#{Regexp.last_match(4)});"
272 "#{functype} #{Regexp.last_match(2).strip}(#{Regexp.last_match(3)});"
273 end
274 end
275
276 source = remove_nested_pairs_of_braces(source) unless cpp
277
278 if @treat_inlines == :include
279 # Functions having "{ }" at this point are/were inline functions,
280 # User wants them in so 'disguise' them as normal functions with the ";"
281 source.gsub!('{ }', ';')
282 end
283
284 # remove function definitions by stripping off the arguments right now
285 source.gsub!(/\([^\)]*\)\s*\{[^\}]*\}/m, ';')
286
287 # drop extra white space to make the rest go faster
288 source.gsub!(/^\s+/, '') # remove extra white space from beginning of line
289 source.gsub!(/\s+$/, '') # remove extra white space from end of line
290 source.gsub!(/\s*\(\s*/, '(') # remove extra white space from before left parens
291 source.gsub!(/\s*\)\s*/, ')') # remove extra white space from before right parens
292 source.gsub!(/\s+/, ' ') # remove remaining extra white space
293
294 # split lines on semicolons and remove things that are obviously not what we are looking for
295 src_lines = source.split(/\s*;\s*/)
296 src_lines = src_lines.uniq unless cpp # must retain closing braces for class/namespace
297 src_lines.delete_if { |line| line.strip.empty? } # remove blank lines
298 src_lines.delete_if { |line| !(line =~ /[\w\s\*]+\(+\s*\*[\*\s]*[\w\s]+(?:\[[\w\s]*\]\s*)+\)+\s*\((?:[\w\s\*]*,?)*\s*\)/).nil? } # remove function pointer arrays
299
300 unless @treat_externs == :include
301 src_lines.delete_if { |line| !(line =~ /(?:^|\s+)(?:extern)\s+/).nil? } # remove extern functions
302 end
303
304 unless @treat_inlines == :include
305 src_lines.delete_if { |line| !(line =~ /(?:^|\s+)(?:inline)\s+/).nil? } # remove inline functions
306 end
307
308 src_lines.delete_if(&:empty?) # drop empty lines
309 end
310
311 # Rudimentary C++ parser - does not handle all situations - e.g.:
312 # * A namespace function appears after a class with private members (should be parsed)
313 # * Anonymous namespace (shouldn't parse anything - no matter how nested - within it)
314 # * A class nested within another class
315 def parse_cpp_functions(source)
316 funcs = []
317
318 ns = []
319 pub = false
320 source.each do |line|
321 # Search for namespace, class, opening and closing braces
322 line.scan(/(?:(?:\b(?:namespace|class)\s+(?:\S+)\s*)?{)|}/).each do |item|
323 if item == '}'
324 ns.pop
325 else
326 token = item.strip.sub(/\s+/, ' ')
327 ns << token
328
329 pub = false if token.start_with? 'class'
330 pub = true if token.start_with? 'namespace'
331 end
332 end
333
334 pub = true if line =~ /public:/
335 pub = false if line =~ /private:/ || line =~ /protected:/
336
337 # ignore non-public and non-static
338 next unless pub
339 next unless line =~ /\bstatic\b/
340
341 line.sub!(/^.*static/, '')
342 next unless line =~ @declaration_parse_matcher
343
344 tmp = ns.reject { |item| item == '{' }
345
346 # Identify class name, if any
347 cls = nil
348 if tmp[-1].start_with? 'class '
349 cls = tmp.pop.sub(/class (\S+) {/, '\1')
350 end
351
352 # Assemble list of namespaces
353 tmp.each { |item| item.sub!(/(?:namespace|class) (\S+) {/, '\1') }
354
355 funcs << [line.strip.gsub(/\s+/, ' '), tmp, cls]
356 end
357 funcs
358 end
359
360 def parse_functions(source)
361 funcs = []
362 source.each { |line| funcs << line.strip.gsub(/\s+/, ' ') if line =~ @declaration_parse_matcher }
363 if funcs.empty?
364 case @when_no_prototypes
365 when :error
366 raise 'ERROR: No function prototypes found!'
367 when :warn
368 puts 'WARNING: No function prototypes found!' unless @verbosity < 1
369 end
370 end
371 funcs
372 end
373
374 def parse_type_and_name(arg)
375 # Split up words and remove known attributes. For pointer types, make sure
376 # to remove 'const' only when it applies to the pointer itself, not when it
377 # applies to the type pointed to. For non-pointer types, remove any
378 # occurrence of 'const'.
379 arg.gsub!(/(\w)\*/, '\1 *') # pull asterisks away from preceding word
380 arg.gsub!(/\*(\w)/, '* \1') # pull asterisks away from following word
381 arg_array = arg.split
382 arg_info = divine_ptr_and_const(arg)
383 arg_info[:name] = arg_array[-1]
384
385 attributes = arg.include?('*') ? @c_attr_noconst : @c_attributes
386 attr_array = []
387 type_array = []
388
389 arg_array[0..-2].each do |word|
390 if attributes.include?(word)
391 attr_array << word
392 elsif @c_calling_conventions.include?(word)
393 arg_info[:c_calling_convention] = word
394 else
395 type_array << word
396 end
397 end
398
399 if arg_info[:const_ptr?]
400 attr_array << 'const'
401 type_array.delete_at(type_array.rindex('const'))
402 end
403
404 arg_info[:modifier] = attr_array.join(' ')
405 arg_info[:type] = type_array.join(' ').gsub(/\s+\*/, '*') # remove space before asterisks
406 arg_info
407 end
408
409 def parse_args(arg_list)
410 args = []
411 arg_list.split(',').each do |arg|
412 arg.strip!
413 return args if arg =~ /^\s*((\.\.\.)|(void))\s*$/ # we're done if we reach void by itself or ...
414
415 arg_info = parse_type_and_name(arg)
416 arg_info.delete(:modifier) # don't care about this
417 arg_info.delete(:c_calling_convention) # don't care about this
418
419 # in C, array arguments implicitly degrade to pointers
420 # make the translation explicit here to simplify later logic
421 if @treat_as_array[arg_info[:type]] && !(arg_info[:ptr?])
422 arg_info[:type] = "#{@treat_as_array[arg_info[:type]]}*"
423 arg_info[:type] = "const #{arg_info[:type]}" if arg_info[:const?]
424 arg_info[:ptr?] = true
425 end
426
427 args << arg_info
428 end
429
430 # Try to find array pair in parameters following this pattern : <type> * <name>, <@array_size_type> <@array_size_name>
431 args.each_with_index do |val, index|
432 next_index = index + 1
433 next unless args.length > next_index
434
435 if (val[:ptr?] == true) && args[next_index][:name].match(@array_size_name) && @array_size_type.include?(args[next_index][:type])
436 val[:array_data?] = true
437 args[next_index][:array_size?] = true
438 end
439 end
440
441 args
442 end
443
444 def divine_ptr(arg)
445 return false unless arg.include? '*'
446 # treat "const char *" and similar as a string, not a pointer
447 return false if /(^|\s)(const\s+)?char(\s+const)?\s*\*(?!.*\*)/ =~ arg
448
449 true
450 end
451
452 def divine_const(arg)
453 # a non-pointer arg containing "const" is a constant
454 # an arg containing "const" before the last * is a pointer to a constant
455 if arg.include?('*') ? (/(^|\s|\*)const(\s(\w|\s)*)?\*(?!.*\*)/ =~ arg) : (/(^|\s)const(\s|$)/ =~ arg)
456 true
457 else
458 false
459 end
460 end
461
462 def divine_ptr_and_const(arg)
463 divination = {}
464
465 divination[:ptr?] = divine_ptr(arg)
466 divination[:const?] = divine_const(arg)
467
468 # an arg containing "const" after the last * is a constant pointer
469 divination[:const_ptr?] = /\*(?!.*\*)\s*const(\s|$)/ =~ arg ? true : false
470
471 divination
472 end
473
474 def clean_args(arg_list, parse_project)
475 if @local_as_void.include?(arg_list.strip) || arg_list.empty?
476 'void'
477 else
478 c = 0
479 # magically turn brackets into asterisks, also match for parentheses that come from macros
480 arg_list.gsub!(/(\w+)(?:\s*\[[^\[\]]*\])+/, '*\1')
481 # remove space to place asterisks with type (where they belong)
482 arg_list.gsub!(/\s+\*/, '*')
483 # pull asterisks away from arg to place asterisks with type (where they belong)
484 arg_list.gsub!(/\*(\w)/, '* \1')
485
486 # scan argument list for function pointers and replace them with custom types
487 arg_list.gsub!(/([\w\s\*]+)\(+([\w\s]*)\*[\*\s]*([\w\s]*)\s*\)+\s*\(((?:[\w\s\*]*,?)*)\s*\)*/) do |_m|
488 functype = "cmock_#{parse_project[:module_name]}_func_ptr#{parse_project[:typedefs].size + 1}"
489 funcret = Regexp.last_match(1).strip
490 funcdecl = Regexp.last_match(2).strip
491 funcname = Regexp.last_match(3).strip
492 funcargs = Regexp.last_match(4).strip
493 funconst = ''
494 if funcname.include? 'const'
495 funcname.gsub!('const', '').strip!
496 funconst = 'const '
497 end
498 if funcdecl != ''
499 funcdecl += ' '
500 end
501 parse_project[:typedefs] << "typedef #{funcret}(#{funcdecl}*#{functype})(#{funcargs});"
502 funcname = "cmock_arg#{c += 1}" if funcname.empty?
503 "#{functype} #{funconst}#{funcname}"
504 end
505
506 # scan argument list for function pointers with shorthand notation and replace them with custom types
507 arg_list.gsub!(/([\w\s\*]+)\s+(\w+)\s*\(((?:[\w\s\*]*,?)*)\s*\)*/) do |_m|
508 functype = "cmock_#{parse_project[:module_name]}_func_ptr#{parse_project[:typedefs].size + 1}"
509 funcret = Regexp.last_match(1).strip
510 funcname = Regexp.last_match(2).strip
511 funcargs = Regexp.last_match(3).strip
512 funconst = ''
513 if funcname.include? 'const'
514 funcname.gsub!('const', '').strip!
515 funconst = 'const '
516 end
517 parse_project[:typedefs] << "typedef #{funcret}(*#{functype})(#{funcargs});"
518 funcname = "cmock_arg#{c += 1}" if funcname.empty?
519 "#{functype} #{funconst}#{funcname}"
520 end
521
522 # automatically name unnamed arguments (those that only had a type)
523 arg_list.split(/\s*,\s*/).map do |arg|
524 parts = (arg.split - ['struct', 'union', 'enum', 'const', 'const*'])
525 if (parts.size < 2) || (parts[-1][-1].chr == '*') || @standards.include?(parts[-1])
526 "#{arg} cmock_arg#{c += 1}"
527 else
528 arg
529 end
530 end.join(', ')
531 end
532 end
533
534 def parse_declaration(parse_project, declaration, namespace = [], classname = nil)
535 decl = {}
536 decl[:namespace] = namespace
537 decl[:class] = classname
538
539 regex_match = @declaration_parse_matcher.match(declaration)
540 raise "Failed parsing function declaration: '#{declaration}'" if regex_match.nil?
541
542 # grab argument list
543 args = regex_match[2].strip
544
545 # process function attributes, return type, and name
546 parsed = parse_type_and_name(regex_match[1])
547
548 # Record original name without scope prefix
549 decl[:unscoped_name] = parsed[:name]
550
551 # Prefix name with namespace scope (if any) and then class
552 decl[:name] = namespace.join('_')
553 unless classname.nil?
554 decl[:name] << '_' unless decl[:name].empty?
555 decl[:name] << classname
556 end
557 # Add original name to complete fully scoped name
558 decl[:name] << '_' unless decl[:name].empty?
559 decl[:name] << decl[:unscoped_name]
560
561 decl[:modifier] = parsed[:modifier]
562 unless parsed[:c_calling_convention].nil?
563 decl[:c_calling_convention] = parsed[:c_calling_convention]
564 end
565
566 rettype = parsed[:type]
567 rettype = 'void' if @local_as_void.include?(rettype.strip)
568 decl[:return] = { :type => rettype,
569 :name => 'cmock_to_return',
570 :str => "#{rettype} cmock_to_return",
571 :void? => (rettype == 'void'),
572 :ptr? => parsed[:ptr?] || false,
573 :const? => parsed[:const?] || false,
574 :const_ptr? => parsed[:const_ptr?] || false }
575
576 # remove default argument statements from mock definitions
577 args.gsub!(/=\s*[a-zA-Z0-9_\.]+\s*/, ' ')
578
579 # check for var args
580 if args =~ /\.\.\./
581 decl[:var_arg] = args.match(/[\w\s]*\.\.\./).to_s.strip
582 args = if args =~ /\,[\w\s]*\.\.\./
583 args.gsub!(/\,[\w\s]*\.\.\./, '')
584 else
585 'void'
586 end
587 else
588 decl[:var_arg] = nil
589 end
590 args = clean_args(args, parse_project)
591 decl[:args_string] = args
592 decl[:args] = parse_args(args)
593 decl[:args_call] = decl[:args].map { |a| a[:name] }.join(', ')
594 decl[:contains_ptr?] = decl[:args].inject(false) { |ptr, arg| arg[:ptr?] ? true : ptr }
595
596 if decl[:return][:type].nil? || decl[:name].nil? || decl[:args].nil? ||
597 decl[:return][:type].empty? || decl[:name].empty?
598 raise "Failed Parsing Declaration Prototype!\n" \
599 " declaration: '#{declaration}'\n" \
600 " modifier: '#{decl[:modifier]}'\n" \
601 " return: #{prototype_inspect_hash(decl[:return])}\n" \
602 " function: '#{decl[:name]}'\n" \
603 " args: #{prototype_inspect_array_of_hashes(decl[:args])}\n"
604 end
605
606 decl
607 end
608
609 def prototype_inspect_hash(hash)
610 pairs = []
611 hash.each_pair { |name, value| pairs << ":#{name} => #{"'" if value.class == String}#{value}#{"'" if value.class == String}" }
612 "{#{pairs.join(', ')}}"
613 end
614
615 def prototype_inspect_array_of_hashes(array)
616 hashes = []
617 array.each { |hash| hashes << prototype_inspect_hash(hash) }
618 case array.size
619 when 0
620 return '[]'
621 when 1
622 return "[#{hashes[0]}]"
623 else
624 return "[\n #{hashes.join("\n ")}\n ]\n"
625 end
626 end
627 end