Skip to content

Commit 0f10074

Browse files
committed
Adopt clang-format for code formatting
1 parent a43e90c commit 0f10074

File tree

6 files changed

+278
-0
lines changed

6 files changed

+278
-0
lines changed

.clang-format

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
---
2+
Language: Cpp
3+
4+
# Indentation
5+
UseTab: Never
6+
IndentWidth: 4
7+
BreakBeforeBraces: Attach
8+
IndentCaseLabels: false
9+
NamespaceIndentation: None
10+
ContinuationIndentWidth: 4
11+
IndentPPDirectives: None
12+
IndentWrappedFunctionNames: false
13+
AccessModifierOffset: -2
14+
15+
# Alignment
16+
AlignAfterOpenBracket: BlockIndent
17+
AlignConsecutiveAssignments: false
18+
AlignConsecutiveDeclarations: false
19+
AlignConsecutiveMacros: false
20+
AlignEscapedNewlines: Left
21+
AlignOperands: false
22+
AlignTrailingComments: true
23+
DerivePointerAlignment: false
24+
PointerAlignment: Right
25+
26+
# Function calls formatting
27+
BinPackArguments: false
28+
BinPackParameters: false
29+
AllowAllArgumentsOnNextLine: false
30+
ExperimentalAutoDetectBinPacking: false
31+
PenaltyBreakBeforeFirstCallParameter: 1
32+
AlwaysBreakAfterDefinitionReturnType: None
33+
34+
# Wrapping and Breaking
35+
ColumnLimit: 0
36+
AllowShortBlocksOnASingleLine: Never
37+
AllowShortCaseLabelsOnASingleLine: false
38+
AllowShortFunctionsOnASingleLine: All
39+
AllowShortIfStatementsOnASingleLine: Always
40+
AllowShortLoopsOnASingleLine: false
41+
AlwaysBreakAfterReturnType: None
42+
AlwaysBreakBeforeMultilineStrings: false
43+
AlwaysBreakTemplateDeclarations: No
44+
BreakBeforeBinaryOperators: None
45+
BreakBeforeTernaryOperators: false
46+
BreakConstructorInitializers: BeforeColon
47+
BreakInheritanceList: BeforeColon
48+
BreakStringLiterals: false
49+
CompactNamespaces: false
50+
ConstructorInitializerAllOnOneLineOrOnePerLine: false
51+
Cpp11BracedListStyle: false
52+
ReflowComments: false
53+
SortIncludes: Never
54+
55+
# Spaces
56+
SpaceAfterCStyleCast: true
57+
SpaceAfterLogicalNot: false
58+
SpaceAfterTemplateKeyword: true
59+
SpaceBeforeAssignmentOperators: true
60+
SpaceBeforeCpp11BracedList: true
61+
SpaceBeforeCtorInitializerColon: true
62+
SpaceBeforeInheritanceColon: true
63+
SpaceBeforeParens: ControlStatements
64+
SpaceBeforeRangeBasedForLoopColon: true
65+
SpaceBeforeSquareBrackets: false
66+
SpaceInEmptyBlock: false
67+
SpaceInEmptyParentheses: false
68+
SpacesBeforeTrailingComments: 1
69+
SpacesInAngles: false
70+
SpacesInCStyleCastParentheses: false
71+
SpacesInConditionalStatement: false
72+
SpacesInContainerLiterals: true
73+
SpacesInParentheses: false
74+
SpacesInSquareBrackets: false

.github/workflows/clang-format.yml

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
name: C Code Formatting Check
2+
3+
on:
4+
push:
5+
paths:
6+
- '**.c'
7+
- '**.h'
8+
- '.clang-format'
9+
- '.github/workflows/clang-format.yml'
10+
pull_request:
11+
paths:
12+
- '**.c'
13+
- '**.h'
14+
- '.clang-format'
15+
- '.github/workflows/clang-format.yml'
16+
17+
jobs:
18+
format-check:
19+
runs-on: ubuntu-latest
20+
steps:
21+
- uses: actions/checkout@v4
22+
- uses: ruby/setup-ruby@v1
23+
with:
24+
ruby-version: "3.4"
25+
bundler-cache: none
26+
- name: Set working directory as safe
27+
run: git config --global --add safe.directory $(pwd)
28+
- name: Set up permission
29+
run: chmod -R o-w /opt/hostedtoolcache/Ruby
30+
- name: Install dependencies
31+
run: |
32+
sudo apt-get update
33+
sudo apt-get install -y libdb-dev curl autoconf automake m4 libtool
34+
- name: Install clang-format from LLVM
35+
run: |
36+
wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -
37+
sudo apt-add-repository "deb http://apt.llvm.org/jammy/ llvm-toolchain-jammy main"
38+
sudo apt-get update
39+
sudo apt-get install -y clang-format
40+
clang-format --version
41+
- name: Install Re2c
42+
run: |
43+
cd /tmp
44+
curl -L https://github.com/skvadrik/re2c/archive/refs/tags/3.1.tar.gz > re2c-3.1.tar.gz
45+
tar xf re2c-3.1.tar.gz
46+
cd re2c-3.1
47+
autoreconf -i -W all
48+
./configure
49+
make
50+
sudo make install
51+
- name: Update rubygems & bundler
52+
run: |
53+
ruby -v
54+
gem update --system
55+
- name: bin/setup
56+
run: |
57+
bin/setup
58+
- name: Check C code formatting
59+
run: |
60+
clang-format --version
61+
bundle exec rake templates
62+
bundle exec rake format:c_check

