build: Update compiler flags and addressing discovered warnings

Change-Id: I95e89871e1bcd15ee8e8b3fc181861e40a6b127b
diff --git a/.waf-tools/default-compiler-flags.py b/.waf-tools/default-compiler-flags.py
index ce19594..9f15fcc 100644
--- a/.waf-tools/default-compiler-flags.py
+++ b/.waf-tools/default-compiler-flags.py
@@ -1,49 +1,57 @@
 # -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
 
-from waflib import Logs, Configure
+from waflib import Logs, Configure, Utils
 
 def options(opt):
     opt.add_option('--debug', '--with-debug', action='store_true', default=False, dest='debug',
                    help='''Compile in debugging mode without optimizations (-O0 or -Og)''')
 
 def configure(conf):
-    areCustomCxxflagsPresent = (len(conf.env.CXXFLAGS) > 0)
-    defaultFlags = ['-std=c++0x', '-std=c++11',
-                    '-stdlib=libc++',   # clang on OSX < 10.9 by default uses gcc's
-                                        # libstdc++, which is not C++11 compatible
-                    '-pedantic', '-Wall']
+    cxx = conf.env['CXX_NAME'] # CXX_NAME represents generic name of the compiler
+    if cxx == 'gcc':
+        flags = GccFlags()
+    elif cxx == 'clang':
+        flags = ClangFlags()
+    else:
+        flags = CompilerFlags()
+        Logs.warn('The code has not yet been tested with %s compiler' % cxx)
 
+    areCustomCxxflagsPresent = (len(conf.env.CXXFLAGS) > 0)
+
+    # General flags are always applied (e.g., selecting C++11 mode)
+    generalFlags = flags.getGeneralFlags(conf)
+    conf.add_supported_cxxflags(generalFlags['CXXFLAGS'])
+    conf.add_supported_linkflags(generalFlags['LINKFLAGS'])
+    conf.env.DEFINES += generalFlags['DEFINES']
+
+    # Debug or optimized CXXFLAGS and LINKFLAGS are applied only if the
+    # corresponding environment variables are not set.
+    # DEFINES are always applied.
     if conf.options.debug:
-        conf.define('_DEBUG', 1)
-        defaultFlags += ['-O0',
-                         '-Og', # gcc >= 4.8
-                         '-g3',
-                         '-fcolor-diagnostics', # clang
-                         '-fdiagnostics-color', # gcc >= 4.9
-                         '-Werror',
-                         '-Wno-error=deprecated-register',
-                        ]
+        extraFlags = flags.getDebugFlags(conf)
         if areCustomCxxflagsPresent:
-            missingFlags = [x for x in defaultFlags if x not in conf.env.CXXFLAGS]
+            missingFlags = [x for x in extraFlags['CXXFLAGS'] if x not in conf.env.CXXFLAGS]
             if len(missingFlags) > 0:
                 Logs.warn("Selected debug mode, but CXXFLAGS is set to a custom value '%s'"
                           % " ".join(conf.env.CXXFLAGS))
                 Logs.warn("Default flags '%s' are not activated" % " ".join(missingFlags))
-        else:
-            conf.add_supported_cxxflags(defaultFlags)
     else:
-        defaultFlags += ['-O2', '-g']
-        if not areCustomCxxflagsPresent:
-            conf.add_supported_cxxflags(defaultFlags)
+        extraFlags = flags.getOptimizedFlags(conf)
 
-    # clang on OSX < 10.9 by default uses gcc's libstdc++, which is not C++11 compatible
-    conf.add_supported_linkflags(['-stdlib=libc++'])
+    if not areCustomCxxflagsPresent:
+        conf.add_supported_cxxflags(extraFlags['CXXFLAGS'])
+        conf.add_supported_linkflags(extraFlags['LINKFLAGS'])
+
+    conf.env.DEFINES += extraFlags['DEFINES']
 
 @Configure.conf
 def add_supported_cxxflags(self, cxxflags):
     """
     Check which cxxflags are supported by compiler and add them to env.CXXFLAGS variable
     """
