formatc.lua 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 {
  26. 'tokens',
  27. -- Comment of form /* ... */
  28. comment = Ct(P '/*' * C((V 'newline' + (1 - P '*/')) ^ 0) * P '*/' * Cc 'comment'),
  29. -- Single line comment
  30. line_comment = Ct(P '//' * C((1 - V 'newline') ^ 0) * Cc 'comment_line'),
  31. -- Single platform independent line break which increments line number
  32. newline = (P '\r\n' + P '\n\r' + S '\r\n') * (Cp() * Carg(1)) / function(pos, state)
  33. state.line = state.line + 1
  34. state.line_start = pos
  35. end,
  36. -- Line continuation
  37. line_extend = Ct(C(P [[\]] * V 'newline') * Cc 'line_extend'),
  38. -- Whitespace of any length (includes newlines)
  39. whitespace = Ct(C((S ' \t' + V 'newline') ^ 1) * Cc 'whitespace'),
  40. -- Special form of #include with filename followed in angled brackets (matches 3 tokens)
  41. include = Ct(C(P '#include') * Cc 'preprocessor') * Ct(C(S ' \t' ^ 1) * Cc 'whitespace') * Ct(
  42. C(P '<' * (1 - P '>') ^ 1 * P '>') * Cc 'string'
  43. ),
  44. -- Preprocessor instruction
  45. preprocessor = V 'include'
  46. + Ct(
  47. C(
  48. P '#'
  49. * P ' ' ^ 0
  50. * (P 'define' + P 'elif' + P 'else' + P 'endif' + P '#' + P 'error' + P 'ifdef' + P 'ifndef' + P 'if' + P 'import' + P 'include' + P 'line' + P 'pragma' + P 'undef' + P 'using' + P 'pragma')
  51. * #S ' \r\n\t'
  52. ) * Cc 'preprocessor'
  53. ),
  54. -- Identifier of form [a-zA-Z_][a-zA-Z0-9_]*
  55. identifier = Ct(C(R('az', 'AZ', '__') * R('09', 'az', 'AZ', '__') ^ 0) * Cc 'identifier'),
  56. -- Single character in a string
  57. sstring_char = R('\001&', '([', ']\255') + (P '\\' * S [[ntvbrfa\?'"0x]]),
  58. dstring_char = R('\001!', '#[', ']\255') + (P '\\' * S [[ntvbrfa\?'"0x]]),
  59. -- String literal
  60. string = Ct(
  61. C(
  62. P "'" * (V 'sstring_char' + P '"') ^ 0 * P "'"
  63. + P '"' * (V 'dstring_char' + P "'") ^ 0 * P '"'
  64. ) * Cc 'string'
  65. ),
  66. -- Operator
  67. operator = Ct(
  68. C(
  69. P '>>='
  70. + P '<<='
  71. + P '...'
  72. + P '::'
  73. + P '<<'
  74. + P '>>'
  75. + P '<='
  76. + P '>='
  77. + P '=='
  78. + P '!='
  79. + P '||'
  80. + P '&&'
  81. + P '++'
  82. + P '--'
  83. + P '->'
  84. + P '+='
  85. + P '-='
  86. + P '*='
  87. + P '/='
  88. + P '|='
  89. + P '&='
  90. + P '^='
  91. + S '+-*/=<>%^|&.?:!~,'
  92. ) * Cc 'operator'
  93. ),
  94. -- Misc. char (token type is the character itself)
  95. char = Ct(C(S '[]{}();') / function(x)
  96. return x, x
  97. end),
  98. -- Hex, octal or decimal number
  99. int = Ct(
  100. C((P '0x' * R('09', 'af', 'AF') ^ 1) + (P '0' * R '07' ^ 0) + R '09' ^ 1) * Cc 'integer'
  101. ),
  102. -- Floating point number
  103. f_exponent = S 'eE' + S '+-' ^ -1 * R '09' ^ 1,
  104. f_terminator = S 'fFlL',
  105. float = Ct(
  106. C(
  107. R '09' ^ 1 * V 'f_exponent' * V 'f_terminator' ^ -1
  108. + R '09' ^ 0 * P '.' * R '09' ^ 1 * V 'f_exponent' ^ -1 * V 'f_terminator' ^ -1
  109. + R '09' ^ 1 * P '.' * R '09' ^ 0 * V 'f_exponent' ^ -1 * V 'f_terminator' ^ -1
  110. ) * Cc 'float'
  111. ),
  112. -- Any token
  113. token = V 'comment'
  114. + V 'line_comment'
  115. + V 'identifier'
  116. + V 'whitespace'
  117. + V 'line_extend'
  118. + V 'preprocessor'
  119. + V 'string'
  120. + V 'char'
  121. + V 'operator'
  122. + V 'float'
  123. + V 'int',
  124. -- Error for when nothing else matches
  125. error = (Cp() * C(P(1) ^ -8) * Carg(1)) / function(pos, where, state)
  126. error(
  127. ("Tokenising error on line %i, position %i, near '%s'"):format(
  128. state.line,
  129. pos - state.line_start + 1,
  130. where
  131. )
  132. )
  133. end,
  134. -- Match end of input or throw error
  135. finish = -P(1) + V 'error',
  136. -- Match stream of tokens into a table
  137. tokens = Ct(V 'token' ^ 0) * V 'finish',
  138. }
  139. local function TokeniseC(str)
  140. return tokens:match(str, 1, { line = 1, line_start = 1 })
  141. end
  142. local function set(t)
  143. local s = {}
  144. for _, v in ipairs(t) do
  145. s[v] = true
  146. end
  147. return s
  148. end
  149. local C_keywords = set { -- luacheck: ignore
  150. 'break',
  151. 'case',
  152. 'char',
  153. 'const',
  154. 'continue',
  155. 'default',
  156. 'do',
  157. 'double',
  158. 'else',
  159. 'enum',
  160. 'extern',
  161. 'float',
  162. 'for',
  163. 'goto',
  164. 'if',
  165. 'int',
  166. 'long',
  167. 'register',
  168. 'return',
  169. 'short',
  170. 'signed',
  171. 'sizeof',
  172. 'static',
  173. 'struct',
  174. 'switch',
  175. 'typedef',
  176. 'union',
  177. 'unsigned',
  178. 'void',
  179. 'volatile',
  180. 'while',
  181. }
  182. -- Very primitive C formatter that tries to put "things" inside braces on one
  183. -- line. This is a step done after preprocessing the C source to ensure that
  184. -- the duplicate line detector can more reliably pick out identical declarations.
  185. --
  186. -- an example:
  187. -- struct mystruct
  188. -- {
  189. -- int a;
  190. -- int b;
  191. -- };
  192. --
  193. -- would become:
  194. -- struct mystruct { int a; int b; };
  195. --
  196. -- The first one will have a lot of false positives (the line '{' for
  197. -- example), the second one is more unique.
  198. --- @param string
  199. --- @return string
  200. local function formatc(str)
  201. local toks = TokeniseC(str)
  202. local result = {}
  203. local block_level = 0
  204. local allow_one_nl = false
  205. local end_at_brace = false
  206. for _, token in ipairs(toks) do
  207. local typ = token[2]
  208. if typ == '{' then
  209. block_level = block_level + 1
  210. elseif typ == '}' then
  211. block_level = block_level - 1
  212. if block_level == 0 and end_at_brace then
  213. -- if we're not inside a block, we're at the basic statement level,
  214. -- and ';' indicates we're at the end of a statement, so we put end
  215. -- it with a newline.
  216. token[1] = token[1] .. '\n'
  217. end_at_brace = false
  218. end
  219. elseif typ == 'identifier' then
  220. -- static and/or inline usually indicate an inline header function,
  221. -- which has no trailing ';', so we have to add a newline after the
  222. -- '}' ourselves.
  223. local tok = token[1]
  224. if tok == 'static' or tok == 'inline' or tok == '__inline' then
  225. end_at_brace = true
  226. end
  227. elseif typ == 'preprocessor' then
  228. -- preprocessor directives don't end in ';' but need their newline, so
  229. -- we're going to allow the next newline to pass.
  230. allow_one_nl = true
  231. elseif typ == ';' then
  232. if block_level == 0 then
  233. -- if we're not inside a block, we're at the basic statement level,
  234. -- and ';' indicates we're at the end of a statement, so we put end
  235. -- it with a newline.
  236. token[1] = ';\n'
  237. end_at_brace = false
  238. end
  239. elseif typ == 'whitespace' then
  240. -- replace all whitespace by one space
  241. local repl = ' '
  242. -- except when allow_on_nl is true and there's a newline in the whitespace
  243. if string.find(token[1], '[\r\n]+') and allow_one_nl == true then
  244. -- in that case we replace all whitespace by one newline
  245. repl = '\n'
  246. allow_one_nl = false
  247. end
  248. token[1] = string.gsub(token[1], '%s+', repl)
  249. end
  250. result[#result + 1] = token[1]
  251. end
  252. return table.concat(result)
  253. end
  254. -- standalone operation (very handy for debugging)
  255. local function standalone(...) -- luacheck: ignore
  256. local Preprocess = require('preprocess')
  257. Preprocess.add_to_include_path('./../../src')
  258. Preprocess.add_to_include_path('./../../build/include')
  259. Preprocess.add_to_include_path('./../../.deps/usr/include')
  260. local raw = Preprocess.preprocess('', arg[1])
  261. local formatted
  262. if #arg == 2 and arg[2] == 'no' then
  263. formatted = raw
  264. else
  265. formatted = formatc(raw)
  266. end
  267. print(formatted)
  268. end
  269. -- uncomment this line (and comment the `return`) for standalone debugging
  270. -- example usage:
  271. -- ../../.deps/usr/bin/luajit formatc.lua ../../include/fileio.h.generated.h
  272. -- ../../.deps/usr/bin/luajit formatc.lua /usr/include/malloc.h
  273. -- standalone(...)
  274. return formatc