Initial Revision
[ohcount] / ext / ohcount_native / escape_helper.rb
1 module EscapeHelper
2         # From Ruby, we are generating C code which will call pcre.
3         #
4         # This means that characters that are significant to the C parser or the pcre regular
5         # expression parser must be escaped multiple times, once for each layer of code that
6         # must evaluate it.
7         #
8         # For instance, suppose you want to represent a literal backslash in a regular expression.
9         # That means we must pass TWO backslashes (\\) to pcre.
10         # The two backslashes will be stored in a C string constant -- and to express two backslashes
11         # in a C string constant, we must use FOUR backslashes (\\\\).
12         # It gets even better. To express these four backslashes in Ruby, we must use a literal string
13         # that has EIGHT backslashes!
14         #
15         # This helper method exists to wade through all of this mess, adding the correct number of
16         # backslashes to many types of special characters.
17         #
18         # Some examples:
19         #
20         #   e('/*')     -> /\\\*      # * must be escaped because it has meaning to regular expression parser
21         #   e('"')      -> \\\"       # " must be escaped because it has meaning to the C string parser
22         #   e('\\')     -> \\\\\\\\   # \ must be multiply escaped because it has meaning to both C and regex
23         #
24         # If you really want to pass a regular expression operator to pcre (for instance, you want . to be
25         # the wildcard operator, not a literal period), then you should NOT use this helper, and you'll have to
26         # sort out your escaping on your own.
27         #
28         # Someday we'll move this whole product over to Regel and get rid of all this craziness.
29         def e(string)
30                 string.gsub(/\\/,'\\\\' * 4).gsub(/([\+\-\?\.\*\(\)\[\]])/, '\\\\' * 2 + '\1').gsub('"', '\\\\"')
31         end
32 end