+    if len(cxxflags) == 0:
+        return
+
     self.start_msg('Checking supported CXXFLAGS')
 
     supportedFlags = []
@@ -59,6 +67,9 @@
     """
     Check which linkflags are supported by compiler and add them to env.LINKFLAGS variable
     """
+    if len(linkflags) == 0:
+        return
+
     self.start_msg('Checking supported LINKFLAGS')
 
     supportedFlags = []
@@ -68,3 +79,105 @@
 
     self.end_msg(' '.join(supportedFlags))
     self.env.LINKFLAGS = supportedFlags + self.env.LINKFLAGS
+
+
+class CompilerFlags(object):
+    def getGeneralFlags(self, conf):
+        """Get dict of CXXFLAGS, LINKFLAGS, and DEFINES that are always needed"""
+        return {'CXXFLAGS': [], 'LINKFLAGS': [], 'DEFINES': []}
+
+    def getDebugFlags(self, conf):
+        """Get dict of CXXFLAGS, LINKFLAGS, and DEFINES that are needed only in debug mode"""
+        return {'CXXFLAGS': [], 'LINKFLAGS': [], 'DEFINES': ['_DEBUG']}
+
+    def getOptimizedFlags(self, conf):
+        """Get dict of CXXFLAGS, LINKFLAGS, and DEFINES that are needed only in optimized mode"""
+        return {'CXXFLAGS': [], 'LINKFLAGS': [], 'DEFINES': ['NDEBUG']}
+
+class GccBasicFlags(CompilerFlags):
+    """
+    This class defines basic flags that work for both gcc and clang compilers
+    """
+    def getDebugFlags(self, conf):
+        flags = super(GccBasicFlags, self).getDebugFlags(conf)
+        flags['CXXFLAGS'] += ['-O0',
+                              '-g3',
+                              '-pedantic',
+                              '-Wall',
+                              '-Wextra',
+                              '-Werror',
+                              '-Wno-unused-parameter',
+                              '-Wno-error=maybe-uninitialized', # Bug #1615
+                              ]
+        return flags
+
+    def getOptimizedFlags(self, conf):
+        flags = super(GccBasicFlags, self).getOptimizedFlags(conf)
+        flags['CXXFLAGS'] += ['-O2',
+                              '-g',
+                              '-pedantic',
+                              '-Wall',
+                              '-Wextra',
+                              '-Wno-unused-parameter',
+                              ]
+        return flags
+
+class GccFlags(GccBasicFlags):
+    def getGeneralFlags(self, conf):
+        flags = super(GccFlags, self).getGeneralFlags(conf)
+        version = tuple(int(i) for i in conf.env['CC_VERSION'])
+        if version < (4, 6, 0):
+            conf.fatal('The version of gcc you are using (%s) is too old.\n' %
+                       '.'.join(conf.env['CC_VERSION']) +
+                       'The minimum supported gcc version is 4.6.0.')
+        elif version < (4, 7, 0):
+            flags['CXXFLAGS'] += ['-std=c++0x']
+        else:
+            flags['CXXFLAGS'] += ['-std=c++11']
+        if version < (4, 8, 0):
+            flags['DEFINES'] += ['_GLIBCXX_USE_NANOSLEEP'] # Bug #2499
+        return flags
+
+    def getDebugFlags(self, conf):
+        flags = super(GccFlags, self).getDebugFlags(conf)
+        version = tuple(int(i) for i in conf.env['CC_VERSION'])
+        if version < (5, 1, 0):
+            flags['CXXFLAGS'] += ['-Wno-missing-field-initializers']
+        flags['CXXFLAGS'] += ['-Og', # gcc >= 4.8
+                              '-fdiagnostics-color', # gcc >= 4.9
+                              ]
+        return flags
+
+    def getOptimizedFlags(self, conf):
+        flags = super(GccFlags, self).getOptimizedFlags(conf)
+        version = tuple(int(i) for i in conf.env['CC_VERSION'])
+        if version < (5, 1, 0):
+            flags['CXXFLAGS'] += ['-Wno-missing-field-initializers']
+        flags['CXXFLAGS'] += ['-fdiagnostics-color'] # gcc >= 4.9
+        return flags
+
+class ClangFlags(GccBasicFlags):
+    def getGeneralFlags(self, conf):
+        flags = super(ClangFlags, self).getGeneralFlags(conf)
+        flags['CXXFLAGS'] += ['-std=c++11']
+        if Utils.unversioned_sys_platform() == 'darwin':
+            flags['CXXFLAGS'] += ['-stdlib=libc++']
+            flags['LINKFLAGS'] += ['-stdlib=libc++']
+        return flags
+
+    def getDebugFlags(self, conf):
+        flags = super(ClangFlags, self).getDebugFlags(conf)
+        flags['CXXFLAGS'] += ['-fcolor-diagnostics',
+                              '-Wno-unused-local-typedef', # Bugs #2657 and #3209
+                              '-Wno-error=unneeded-internal-declaration', # Bug #1588
+                              '-Wno-error=deprecated-register',
+                              '-Wno-error=keyword-macro', # Bug #3235
+                              ]
+        return flags
+
+    def getOptimizedFlags(self, conf):
+        flags = super(ClangFlags, self).getOptimizedFlags(conf)
+        flags['CXXFLAGS'] += ['-fcolor-diagnostics',
+                              '-Wno-unused-local-typedef', # Bugs #2657 and #3209
+                              ]
+        return flags
diff --git a/src/storage/index.cpp b/src/storage/index.cpp
index 2bf17ac..572dc97 100644
--- a/src/storage/index.cpp
+++ b/src/storage/index.cpp
@@ -56,7 +56,7 @@
   return true;
 }
 
