Skip to content

Sync sketch formatter configuration from source #1285

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 8, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 101 additions & 45 deletions arduino-ide-extension/src/node/clang-formatter.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as os from 'os';
import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
import { MaybePromise } from '@theia/core/lib/common/types';
import { FileUri } from '@theia/core/lib/node/file-uri';
Expand Down Expand Up @@ -121,25 +122,39 @@ function toClangOptions(
return { UseTab: 'Never', TabWidth: 2 };
}

// See: https://releases.llvm.org/11.0.1/tools/clang/docs/ClangFormatStyleOptions.html
export function style({ TabWidth, UseTab }: ClangFormatOptions): string {
return JSON.stringify(styleJson({ TabWidth, UseTab })).replace(/\"/g, '\\"');
let styleArgument = JSON.stringify(styleJson({ TabWidth, UseTab })).replace(
/[\\"]/g,
'\\$&'
);
if (os.platform() === 'win32') {
// Windows command interpreter does not use backslash escapes. This causes the argument to have alternate quoted and
// unquoted sections.
// Special characters in the unquoted sections must be caret escaped.
const styleArgumentSplit = styleArgument.split('"');
for (let i = 1; i < styleArgumentSplit.length; i += 2) {
styleArgumentSplit[i] = styleArgumentSplit[i].replace(/[<>^|]/g, '^$&');
}

styleArgument = styleArgumentSplit.join('"');
}

return styleArgument;
}

function styleJson({
TabWidth,
UseTab,
}: ClangFormatOptions): Record<string, unknown> {
// Source: https://github.com/arduino/tooling-project-assets/tree/main/other/clang-format-configuration
return {
Language: 'Cpp',
// # LLVM is the default style setting, used when a configuration option is not set here
BasedOnStyle: 'LLVM',
AccessModifierOffset: -2,
AlignAfterOpenBracket: 'Align',
AlignConsecutiveAssignments: false,
AlignConsecutiveBitFields: false,
AlignConsecutiveDeclarations: false,
AlignConsecutiveMacros: false,
AlignArrayOfStructures: 'None',
AlignConsecutiveAssignments: 'None',
AlignConsecutiveBitFields: 'None',
AlignConsecutiveDeclarations: 'None',
AlignConsecutiveMacros: 'None',
AlignEscapedNewlines: 'DontAlign',
AlignOperands: 'Align',
AlignTrailingComments: true,
Expand All @@ -150,24 +165,26 @@ function styleJson({
AllowShortCaseLabelsOnASingleLine: true,
AllowShortEnumsOnASingleLine: true,
AllowShortFunctionsOnASingleLine: 'Empty',
AllowShortIfStatementsOnASingleLine: 'Always',
AllowShortIfStatementsOnASingleLine: 'AllIfsAndElse',
AllowShortLambdasOnASingleLine: 'Empty',
AllowShortLoopsOnASingleLine: true,
AlwaysBreakAfterDefinitionReturnType: 'None',
AlwaysBreakAfterReturnType: 'None',
AlwaysBreakBeforeMultilineStrings: false,
AlwaysBreakTemplateDeclarations: 'No',
AttributeMacros: ['__capability'],
BasedOnStyle: 'LLVM',
BinPackArguments: true,
BinPackParameters: true,
// # Only used when "BreakBeforeBraces" set to "Custom"
BitFieldColonSpacing: 'Both',
BraceWrapping: {
AfterCaseLabel: false,
AfterClass: false,
AfterControlStatement: 'Never',
AfterEnum: false,
AfterFunction: false,
AfterNamespace: false,
// #AfterObjCDeclaration:
AfterObjCDeclaration: false,
AfterStruct: false,
AfterUnion: false,
AfterExternBlock: false,
Expand All @@ -176,104 +193,143 @@ function styleJson({
BeforeLambdaBody: false,
BeforeWhile: false,
IndentBraces: false,
SplitEmptyFunction: false,
SplitEmptyRecord: false,
SplitEmptyNamespace: false,
SplitEmptyFunction: true,
SplitEmptyRecord: true,
SplitEmptyNamespace: true,
},
// # Java-specific
// #BreakAfterJavaFieldAnnotations:
BreakAfterJavaFieldAnnotations: false,
BreakBeforeBinaryOperators: 'NonAssignment',
BreakBeforeBraces: 'Attach',
BreakBeforeConceptDeclarations: false,
BreakBeforeInheritanceComma: false,
BreakBeforeTernaryOperators: true,
BreakConstructorInitializers: 'BeforeColon',
BreakConstructorInitializersBeforeComma: false,
BreakInheritanceList: 'BeforeColon',
BreakStringLiterals: false,
ColumnLimit: 0,
// # "" matches none
CommentPragmas: '',
CompactNamespaces: false,
ConstructorInitializerAllOnOneLineOrOnePerLine: true,
ConstructorInitializerAllOnOneLineOrOnePerLine: false,
ConstructorInitializerIndentWidth: 2,
ContinuationIndentWidth: 2,
Cpp11BracedListStyle: false,
DeriveLineEnding: true,
DerivePointerAlignment: true,
DisableFormat: false,
// # Docs say "Do not use this in config files". The default (LLVM 11.0.1) is "false".
// #ExperimentalAutoDetectBinPacking:
EmptyLineAfterAccessModifier: 'Leave',
EmptyLineBeforeAccessModifier: 'Leave',
ExperimentalAutoDetectBinPacking: false,
FixNamespaceComments: false,
ForEachMacros: [],
ForEachMacros: ['foreach', 'Q_FOREACH', 'BOOST_FOREACH'],
IfMacros: ['KJ_IF_MAYBE'],
IncludeBlocks: 'Preserve',
IncludeCategories: [],
// # "" matches none
IncludeCategories: [
{
Regex: '^"(llvm|llvm-c|clang|clang-c)/',
Priority: 2,
SortPriority: 0,
CaseSensitive: false,
},
{
Regex: '^(<|"(gtest|gmock|isl|json)/)',
Priority: 3,
SortPriority: 0,
CaseSensitive: false,
},
{ Regex: '.*', Priority: 1, SortPriority: 0, CaseSensitive: false },
],
IncludeIsMainRegex: '',
IncludeIsMainSourceRegex: '',
IndentAccessModifiers: false,
IndentCaseBlocks: true,
IndentCaseLabels: true,
IndentExternBlock: 'Indent',
IndentGotoLabels: false,
IndentPPDirectives: 'None',
IndentRequires: true,
IndentWidth: 2,
IndentWrappedFunctionNames: false,
InsertTrailingCommas: 'None',
// # Java-specific
// #JavaImportGroups:
// # JavaScript-specific
// #JavaScriptQuotes:
// #JavaScriptWrapImports
JavaScriptQuotes: 'Leave',
JavaScriptWrapImports: true,
KeepEmptyLinesAtTheStartOfBlocks: true,
LambdaBodyIndentation: 'Signature',
Language: 'Cpp',
MacroBlockBegin: '',
MacroBlockEnd: '',
// # Set to a large number to effectively disable
MaxEmptyLinesToKeep: 100000,
NamespaceIndentation: 'None',
NamespaceMacros: [],
// # Objective C-specific
// #ObjCBinPackProtocolList:
// #ObjCBlockIndentWidth:
// #ObjCBreakBeforeNestedBlockParam:
// #ObjCSpaceAfterProperty:
// #ObjCSpaceBeforeProtocolList
ObjCBinPackProtocolList: 'Auto',
ObjCBlockIndentWidth: 2,
ObjCBreakBeforeNestedBlockParam: true,
ObjCSpaceAfterProperty: false,
ObjCSpaceBeforeProtocolList: true,
PPIndentWidth: -1,
PackConstructorInitializers: 'BinPack',
PenaltyBreakAssignment: 1,
PenaltyBreakBeforeFirstCallParameter: 1,
PenaltyBreakComment: 1,
PenaltyBreakFirstLessLess: 1,
PenaltyBreakOpenParenthesis: 1,
PenaltyBreakString: 1,
PenaltyBreakTemplateDeclaration: 1,
PenaltyExcessCharacter: 1,
PenaltyIndentedWhitespace: 1,
PenaltyReturnTypeOnItsOwnLine: 1,
// # Used as a fallback if alignment style can't be detected from code (DerivePointerAlignment: true)
PointerAlignment: 'Right',
RawStringFormats: [],
QualifierAlignment: 'Leave',
ReferenceAlignment: 'Pointer',
ReflowComments: false,
SortIncludes: false,
RemoveBracesLLVM: false,
SeparateDefinitionBlocks: 'Leave',
ShortNamespaceLines: 0,
SortIncludes: 'Never',
SortJavaStaticImport: 'Before',
SortUsingDeclarations: false,
SpaceAfterCStyleCast: false,
SpaceAfterLogicalNot: false,
SpaceAfterTemplateKeyword: false,
SpaceAroundPointerQualifiers: 'Default',
SpaceBeforeAssignmentOperators: true,
SpaceBeforeCaseColon: false,
SpaceBeforeCpp11BracedList: false,
SpaceBeforeCtorInitializerColon: true,
SpaceBeforeInheritanceColon: true,
SpaceBeforeParens: 'ControlStatements',
SpaceBeforeParensOptions: {
AfterControlStatements: true,
AfterForeachMacros: true,
AfterFunctionDefinitionName: false,
AfterFunctionDeclarationName: false,
AfterIfMacros: true,
AfterOverloadedOperator: false,
BeforeNonEmptyParentheses: false,
},
SpaceBeforeRangeBasedForLoopColon: true,
SpaceBeforeSquareBrackets: false,
SpaceInEmptyBlock: false,
SpaceInEmptyParentheses: false,
SpacesBeforeTrailingComments: 2,
SpacesInAngles: false,
SpacesInAngles: 'Leave',
SpacesInCStyleCastParentheses: false,
SpacesInConditionalStatement: false,
SpacesInContainerLiterals: false,
SpacesInLineCommentPrefix: { Minimum: 0, Maximum: -1 },
SpacesInParentheses: false,
SpacesInSquareBrackets: false,
Standard: 'Auto',
StatementMacros: [],
StatementAttributeLikeMacros: ['Q_EMIT'],
StatementMacros: ['Q_UNUSED', 'QT_REQUIRE_VERSION'],
TabWidth,
TypenameMacros: [],
// # Default to LF if line endings can't be detected from the content (DeriveLineEnding).
UseCRLF: false,
UseTab,
WhitespaceSensitiveMacros: [],
WhitespaceSensitiveMacros: [
'STRINGIZE',
'PP_STRINGIZE',
'BOOST_PP_STRINGIZE',
'NS_SWIFT_NAME',
'CF_SWIFT_NAME',
],
};
}