formatc.lua 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. --[[ Copyright (c) 2009 Peter "Corsix" Cawley
  2. Permission is hereby granted, free of charge, to any person obtaining a copy of
  3. this software and associated documentation files (the "Software"), to deal in
  4. the Software without restriction, including without limitation the rights to
  5. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  6. of the Software, and to permit persons to whom the Software is furnished to do
  7. so, subject to the following conditions:
  8. The above copyright notice and this permission notice shall be included in all
  9. copies or substantial portions of the Software.
  10. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  11. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  13. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  14. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  15. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  16. SOFTWARE. --]]
  17. -- this C parser was taken from Corsix-TH, I'm sure this could be done much
  18. -- better (i.e.: I think everything I do could be substitutions made with LPeg
  19. -- during parsing), but I've just learned enough basic LPeg to make this
  20. -- work.
  21. -- see: http://lua-users.org/wiki/LpegRecipes
  22. local lpeg = require "lpeg"
  23. local C, P, R, S, V = lpeg.C, lpeg.P, lpeg.R, lpeg.S, lpeg.V
  24. local Carg, Cc, Cp, Ct = lpeg.Carg, lpeg.Cc, lpeg.Cp, lpeg.Ct
  25. local tokens = P { "tokens";
  26. -- Comment of form /* ... */
  27. comment = Ct(P"/*" * C((V"newline" + (1 - P"*/"))^0) * P"*/" * Cc"comment"),
  28. -- Single line comment
  29. line_comment = Ct(P"//" * C((1 - V"newline")^0) * Cc"comment_line"),
  30. -- Single platform independent line break which increments line number
  31. newline = (P"\r\n" + P"\n\r" + S"\r\n") * (Cp() * Carg(1)) / function(pos, state)
  32. state.line = state.line + 1
  33. state.line_start = pos
  34. end,
  35. -- Line continuation
  36. line_extend = Ct(C(P[[\]] * V"newline") * Cc"line_extend"),
  37. -- Whitespace of any length (includes newlines)
  38. whitespace = Ct(C((S" \t" + V"newline")^1) * Cc"whitespace"),
  39. -- Special form of #include with filename followed in angled brackets (matches 3 tokens)
  40. include = Ct(C(P"#include") * Cc"preprocessor") *
  41. Ct(C(S" \t"^1) * Cc"whitespace") *
  42. Ct(C(P"<" * (1 - P">")^1 * P">") * Cc"string"),
  43. -- Preprocessor instruction
  44. preprocessor = V"include" +
  45. Ct(C(P"#" * P" "^0 * ( P"define" + P"elif" + P"else" + P"endif" + P"#" +
  46. P"error" + P"ifdef" + P"ifndef" + P"if" + P"import" +
  47. P"include" + P"line" + P"pragma" + P"undef" + P"using" +
  48. P"pragma"
  49. ) * #S" \r\n\t") * Cc"preprocessor"),
  50. -- Identifier of form [a-zA-Z_][a-zA-Z0-9_]*
  51. identifier = Ct(C(R("az","AZ","__") * R("09","az","AZ","__")^0) * Cc"identifier"),
  52. -- Single character in a string
  53. sstring_char = R("\001&","([","]\255") + (P"\\" * S[[ntvbrfa\?'"0x]]),
  54. dstring_char = R("\001!","#[","]\255") + (P"\\" * S[[ntvbrfa\?'"0x]]),
  55. -- String literal
  56. string = Ct(C(P"'" * (V"sstring_char" + P'"')^0 * P"'" +
  57. P'"' * (V"dstring_char" + P"'")^0 * P'"') * Cc"string"),
  58. -- Operator
  59. operator = Ct(C(P">>=" + P"<<=" + P"..." +
  60. P"::" + P"<<" + P">>" + P"<=" + P">=" + P"==" + P"!=" +
  61. P"||" + P"&&" + P"++" + P"--" + P"->" + P"+=" + P"-=" +
  62. P"*=" + P"/=" + P"|=" + P"&=" + P"^=" + S"+-*/=<>%^|&.?:!~,") * Cc"operator"),
  63. -- Misc. char (token type is the character itself)
  64. char = Ct(C(S"[]{}();") / function(x) return x, x end),
  65. -- Hex, octal or decimal number
  66. int = Ct(C((P"0x" * R("09","af","AF")^1) + (P"0" * R"07"^0) + R"09"^1) * Cc"integer"),
  67. -- Floating point number
  68. f_exponent = S"eE" + S"+-"^-1 * R"09"^1,
  69. f_terminator = S"fFlL",
  70. float = Ct(C(
  71. R"09"^1 * V"f_exponent" * V"f_terminator"^-1 +
  72. R"09"^0 * P"." * R"09"^1 * V"f_exponent"^-1 * V"f_terminator"^-1 +
  73. R"09"^1 * P"." * R"09"^0 * V"f_exponent"^-1 * V"f_terminator"^-1
  74. ) * Cc"float"),
  75. -- Any token
  76. token = V"comment" +
  77. V"line_comment" +
  78. V"identifier" +
  79. V"whitespace" +
  80. V"line_extend" +
  81. V"preprocessor" +
  82. V"string" +
  83. V"char" +
  84. V"operator" +
  85. V"float" +
  86. V"int",
  87. -- Error for when nothing else matches
  88. error = (Cp() * C(P(1) ^ -8) * Carg(1)) / function(pos, where, state)
  89. error(("Tokenising error on line %i, position %i, near '%s'")
  90. :format(state.line, pos - state.line_start + 1, where))
  91. end,
  92. -- Match end of input or throw error
  93. finish = -P(1) + V"error",
  94. -- Match stream of tokens into a table
  95. tokens = Ct(V"token" ^ 0) * V"finish",
  96. }
  97. local function TokeniseC(str)
  98. return tokens:match(str, 1, {line = 1, line_start = 1})
  99. end
  100. local function set(t)
  101. local s = {}
  102. for _, v in ipairs(t) do
  103. s[v] = true
  104. end
  105. return s
  106. end
  107. local C_keywords = set { -- luacheck: ignore
  108. "break", "case", "char", "const", "continue", "default", "do", "double",
  109. "else", "enum", "extern", "float", "for", "goto", "if", "int", "long",
  110. "register", "return", "short", "signed", "sizeof", "static", "struct",
  111. "switch", "typedef", "union", "unsigned", "void", "volatile", "while",
  112. }
  113. -- Very primitive C formatter that tries to put "things" inside braces on one
  114. -- line. This is a step done after preprocessing the C source to ensure that
  115. -- the duplicate line detecter can more reliably pick out identical declarations.
  116. --
  117. -- an example:
  118. -- struct mystruct
  119. -- {
  120. -- int a;
  121. -- int b;
  122. -- };
  123. --
  124. -- would become:
  125. -- struct mystruct { int a; int b; };
  126. --
  127. -- The first one will have a lot of false positives (the line '{' for
  128. -- example), the second one is more unique.
  129. local function formatc(str)
  130. local toks = TokeniseC(str)
  131. local result = {}
  132. local block_level = 0
  133. local allow_one_nl = false
  134. local end_at_brace = false
  135. for _, token in ipairs(toks) do
  136. local typ = token[2]
  137. if typ == '{' then
  138. block_level = block_level + 1
  139. elseif typ == '}' then
  140. block_level = block_level - 1
  141. if block_level == 0 and end_at_brace then
  142. -- if we're not inside a block, we're at the basic statement level,
  143. -- and ';' indicates we're at the end of a statement, so we put end
  144. -- it with a newline.
  145. token[1] = token[1] .. "\n"
  146. end_at_brace = false
  147. end
  148. elseif typ == 'identifier' then
  149. -- static and/or inline usually indicate an inline header function,
  150. -- which has no trailing ';', so we have to add a newline after the
  151. -- '}' ourselves.
  152. local tok = token[1]
  153. if tok == 'static' or tok == 'inline' or tok == '__inline' then
  154. end_at_brace = true
  155. end
  156. elseif typ == 'preprocessor' then
  157. -- preprocessor directives don't end in ';' but need their newline, so
  158. -- we're going to allow the next newline to pass.
  159. allow_one_nl = true
  160. elseif typ == ';' then
  161. if block_level == 0 then
  162. -- if we're not inside a block, we're at the basic statement level,
  163. -- and ';' indicates we're at the end of a statement, so we put end
  164. -- it with a newline.
  165. token[1] = ";\n"
  166. end
  167. elseif typ == 'whitespace' then
  168. -- replace all whitespace by one space
  169. local repl = " "
  170. -- except when allow_on_nl is true and there's a newline in the whitespace
  171. if string.find(token[1], "[\r\n]+") and allow_one_nl == true then
  172. -- in that case we replace all whitespace by one newline
  173. repl = "\n"
  174. allow_one_nl = false
  175. end
  176. token[1] = string.gsub(token[1], "%s+", repl)
  177. end
  178. result[#result + 1] = token[1]
  179. end
  180. return table.concat(result)
  181. end
  182. -- standalone operation (very handy for debugging)
  183. local function standalone(...) -- luacheck: ignore
  184. local Preprocess = require("preprocess")
  185. Preprocess.add_to_include_path('./../../src')
  186. Preprocess.add_to_include_path('./../../build/include')
  187. Preprocess.add_to_include_path('./../../.deps/usr/include')
  188. local raw = Preprocess.preprocess('', arg[1])
  189. local formatted
  190. if #arg == 2 and arg[2] == 'no' then
  191. formatted = raw
  192. else
  193. formatted = formatc(raw)
  194. end
  195. print(formatted)
  196. end
  197. -- uncomment this line (and comment the `return`) for standalone debugging
  198. -- example usage:
  199. -- ../../.deps/usr/bin/luajit formatc.lua ../../include/fileio.h.generated.h
  200. -- ../../.deps/usr/bin/luajit formatc.lua /usr/include/malloc.h
  201. -- standalone(...)
  202. return formatc