-Index::Index(const size_t nMaxPackets)
+Index::Index(size_t nMaxPackets)
   : m_maxPackets(nMaxPackets)
   , m_size(0)
 {
@@ -64,7 +64,7 @@
 
 
 bool
-Index::insert(const Data& data, const int64_t id)
+Index::insert(const Data& data, int64_t id)
 {
   if (isFull())
     throw Error("The Index is Full. Cannot Insert Any Data!");
@@ -76,7 +76,7 @@
 }
 
 bool
-Index::insert(const Name& fullName, const int64_t id,
+Index::insert(const Name& fullName, int64_t id,
               const ndn::ConstBufferPtr& keyLocatorHash)
 {
   if (isFull())
@@ -225,7 +225,7 @@
   return std::make_pair(0, Name());
 }
 
-Index::Entry::Entry(const Data& data, const int64_t id)
+Index::Entry::Entry(const Data& data, int64_t id)
   : m_name(data.getFullName())
   , m_id(id)
 {
@@ -234,7 +234,7 @@
     m_keyLocatorHash = computeKeyLocatorHash(signature.getKeyLocator());
 }
 
-Index::Entry::Entry(const Name& fullName, const KeyLocator& keyLocator, const int64_t id)
+Index::Entry::Entry(const Name& fullName, const KeyLocator& keyLocator, int64_t id)
   : m_name(fullName)
   , m_keyLocatorHash(computeKeyLocatorHash(keyLocator))
   , m_id(id)
@@ -242,7 +242,7 @@
 }
 
 Index::Entry::Entry(const Name& fullName,
-                    const ndn::ConstBufferPtr& keyLocatorHash, const int64_t id)
+                    const ndn::ConstBufferPtr& keyLocatorHash, int64_t id)
   : m_name(fullName)
   , m_keyLocatorHash(keyLocatorHash)
   , m_id(id)
diff --git a/src/storage/index.hpp b/src/storage/index.hpp
index ee8eca4..51d51b2 100644
--- a/src/storage/index.hpp
+++ b/src/storage/index.hpp
@@ -63,12 +63,12 @@
     /**
      * @brief construct Entry by data and id number
      */
-    Entry(const Data& data, const int64_t id);
+    Entry(const Data& data, int64_t id);
 
     /**
      * @brief construct Entry by fullName, keyLocator and id number
      */
