Updated cpplint.py and fixed its regexes for C-style casts (#193)

Additional C-style cast warnings thrown were also fixed.
This commit is contained in:
Tyler Veness
2016-08-11 23:38:45 -07:00
committed by Peter Johnson
parent e8f1fdda44
commit 3819cd0768
24 changed files with 109 additions and 68 deletions

View File

@@ -47,7 +47,7 @@ enum class HAL_HandleEnum {
static inline int16_t getHandleIndex(HAL_Handle handle) {
// mask and return last 16 bits
return (int16_t)(handle & 0xffff);
return static_cast<int16_t>(handle & 0xffff);
}
static inline HAL_HandleEnum getHandleType(HAL_Handle handle) {
// mask first 8 bits and cast to enum
@@ -74,13 +74,13 @@ static inline int16_t getHandleTypedIndex(HAL_Handle handle,
// using a 16 bit value so we can store 0-255 and still report error
static inline int16_t getPortHandlePin(HAL_PortHandle handle) {
if (!isHandleType(handle, HAL_HandleEnum::Port)) return InvalidHandleIndex;
return (uint8_t)(handle & 0xff);
return static_cast<uint8_t>(handle & 0xff);
}
// using a 16 bit value so we can store 0-255 and still report error
static inline int16_t getPortHandleModule(HAL_PortHandle handle) {
if (!isHandleType(handle, HAL_HandleEnum::Port)) return InvalidHandleIndex;
return (uint8_t)((handle >> 8) & 0xff);
return static_cast<uint8_t>((handle >> 8) & 0xff);
}
HAL_PortHandle createPortHandle(uint8_t pin, uint8_t module);

View File

@@ -81,7 +81,7 @@ void HAL_SetAnalogOutput(HAL_AnalogOutputHandle analog_output_handle,
return;
}
uint16_t rawValue = (uint16_t)(voltage / 5.0 * 0x1000);
uint16_t rawValue = static_cast<uint16_t>(voltage / 5.0 * 0x1000);
if (voltage < 0.0)
rawValue = 0;

View File

@@ -268,7 +268,9 @@ void HAL_SetCounterPulseLengthMode(HAL_CounterHandle counter_handle,
}
counter->counter->writeConfig_Mode(HAL_Counter_kPulseLength, status);
counter->counter->writeConfig_PulseLengthThreshold(
(uint32_t)(threshold * 1.0e6) * kSystemClockTicksPerMicrosecond, status);
static_cast<uint32_t>(threshold * 1.0e6) *
kSystemClockTicksPerMicrosecond,
status);
}
/**
@@ -379,8 +381,8 @@ void HAL_SetCounterMaxPeriod(HAL_CounterHandle counter_handle, double maxPeriod,
*status = HAL_HANDLE_ERROR;
return;
}
counter->counter->writeTimerConfig_StallPeriod((uint32_t)(maxPeriod * 4.0e8),
status);
counter->counter->writeTimerConfig_StallPeriod(
static_cast<uint32_t>(maxPeriod * 4.0e8), status);
}
/**

View File

@@ -141,7 +141,7 @@ void HAL_SetDigitalPWMRate(double rate, int32_t* status) {
// Currently rounding in the log rate domain... heavy weight toward picking a
// higher freq.
// TODO: Round in the linear rate domain.
uint8_t pwmPeriodPower = (uint8_t)(
uint8_t pwmPeriodPower = static_cast<uint8_t>(
log(1.0 / (pwmSystem->readLoopTiming(status) * 0.25E-6 * rate)) /
log(2.0) +
0.5);

View File

@@ -63,9 +63,9 @@ void initializeDigital(int32_t* status) {
double loopTime = pwmSystem->readLoopTiming(status) /
(kSystemClockTicksPerMicrosecond * 1e3);
pwmSystem->writeConfig_Period((uint16_t)(kDefaultPwmPeriod / loopTime + .5),
status);
uint16_t minHigh = (uint16_t)(
pwmSystem->writeConfig_Period(
static_cast<uint16_t>(kDefaultPwmPeriod / loopTime + .5), status);
uint16_t minHigh = static_cast<uint16_t>(
(kDefaultPwmCenter - kDefaultPwmStepsDown * loopTime) / loopTime + .5);
pwmSystem->writeConfig_MinHigh(minHigh, status);
// Ensure that PWM output values are set to OFF

View File

@@ -93,7 +93,7 @@ Encoder::~Encoder() {
// CounterBase interface
int32_t Encoder::Get(int32_t* status) const {
return (int32_t)(GetRaw(status) * DecodingScaleFactor());
return static_cast<int32_t>(GetRaw(status) * DecodingScaleFactor());
}
int32_t Encoder::GetRaw(int32_t* status) const {

View File

@@ -172,7 +172,8 @@ void HAL_SetFPGAEncoderMaxPeriod(HAL_FPGAEncoderHandle fpga_encoder_handle,
return;
}
encoder->encoder->writeTimerConfig_StallPeriod(
(uint32_t)(maxPeriod * 4.0e8 * DECODING_SCALING_FACTOR), status);
static_cast<uint32_t>(maxPeriod * 4.0e8 * DECODING_SCALING_FACTOR),
status);
}
/**

View File

@@ -210,7 +210,8 @@ uint64_t HAL_GetFPGATime(int32_t* status) {
// check for rollover
if (fpgaTime < prevFPGATime) ++timeEpoch;
prevFPGATime = fpgaTime;
return (((uint64_t)timeEpoch) << 32) | ((uint64_t)fpgaTime);
return static_cast<uint64_t>(timeEpoch) << 32 |
static_cast<uint64_t>(fpgaTime);
}
/**

View File

@@ -124,8 +124,8 @@ int32_t HAL_WriteI2C(int32_t port, int32_t deviceAddress, uint8_t* dataToSend,
port == 0 ? digitalI2COnBoardMutex : digitalI2CMXPMutex;
{
std::lock_guard<priority_recursive_mutex> sync(lock);
return i2clib_write(handle, deviceAddress, (const char*)dataToSend,
(int32_t)sendSize);
return i2clib_write(handle, deviceAddress,
reinterpret_cast<const char*>(dataToSend), sendSize);
}
}

View File

@@ -72,8 +72,8 @@ int64_t HAL_WaitForInterrupt(HAL_InterruptHandle interrupt_handle,
return 0;
}
result = anInterrupt->manager->watch((int32_t)(timeout * 1e3), ignorePrevious,
status);
result = anInterrupt->manager->watch(static_cast<int32_t>(timeout * 1e3),
ignorePrevious, status);
// Don't report a timeout as an error - the return code is enough to tell
// that a timeout happened.

View File

@@ -65,7 +65,7 @@ void updateNotifierAlarmInternal(std::shared_ptr<Notifier> notifier_pointer,
if (triggerTime < closestTrigger) {
closestTrigger = triggerTime;
// Simply truncate the hardware trigger time to 32-bit.
notifierAlarm->writeTriggerTime((uint32_t)triggerTime, status);
notifierAlarm->writeTriggerTime(static_cast<uint32_t>(triggerTime), status);
}
// Enable the alarm. The hardware disables itself after each alarm.
if (!wasActive) notifierAlarm->writeEnable(true, status);

View File

@@ -118,16 +118,16 @@ void HAL_SetPWMConfig(HAL_DigitalHandle pwm_port_handle, double max,
HAL_GetLoopTiming(status) / (kSystemClockTicksPerMicrosecond * 1e3);
if (*status != 0) return;
int32_t maxPwm = (int32_t)((max - kDefaultPwmCenter) / loopTime +
kDefaultPwmStepsDown - 1);
int32_t deadbandMaxPwm = (int32_t)(
int32_t maxPwm = static_cast<int32_t>((max - kDefaultPwmCenter) / loopTime +
kDefaultPwmStepsDown - 1);
int32_t deadbandMaxPwm = static_cast<int32_t>(
(deadbandMax - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1);
int32_t centerPwm = (int32_t)((center - kDefaultPwmCenter) / loopTime +
kDefaultPwmStepsDown - 1);
int32_t deadbandMinPwm = (int32_t)(
int32_t centerPwm = static_cast<int32_t>(
(center - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1);
int32_t deadbandMinPwm = static_cast<int32_t>(
(deadbandMin - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1);
int32_t minPwm = (int32_t)((min - kDefaultPwmCenter) / loopTime +
kDefaultPwmStepsDown - 1);
int32_t minPwm = static_cast<int32_t>((min - kDefaultPwmCenter) / loopTime +
kDefaultPwmStepsDown - 1);
port->maxPwm = maxPwm;
port->deadbandMaxPwm = deadbandMaxPwm;

View File

@@ -66,7 +66,7 @@ void HAL_SetSerialFlowControl(int32_t port, int32_t flow, int32_t* status) {
void HAL_SetSerialTimeout(int32_t port, double timeout, int32_t* status) {
*status = viSetAttribute(m_portHandle[port], VI_ATTR_TMO_VALUE,
(uint32_t)(timeout * 1e3));
static_cast<uint32_t>(timeout * 1e3));
if (*status > 0) *status = 0;
}

25
styleguide/cpplint.py vendored
View File

@@ -906,7 +906,7 @@ class _CppLintState(object):
def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for category, count in list(self.errors_by_category.items()):
for category, count in self.errors_by_category.items():
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
sys.stderr.write('Total errors found: %d\n' % self.error_count)
@@ -1900,7 +1900,7 @@ def CheckForBadCharacters(filename, lines, error):
error: The function to call with any errors found.
"""
for linenum, line in enumerate(lines):
if '\\ufffd' in line:
if '\ufffd' in line:
error(filename, linenum, 'readability/utf8', 5,
'Line contains invalid UTF-8 (or Unicode replacement character).')
if '\0' in line:
@@ -5108,7 +5108,8 @@ def CheckCasts(filename, clean_lines, linenum, error):
if not expecting_function:
CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
r'\(((unsigned )?(char|(short |long )?int|long)|float|'
'double|bool|u?int(8_t|16_t|32_t|64_t))\)', error)
# This doesn't catch all cases. Consider (const char * const)"hello".
#
@@ -5120,7 +5121,7 @@ def CheckCasts(filename, clean_lines, linenum, error):
else:
# Check pointer casts for other than string constants
CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
r'\((\w+\s?\*+\s?)\)', error)
r'\(((const )?\w+\s?\*+\s?)\)', error)
# In addition, we look for people taking the address of a cast. This
# is dangerous -- casts can assign to temporaries, so the pointer doesn't
@@ -5262,12 +5263,15 @@ _HEADERS_CONTAINING_TEMPLATES = (
('<limits>', ('numeric_limits',)),
('<list>', ('list',)),
('<map>', ('map', 'multimap',)),
('<memory>', ('allocator',)),
('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
'unique_ptr', 'weak_ptr')),
('<queue>', ('queue', 'priority_queue',)),
('<set>', ('set', 'multiset',)),
('<stack>', ('stack',)),
('<string>', ('char_traits', 'basic_string',)),
('<tuple>', ('tuple',)),
('<unordered_map>', ('unordered_map', 'unordered_multimap')),
('<unordered_set>', ('unordered_set', 'unordered_multiset')),
('<utility>', ('pair',)),
('<vector>', ('vector',)),
@@ -5282,7 +5286,7 @@ _HEADERS_MAYBE_TEMPLATES = (
('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
'transform',
)),
('<utility>', ('swap',)),
('<utility>', ('forward', 'make_pair', 'move', 'swap')),
)
_RE_PATTERN_STRING = re.compile(r'\bstring\b')
@@ -5433,8 +5437,13 @@ def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
continue
for pattern, template, header in _re_pattern_templates:
if pattern.search(line):
required[header] = (linenum, template)
matched = pattern.search(line)
if matched:
# Don't warn about IWYU in non-STL namespaces:
# (We check only the first match per line; good enough.)
prefix = line[:matched.start()]
if prefix.endswith('std::') or not prefix.endswith('::'):
required[header] = (linenum, template)
# The policy is that if you #include something in foo.h you don't need to
# include it again in foo.cc. Here, we will look at possible includes.

View File

@@ -9,7 +9,26 @@ and a patch was applied:
diff --git a/styleguide/cpplint.py b/styleguide/cpplint.py
--- a/styleguide/cpplint.py
+++ b/styleguide/cpplint.py
@@ -6094,13 +6094,6 @@ def ParseArguments(args):
@@ -5108,7 +5108,8 @@ def CheckCasts(filename, clean_lines, linenum, error):
if not expecting_function:
CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
- r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
+ r'\(((unsigned )?(char|(short |long )?int|long)|float|'
+ 'double|bool|u?int(8_t|16_t|32_t|64_t))\)', error)
# This doesn't catch all cases. Consider (const char * const)"hello".
#
@@ -5120,7 +5121,7 @@ def CheckCasts(filename, clean_lines, linenum, error):
else:
# Check pointer casts for other than string constants
CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
- r'\((\w+\s?\*+\s?)\)', error)
+ r'\(((const )?\w+\s?\*+\s?)\)', error)
# In addition, we look for people taking the address of a cast. This
# is dangerous -- casts can assign to temporaries, so the pointer doesn't
@@ -6102,13 +6103,6 @@ def ParseArguments(args):
def main():
filenames = ParseArguments(sys.argv[1:])

View File

@@ -36,7 +36,8 @@ ADXL345_I2C::ADXL345_I2C(I2C::Port port, Range range, int deviceAddress)
}
void ADXL345_I2C::SetRange(Range range) {
m_i2c.Write(kDataFormatRegister, kDataFormat_FullRes | (uint8_t)range);
m_i2c.Write(kDataFormatRegister,
kDataFormat_FullRes | static_cast<uint8_t>(range));
}
double ADXL345_I2C::GetX() { return GetAcceleration(kAxis_X); }

View File

@@ -49,7 +49,7 @@ void ADXL345_SPI::SetRange(Range range) {
// Specify the data format to read
commands[0] = kDataFormatRegister;
commands[1] = kDataFormat_FullRes | (uint8_t)(range & 0x03);
commands[1] = kDataFormat_FullRes | static_cast<uint8_t>(range & 0x03);
m_spi.Transaction(commands, commands, 2);
}
@@ -68,8 +68,8 @@ double ADXL345_SPI::GetZ() { return GetAcceleration(kAxis_Z); }
double ADXL345_SPI::GetAcceleration(ADXL345_SPI::Axes axis) {
uint8_t buffer[3];
uint8_t command[3] = {0, 0, 0};
command[0] =
(kAddress_Read | kAddress_MultiByte | kDataRegister) + (uint8_t)axis;
command[0] = (kAddress_Read | kAddress_MultiByte | kDataRegister) +
static_cast<uint8_t>(axis);
m_spi.Transaction(command, buffer, 3);
// Sensor is little endian... swap bytes

View File

@@ -95,7 +95,8 @@ void ADXL362::SetRange(Range range) {
// Specify the data format to read
commands[0] = kRegWrite;
commands[1] = kFilterCtlRegister;
commands[2] = kFilterCtl_ODR_100Hz | (uint8_t)((range & 0x03) << 6);
commands[2] =
kFilterCtl_ODR_100Hz | static_cast<uint8_t>((range & 0x03) << 6);
m_spi.Write(commands, 3);
}
@@ -117,7 +118,7 @@ double ADXL362::GetAcceleration(ADXL362::Axes axis) {
uint8_t buffer[4];
uint8_t command[4] = {0, 0, 0, 0};
command[0] = kRegRead;
command[1] = kDataRegister + (uint8_t)axis;
command[1] = kDataRegister + static_cast<uint8_t>(axis);
m_spi.Transaction(command, buffer, 4);
// Sensor is little endian... swap bytes

View File

@@ -43,7 +43,8 @@ void ADXRS450_Gyro::Calibrate() {
Wait(kCalibrationSampleTime);
m_spi.SetAccumulatorCenter((int32_t)m_spi.GetAccumulatorAverage());
m_spi.SetAccumulatorCenter(
static_cast<int32_t>(m_spi.GetAccumulatorAverage()));
m_spi.ResetAccumulator();
}
@@ -89,26 +90,27 @@ static bool CalcParity(uint32_t v) {
}
static inline uint32_t BytesToIntBE(uint8_t* buf) {
uint32_t result = ((uint32_t)buf[0]) << 24;
result |= ((uint32_t)buf[1]) << 16;
result |= ((uint32_t)buf[2]) << 8;
result |= (uint32_t)buf[3];
uint32_t result = static_cast<uint32_t>(buf[0]) << 24;
result |= static_cast<uint32_t>(buf[1]) << 16;
result |= static_cast<uint32_t>(buf[2]) << 8;
result |= static_cast<uint32_t>(buf[3]);
return result;
}
uint16_t ADXRS450_Gyro::ReadRegister(uint8_t reg) {
uint32_t cmd = 0x80000000 | (((uint32_t)reg) << 17);
uint32_t cmd = 0x80000000 | static_cast<uint32_t>(reg) << 17;
if (!CalcParity(cmd)) cmd |= 1u;
// big endian
uint8_t buf[4] = {(uint8_t)((cmd >> 24) & 0xff),
(uint8_t)((cmd >> 16) & 0xff), (uint8_t)((cmd >> 8) & 0xff),
(uint8_t)(cmd & 0xff)};
uint8_t buf[4] = {static_cast<uint8_t>((cmd >> 24) & 0xff),
static_cast<uint8_t>((cmd >> 16) & 0xff),
static_cast<uint8_t>((cmd >> 8) & 0xff),
static_cast<uint8_t>(cmd & 0xff)};
m_spi.Write(buf, 4);
m_spi.Read(false, buf, 4);
if ((buf[0] & 0xe0) == 0) return 0; // error, return 0
return (uint16_t)((BytesToIntBE(buf) >> 5) & 0xffff);
return static_cast<uint16_t>((BytesToIntBE(buf) >> 5) & 0xffff);
}
/**

View File

@@ -25,7 +25,7 @@ AnalogTriggerOutput::AnalogTriggerOutput(const AnalogTrigger& trigger,
AnalogTriggerType outputType)
: m_trigger(trigger), m_outputType(outputType) {
HAL_Report(HALUsageReporting::kResourceType_AnalogTriggerOutput,
trigger.GetIndex(), (uint8_t)outputType);
trigger.GetIndex(), static_cast<uint8_t>(outputType));
}
AnalogTriggerOutput::~AnalogTriggerOutput() {

View File

@@ -22,8 +22,10 @@
#define swap32(x) (x)
/* Compare floats for equality as fixed point numbers */
#define FXP8_EQ(a, b) ((int16_t)((a)*256.0) == (int16_t)((b)*256.0))
#define FXP16_EQ(a, b) ((int32_t)((a)*65536.0) == (int32_t)((b)*65536.0))
#define FXP8_EQ(a, b) \
(static_cast<int16_t>((a)*256.0) == static_cast<int16_t>((b)*256.0))
#define FXP16_EQ(a, b) \
(static_cast<int32_t>((a)*65536.0) == static_cast<int32_t>((b)*65536.0))
const int32_t CANJaguar::kControllerRate;
constexpr double CANJaguar::kApproxBusVoltage;
@@ -912,7 +914,7 @@ void CANJaguar::verify() {
&dataSize)) {
uint16_t faultTime = unpackint16_t(dataBuffer);
if ((uint16_t)(m_faultTime * 1000.0) == faultTime) {
if (static_cast<uint16_t>(m_faultTime * 1000.0) == faultTime) {
m_faultTimeVerified = true;
} else {
// It's wrong - set it again
@@ -1919,7 +1921,7 @@ void CANJaguar::ConfigFaultTime(float faultTime) {
faultTime = 3.0;
// Message takes ms
dataSize = packint16_t(dataBuffer, (int16_t)(faultTime * 1000.0));
dataSize = packint16_t(dataBuffer, static_cast<int16_t>(faultTime * 1000.0));
sendMessage(LM_API_CFG_FAULT_TIME, dataBuffer, dataSize);
m_faultTime = faultTime;

View File

@@ -47,8 +47,8 @@ Notifier::~Notifier() {
*/
void Notifier::UpdateAlarm() {
int32_t status = 0;
HAL_UpdateNotifierAlarm(m_notifier, (uint64_t)(m_expirationTime * 1e6),
&status);
HAL_UpdateNotifierAlarm(
m_notifier, static_cast<uint64_t>(m_expirationTime * 1e6), &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
}

View File

@@ -54,8 +54,9 @@ unsigned int USBCamera::GetJpegSize(void* buffer, unsigned int buffSize) {
} else if (t == 0xda) {
// SOS marker. The next two bytes are a 16-bit big-endian int that is
// the length of the SOS header, skip that
unsigned int len = (((unsigned int)(data[pos + 2] & 0xff)) << 8 |
((unsigned int)data[pos + 3] & 0xff));
unsigned int len = (static_cast<unsigned int>(data[pos + 2]) & 0xff)
<< 8 |
(static_cast<unsigned int>(data[pos + 3]) & 0xff);
pos += len + 2;
// The next marker is the first marker that is 0xff followed by a non-RST
// element. 0xff followed by 0x00 is an escaped 0xff. 0xd0-0xd7 are RST
@@ -70,8 +71,9 @@ unsigned int USBCamera::GetJpegSize(void* buffer, unsigned int buffSize) {
// 16-bit
// big-endian int with the length of the marker header, skip that then
// continue searching
unsigned int len = (((unsigned int)(data[pos + 2] & 0xff)) << 8 |
((unsigned int)data[pos + 3] & 0xff));
unsigned int len = (static_cast<unsigned int>(data[pos + 2]) & 0xff)
<< 8 |
(static_cast<unsigned int>(data[pos + 3]) & 0xff);
pos += len + 2;
}
}
@@ -156,8 +158,8 @@ void USBCamera::UpdateSettings() {
for (unsigned int i = 0; i < count; i++) {
std::cmatch m;
if (!std::regex_match(modes[i].Name, m, reMode)) continue;
unsigned int width = (unsigned int)std::stoul(m[1].str());
unsigned int height = (unsigned int)std::stoul(m[2].str());
unsigned int width = static_cast<unsigned int>(std::stoul(m[1].str()));
unsigned int height = static_cast<unsigned int>(std::stoul(m[2].str()));
if (width != m_width) continue;
if (height != m_height) continue;
double fps = atof(m[4].str().c_str());

View File

@@ -297,7 +297,7 @@ MonoImage* ColorImage::GetIntensityPlane() {
void ColorImage::ReplacePlane(ColorMode mode, MonoImage* plane,
int planeNumber) {
int success = imaqReplaceColorPlanes(
m_imaqImage, (const Image*)m_imaqImage, mode,
m_imaqImage, reinterpret_cast<const Image*>(m_imaqImage), mode,
(planeNumber == 1) ? plane->GetImaqImage() : nullptr,
(planeNumber == 2) ? plane->GetImaqImage() : nullptr,
(planeNumber == 3) ? plane->GetImaqImage() : nullptr);
@@ -475,7 +475,8 @@ void ColorImage::ReplaceIntensityPlane(MonoImage* plane) {
// to imaqColorEqualize.
void ColorImage::Equalize(bool allPlanes) {
// Note that this call uses NI-defined TRUE and FALSE
int success = imaqColorEqualize(m_imaqImage, (const Image*)m_imaqImage,
int success = imaqColorEqualize(m_imaqImage,
reinterpret_cast<const Image*>(m_imaqImage),
(allPlanes) ? TRUE : FALSE);
wpi_setImaqErrorWithContext(success, "Imaq ColorEqualize error");
}