.vscode/extensions.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"recommendations": [
3+
"llvm-vs-code-extensions.vscode-clangd"
4+
]
5+
}

.vscode/settings.json

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"clangd.onConfigChanged": "restart",
3+
"[c]": {
4+
"editor.formatOnSave": true,
5+
"editor.defaultFormatter": "llvm-vs-code-extensions.vscode-clangd"
6+
},
7+
"[cpp]": {
8+
"editor.formatOnSave": true,
9+
"editor.defaultFormatter": "llvm-vs-code-extensions.vscode-clangd"
10+
},
11+
"[h]": {
12+
"editor.formatOnSave": true,
13+
"editor.defaultFormatter": "llvm-vs-code-extensions.vscode-clangd"
14+
},
15+
"[hpp]": {
16+
"editor.formatOnSave": true,
17+
"editor.defaultFormatter": "llvm-vs-code-extensions.vscode-clangd"
18+
}
19+
}

README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,43 @@ After checking out the repo, run `bin/setup` to install dependencies. Then, run
198198

199199
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
200200

201+
### C Code Formatting
202+
203+
This project uses `clang-format` to enforce consistent formatting of C code with a `.clang-format` configuration in the root directory.
204+
205+
#### Setup
206+
207+
First, install clang-format:
208+
209+
```bash
210+
# macOS
211+
brew install clang-format
212+
213+
# Ubuntu/Debian
214+
sudo apt-get install clang-format
215+
216+
# Windows
217+
choco install llvm
218+
```
219+
220+
#### Usage
221+
222+
Format all C source files:
223+
224+
```bash
225+
rake format:c
226+
```
227+
228+
Check formatting without making changes:
229+
230+
```bash
231+
rake format:c_check
232+
```
233+
234+
#### Editor Integration
235+
236+
For VS Code users, install the "clangd" extension which will automatically use the project's `.clang-format` file.
237+
201238
## Contributing
202239

203240
Bug reports and pull requests are welcome on GitHub at https://github.com/ruby/rbs.

Rakefile

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,87 @@ task :confirm_templates => :templates do
4949
sh "git diff --exit-code -- include src"
5050
end
5151

52+
# Task to format C code using clang-format
53+
namespace :format do
54+
dirs = ["src", "ext", "include"]
55+
excluded_files = ["ext/rbs_extension/lexer.c", "src/constants.c", "src/ruby_objs.c"]
56+
57+
# Find all C source and header files, then filter out excluded files
58+
files = `find #{dirs.join(" ")} -type f \\( -name "*.c" -o -name "*.h" \\)`.split("\n").reject do |file|
59+
excluded_files.include?(file)
60+
end
61+
62+
desc "Format C source files using clang-format"
63+
task :c do
64+
puts "Formatting C files..."
65+
66+
# Check if clang-format is installed
67+
unless system("which clang-format > /dev/null 2>&1")
68+
abort "Error: clang-format not found. Please install clang-format first."
69+
end
70+
71+
if files.empty?
72+
puts "No C files found to format"
73+
next
74+
end
75+
76+
puts "Found #{files.length} files to format (excluding generated files)"
77+
78+
exit_status = 0
79+
files.each do |file|
80+
puts "Formatting #{file}"
81+
unless system("clang-format -i -style=file #{file}")
82+
puts "❌ Error formatting #{file}"
83+
exit_status = 1
84+
end
85+
end
86+
87+
exit exit_status unless exit_status == 0
88+
puts "✅ All files formatted successfully"
89+
end
90+
91+
desc "Check if C source files are properly formatted"
92+
task :c_check do
93+
puts "Checking C file formatting..."
94+
95+
# Check if clang-format is installed
96+
unless system("which clang-format > /dev/null 2>&1")
97+
abort "Error: clang-format not found. Please install clang-format first."
98+
end
99+
100+
if files.empty?
101+
puts "No C files found to check"
102+
next
103+
end
104+
105+
puts "Found #{files.length} files to check (excluding generated files)"
106+
107+
needs_format = false
108+
files.each do |file|
109+
formatted = `clang-format -style=file #{file}`
110+
original = File.read(file)
111+
112+
if formatted != original
113+
puts "❌ #{file} needs formatting"
114+
puts "Diff:"
115+
# Save formatted version to temp file and run diff
116+
temp_file = "#{file}.formatted"
117+
File.write(temp_file, formatted)
118+
system("diff -u #{file} #{temp_file}")
119+
File.unlink(temp_file)
120+
needs_format = true
121+
end
122+
end
123+
124+
if needs_format
125+
warn "Some files need formatting. Run 'rake format:c' to format them."
126+
exit 1
127+
else
128+
puts "✅ All files are properly formatted"
129+
end
130+
end
131+
end
132+
52133
rule ".c" => ".re" do |t|
53134
puts "⚠️⚠️⚠️ #{t.name} is older than #{t.source}. You may need to run `rake lexer` ⚠️⚠️⚠️"
54135
end

0 commit comments

Comments
 (0)