-- ldoc/lang.lua
--
-- A "better" C/C++ comment parser for LDoc.
--
-- Copyright 2013 Daniel Silverstone <dsilvers@digital-scurf.org>
--
-- Permission is granted to use this under the same licence terms as
-- LDoc itself.
--

-- To use, place this in ldoc/lang.lua in your source-tree relative to where
-- you invoke LDoc.  This file deliberately does not contain documentation
-- comments and thus should not be picked up by accident.

-- This allows for C/C++ comments of the form:
--
-- /** This is a thingy.
--  *
--  * Here is thingy's description.
--  *
--  * @return Badgers
--  */

local pp = package.path
package.path = pp:gsub("%./%?%.lua;", "")
package.loaded['ldoc.lang'] = nil
local ll = require 'ldoc.lang'
package.path = pp

local class = require 'pl.class'
local stringx = require 'pl.stringx'

local cc_better = class(ll.cc._class)

local function find_pfx(s, common)
   return s:match("^([ *]*)")
end

local function max_pfx(s1, s2)
   if #s1 > #s2 then
      s1 = s1:sub(1, #s2)
   else
      s2 = s2:sub(1, #s1)
   end
   while s1 ~= s2 do
      s1 = s1:sub(1, -2)
      s2 = s2:sub(1, -2)
   end
   return s1
end

function cc_better:grab_block_comment(v,tok)
   v = v:gsub(self.block_comment .. " *",'')
   v = v:sub(1,-3)
   local lines = stringx.splitlines(v, true)

   if #lines > 1 then
      local checklines = {}
      for i = 2, #lines do
	 if lines[i] ~= lines[i]:match("^([ *]*)") then
	    checklines[#checklines+1] = lines[i]
	 end
      end
      if #checklines > 0 then
	 local common_pfx = checklines[1]:match("^([ *]*)")
	 for i = 1, #checklines do
	    local this_pfx = checklines[i]:match("^([ *]*)")
	    common_pfx = max_pfx(common_pfx, this_pfx)
	 end
	 for i = 2, #lines do
	    lines[i] = lines[i]:sub(#common_pfx + 1)
	 end
      end
   end

   v = table.concat(lines, "\n")
   return 'comment', v
end

ll.cc = cc_better()

return ll

