Skip to content

Commit

Permalink
Code Formatting
Browse files Browse the repository at this point in the history
Adopt clang-format and styler for C++ / R code formatting

- Reformat C++ code using clang-format
- Reformat R code using styler
- Add Travis checks that code is well formatted

  Run clang-format and styler on code and use git to
  check for differences. If any are found, fail the build
- Minor typo corrections

Note that we are not attempting to reformat in the repo: the dev is still required to make sure the code is well formatted before submitting, but this should simplify reviews of future PRs.
  • Loading branch information
michaelweylandt authored Jun 25, 2019
2 parents 7c8fd20 + 7786ab6 commit 08196ad
Show file tree
Hide file tree
Showing 51 changed files with 3,585 additions and 2,556 deletions.
150 changes: 150 additions & 0 deletions .clang-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
# Defines the ANGLE style for automatic reformatting.
# https://code.google.com/p/angleproject/wiki/CodingStandard
# See Clang docs: http://clang.llvm.org/docs/ClangFormatStyleOptions.html
Language: Cpp
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: true
BinPackParameters: false
BraceWrapping:
AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: false
AfterStruct: true
AfterUnion: true
AfterExternBlock: false
BeforeCatch: true
BeforeElse: true
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 100
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
- Regex: '^<.*\.h>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: true
IndentPPDirectives: AfterHash
IndentWidth: 4
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Never
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Right
RawStringFormats:
- Language: Cpp
Delimiters:
- cc
- CC
- cpp
- Cpp
- CPP
- 'c++'
- 'C++'
CanonicalDelimiter: ''
BasedOnStyle: google
- Language: TextProto
Delimiters:
- pb
- PB
- proto
- PROTO
EnclosingFunctions:
- EqualsProto
- EquivToProto
- PARSE_PARTIAL_TEXT_PROTO
- PARSE_TEST_PROTO
- PARSE_TEXT_PROTO
- ParseTextOrDie
- ParseTextProtoOrDie
CanonicalDelimiter: ''
BasedOnStyle: google
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseTab: Never
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,4 @@ figs/*
# visualization plots
tests/testthat/*.pdf
.vscode/settings.json
myformat.sh
13 changes: 13 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ os:
# Modified from github.com/jeroen/jsonlite
osx_image: xcode9

addons:
apt:
sources:
# PPA for clang 6.0
- llvm-toolchain-trusty-6.0
# PPA for clang-format 8
- llvm-toolchain-trusty
# PPA for a more recen libstdc++
- ubuntu-toolchain-r-test
packages:
- clang-format

r_packages:
- Rcpp
- RcppArmadillo
Expand All @@ -20,6 +32,7 @@ r_packages:
- covr

before_install:
- bash script/format_check.sh || travis_terminate 1;
- Rscript -e "source('build_steps.R'); before_install()"

after_success:
Expand Down
15 changes: 7 additions & 8 deletions R/internals.R
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#' @importFrom utils packageDescription
moma_git_hash <- function(){
moma_git_hash <- function() {
pd <- packageDescription("moma")
gh_file <- system.file("GIT.HASH", package="moma")
gh_file <- system.file("GIT.HASH", package = "moma")

if(!is.null(pd$RemoteSha)){ # devtools install
if (!is.null(pd$RemoteSha)) { # devtools install
return(pd$RemoteSha)
} else if(file.exists(gh_file)){
} else if (file.exists(gh_file)) {
return(readLines(gh_file))
} else {
NA
Expand All @@ -22,18 +22,17 @@ moma_git_hash <- function(){
#' only.
#' @export
#' @importFrom utils sessionInfo
moma_session_info <- function(){
old_print <- options(max.print=9999)
moma_session_info <- function() {
old_print <- options(max.print = 9999)
on.exit(options(old_print))

cat("MoMA Git Hash: ", moma_git_hash(), "\n")

if(requireNamespace("devtools")){
if (requireNamespace("devtools")) {
print(devtools::session_info("moma"))
} else {
print(sessionInfo())
}

invisible(NULL)
}

61 changes: 32 additions & 29 deletions R/logging.R
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# Logging infrastructure for MoMA

## This must be kept consistent with src/moma_logging.h::MoMAoggerLevel
LEVELS <- c(ERROR = 40,
WARNING = 30,
MESSAGE = 20,
INFO = 10,
DEBUG = 00)
LEVELS <- c(
ERROR = 40,
WARNING = 30,
MESSAGE = 20,
INFO = 10,
DEBUG = 00
)


#' MoMA Package Logging Functionality
Expand Down Expand Up @@ -34,67 +36,68 @@ LEVELS <- c(ERROR = 40,
#' \code{moma_logger_level} function can be used to adjust the global
#' log level. The \code{INFO} and \code{DEBUG} levels can be quite verbose
#' and may significantly slow down the package.
moma_logger_level <- function(level=c("ERROR",
"WARNING",
"MESSAGE",
"INFO",
"DEBUG")){

moma_logger_level <- function(level = c(
"ERROR",
"WARNING",
"MESSAGE",
"INFO",
"DEBUG"
)) {
LEVELS_REV <- setNames(names(LEVELS), LEVELS)

old_level <- LEVELS_REV[as.character(moma_get_logger_level_cpp())]
names(old_level) <- NULL

if(!missing(level)){
level <- match.arg(level);
if (!missing(level)) {
level <- match.arg(level)
moma_set_logger_level_cpp(LEVELS[level])
return(invisible(old_level))
}

old_level
}

moma_error <- function(..., call=TRUE){
msg <- paste(list(...), collapse="")
moma_error <- function(..., call = TRUE) {
msg <- paste(list(...), collapse = "")

## Try to add R level calling info
if(identical(call, TRUE)){
if (identical(call, TRUE)) {
tryCatch({
msg <- paste0(msg, " (Called from ", as.character(as.list(sys.call(-1))[[1]]), ")")
}, error=function(e){})
} else if(is.character(call)){
}, error = function(e) {})
} else if (is.character(call)) {
msg <- paste0(msg, " (Called from ", call, ")")
}

moma_log_cpp(LEVELS["ERROR"], msg)
}

moma_warning <- function(..., call=TRUE){
msg <- paste(list(...), collapse="")
moma_warning <- function(..., call = TRUE) {
msg <- paste(list(...), collapse = "")

## Try to add R level calling info
if(identical(call, TRUE)){
if (identical(call, TRUE)) {
tryCatch({
msg <- paste0(msg, " (Called from ", as.character(as.list(sys.call(-1))[[1]]), ")")
}, error=function(e){})
} else if(is.character(call)){
}, error = function(e) {})
} else if (is.character(call)) {
msg <- paste0(msg, " (Called from ", call, ")")
}

moma_log_cpp(LEVELS["WARNING"], msg)
}

moma_message <- function(...){
msg <- paste(list(...), collapse="")
moma_message <- function(...) {
msg <- paste(list(...), collapse = "")
moma_log_cpp(LEVELS["MESSAGE"], msg)
}

moma_info <- function(...){
msg <- paste(list(...), collapse="")
moma_info <- function(...) {
msg <- paste(list(...), collapse = "")
moma_log_cpp(LEVELS["INFO"], msg)
}

moma_debug <- function(...){
msg <- paste(list(...), collapse="")
moma_debug <- function(...) {
msg <- paste(list(...), collapse = "")
moma_log_cpp(LEVELS["DEBUG"], msg)
}
40 changes: 21 additions & 19 deletions R/moma_4Dlist_extractor.R
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
get_4Dlist_elem <- function(x, alpha_u_i, lambda_u_i, alpha_v_i, lambda_v_i){
if(!inherits(x, "MoMA_4D_list")){
get_4Dlist_elem <- function(x, alpha_u_i, lambda_u_i, alpha_v_i, lambda_v_i) {
if (!inherits(x, "MoMA_4D_list")) {
moma_error(sQuote("x"), " should be a ", sQuote("MoMA_4D_list"), " object.")
}
n_alpha_u = dim(x)[1]
n_lambda_u = dim(x)[2]
n_alpha_v = dim(x)[3]
n_lambda_v = dim(x)[4]
n_alpha_u <- dim(x)[1]
n_lambda_u <- dim(x)[2]
n_alpha_v <- dim(x)[3]
n_lambda_v <- dim(x)[4]

# NOTE: R index starts from 1
if(
alpha_u_i <= 0 || alpha_u_i > n_alpha_u ||
lambda_u_i <= 0 || lambda_u_i > n_lambda_u ||
alpha_v_i <= 0 || alpha_v_i > n_alpha_v ||
lambda_v_i <= 0 || lambda_v_i > n_lambda_v
){
moma_error("Invalid index (",alpha_u_i, ",", lambda_u_i,
",",alpha_v_i, ",",lambda_v_i,"), dim = ",
dim(x))
if (
alpha_u_i <= 0 || alpha_u_i > n_alpha_u ||
lambda_u_i <= 0 || lambda_u_i > n_lambda_u ||
alpha_v_i <= 0 || alpha_v_i > n_alpha_v ||
lambda_v_i <= 0 || lambda_v_i > n_lambda_v
) {
moma_error(
"Invalid index (", alpha_u_i, ",", lambda_u_i,
",", alpha_v_i, ",", lambda_v_i, "), dim = ",
dim(x)
)
}
return(x[n_lambda_u * n_alpha_v * n_lambda_v * (alpha_u_i-1) +
n_alpha_v * n_lambda_v * (lambda_u_i-1) +
n_lambda_v * (alpha_v_i-1) +
lambda_v_i])
return(x[n_lambda_u * n_alpha_v * n_lambda_v * (alpha_u_i - 1) +
n_alpha_v * n_lambda_v * (lambda_u_i - 1) +
n_lambda_v * (alpha_v_i - 1) +
lambda_v_i])
}
Loading

0 comments on commit 08196ad

Please sign in to comment.