-- $LastChangedDate: 2010-05-25 21:26:05 -0400 (Tue, 25 May 2010) $
-- LEGAL: COPYRIGHT (C) 2010 JIM E. BROOKS WWW.PALOMINO3D.ORG
-- Find programming mistakes in Lua scripts.
-- Usage: lint.lua luaScript(s)

function Error( msg, filename, lineNum )
    print( "ERROR[checks.lua] " .. msg )
    print( "ERROR[checks.lua] " .. filename .. ":" .. tostring(lineNum) )
    os.exit( 1 )
end

-- Check a Lua script.
function Check( filename )
    -- Open file.
    io.input( filename )  -- throws exception

    -- For each line.
    lineNum = 1
    while true do
        -- Read next line else stop.
        line = io.read( "*line" )
        if not line then
            break
        end

        -- If this line has the special comment "@check" then ignore it.
        if ( not string.match( line, "@lint" ) ) then
            -- Remove comments.
            line = string.gsub( line, "%-%-.*$", "" )

            -- Do checks.

            -- Catch mistake: self.Func() which should have a colon: self:Func()  @lint
            if ( string.match( line, "self%.[%a_][%w_]*%(" ) ) then
                Error( "Found self.Func() which should have a colon: self:Func()", filename, lineNum )  -- @lint
            end
        end

        lineNum = lineNum + 1
    end
end

-- Parse args.
if ( #arg == 0 ) then
    print( "Finds programming mistakes in Lua scripts." )
    print( "Usage: lint.lua luaScript(s)" )
    os.exit( 1 )
else
    -- For each arg/file.
    local argIdx = 1
    while argIdx <= #arg do
        -- Check file.
        local filename = arg[argIdx]
        Check( filename )

        -- Next file.
        argIdx = argIdx + 1
    end
end

-- Ok.
os.exit( 0 )