-    Entry(const Name& fullName, const KeyLocator& keyLocator, const int64_t id);
+    Entry(const Name& fullName, const KeyLocator& keyLocator, int64_t id);
 
     /**
      * @brief construct Entry by fullName, keyLocatorHash and id number
@@ -76,7 +76,7 @@
      * @param  keyLocatorHash  keyLocator hashed by sha256
      * @param  id              record ID from database
      */
-    Entry(const Name& fullName, const ndn::ConstBufferPtr& keyLocatorHash, const int64_t id);
+    Entry(const Name& fullName, const ndn::ConstBufferPtr& keyLocatorHash, int64_t id);
 
     /**
      *  @brief implicit construct Entry by full name
@@ -106,7 +106,7 @@
     /**
      *  @brief get record ID from database
      */
-    const int64_t
+    int64_t
     getId() const
     {
       return m_id;
@@ -148,7 +148,7 @@
 
 public:
   explicit
-  Index(const size_t nMaxPackets);
+  Index(size_t nMaxPackets);
 
   /**
    *  @brief insert entries into index
@@ -156,7 +156,7 @@
    *  @param  id      obtained from database
    */
   bool
-  insert(const Data& data, const int64_t id);
+  insert(const Data& data, int64_t id);
 
   /**
    *  @brief insert entries into index
@@ -164,7 +164,7 @@
    *  @param  id      obtained from database
    */
   bool
-  insert(const Name& fullName, const int64_t id,
+  insert(const Name& fullName, int64_t id,
          const ndn::ConstBufferPtr& keyLocatorHash);
 
   /**
@@ -198,7 +198,7 @@
   static const ndn::ConstBufferPtr
   computeKeyLocatorHash(const KeyLocator& keyLocator);
 
-  const size_t
+  size_t
   size() const
   {
     return m_size;
diff --git a/tests/unit/index.cpp b/tests/unit/index.cpp
index f2cf919..ca96536 100644
--- a/tests/unit/index.cpp
+++ b/tests/unit/index.cpp
@@ -57,10 +57,10 @@
     return *m_interest;
   }
 
-  uint64_t
+  int
   find()
   {
-    std::pair<int,Name> found = m_index.find(*m_interest);
+    std::pair<int, Name> found = m_index.find(*m_interest);
     return found.first;
   }
 
diff --git a/tests/unit/repo-storage.cpp b/tests/unit/repo-storage.cpp
index 9157115..61632ad 100644
--- a/tests/unit/repo-storage.cpp
+++ b/tests/unit/repo-storage.cpp
@@ -53,7 +53,7 @@
     }
 
   // check size directly with the storage (repo doesn't have interface yet)
-  BOOST_CHECK_EQUAL(this->store->size(), this->data.size());
+  BOOST_CHECK_EQUAL(this->store->size(), static_cast<int64_t>(this->data.size()));
 
   // Read
   for (typename T::InterestContainer::iterator i = this->interests.begin();
diff --git a/tests/unit/sqlite-handle.cpp b/tests/unit/sqlite-handle.cpp
index 59c5977..d493e3d 100644
--- a/tests/unit/sqlite-handle.cpp
+++ b/tests/unit/sqlite-handle.cpp
@@ -52,7 +52,7 @@
       this->idToDataMap.insert(std::make_pair(id, *i));
       ids.push_back(id);
     }
-  BOOST_CHECK_EQUAL(this->handle->size(), this->data.size());
+  BOOST_CHECK_EQUAL(this->handle->size(), static_cast<int64_t>(this->data.size()));
 
   std::random_shuffle(ids.begin(), ids.end());
 
@@ -63,7 +63,7 @@
     BOOST_REQUIRE(this->idToDataMap.count(*i) > 0);
     BOOST_CHECK_EQUAL(*this->idToDataMap[*i], *retrievedData);
   }
-  BOOST_CHECK_EQUAL(this->handle->size(), this->data.size());
+  BOOST_CHECK_EQUAL(this->handle->size(), static_cast<int64_t>(this->data.size()));
 
   // Delete
   for (std::vector<int64_t>::iterator i = ids.begin(); i != ids.end(); ++i) {