0
# Core Processing
1
2
Main linting functions for processing Solidity source code at different levels - from strings to files to directory patterns. These functions form the primary programmatic API for Solhint.
3
4
## Capabilities
5
6
### Process String
7
8
Processes Solidity source code from a string and returns linting results.
9
10
```javascript { .api }
11
/**
12
* Processes Solidity source code string and returns a Reporter with linting results
13
* @param {string} inputStr - Solidity source code to lint
14
* @param {Object} config - Configuration object with rules and settings (optional)
15
* @param {string} fileName - Name of the file being processed (optional)
16
* @returns {Reporter} Reporter instance with linting results
17
*/
18
function processStr(inputStr, config = {}, fileName = '');
19
```
20
21
**Usage Examples:**
22
23
```javascript
24
const { processStr } = require('solhint');
25
26
// Basic usage with default config
27
const sourceCode = `
28
contract Example {
29
function test() public {}
30
}`;
31
const report = processStr(sourceCode);
32
console.log('Errors:', report.errorCount);
33
34
// With custom configuration
35
const config = {
36
rules: {
37
'func-visibility': 'error',
38
'compiler-version': ['error', '^0.8.0']
39
}
40
};
41
const reportWithConfig = processStr(sourceCode, config, 'Example.sol');
42
43
// Check specific issues
44
if (reportWithConfig.errorCount > 0) {
45
reportWithConfig.messages.forEach(msg => {
46
console.log(`Line ${msg.line}: ${msg.message} (${msg.ruleId})`);
47
});
48
}
49
```
50
51
### Process File
52
53
Processes a single Solidity file and returns linting results with file metadata.
54
55
```javascript { .api }
56
/**
57
* Processes a single Solidity file and returns linting results
58
* @param {string} file - Path to Solidity file to lint
59
* @param {Object} config - Configuration object (optional, uses config resolution if not provided)
60
* @param {string} rootDir - Root directory for config resolution (optional, defaults to process.cwd())
61
* @param {string} explicitConfigPath - Path to explicit config file (optional)
62
* @returns {Reporter} Reporter instance with linting results and file metadata
63
*/
64
function processFile(file, config, rootDir = process.cwd(), explicitConfigPath);
65
```
66
67
**Usage Examples:**
68
69
```javascript
70
const { processFile } = require('solhint');
71
72
// Process with default configuration resolution
73
const report = processFile('./contracts/Token.sol');
74
console.log('File:', report.filePath);
75
console.log('Issues found:', report.reports.length);
76
77
// Process with explicit configuration
78
const customConfig = {
79
rules: {
80
'no-console': 'error',
81
'max-line-length': ['warn', 120]
82
}
83
};
84
const reportWithConfig = processFile(
85
'./contracts/Token.sol',
86
customConfig,
87
process.cwd()
88
);
89
90
// Process with explicit config file
91
const reportWithConfigFile = processFile(
92
'./contracts/Token.sol',
93
undefined,
94
process.cwd(),
95
'./.solhint-custom.json'
96
);
97
98
// Handle caching
99
const cachedConfig = {
100
rules: { 'func-visibility': 'error' },
101
cache: true,
102
cacheLocation: './node_modules/.cache/solhint/.solhintcache.json'
103
};
104
const cachedReport = processFile('./contracts/Token.sol', cachedConfig);
105
if (cachedReport.skipped) {
106
console.log('File was skipped due to cache');
107
}
108
```
109
110
### Process Path
111
112
Processes multiple files matching a glob pattern and returns array of linting results.
113
114
```javascript { .api }
115
/**
116
* Processes multiple files matching a glob pattern
117
* @param {string} pattern - Glob pattern to match Solidity files
118
* @param {Object} config - Configuration object (optional)
119
* @param {string} rootDir - Root directory for processing (optional, defaults to process.cwd())
120
* @param {string} explicitConfigPath - Path to explicit config file (optional)
121
* @returns {Array<Reporter>} Array of Reporter instances for each processed file
122
*/
123
function processPath(pattern, config, rootDir = process.cwd(), explicitConfigPath);
124
```
125
126
**Usage Examples:**
127
128
```javascript
129
const { processPath } = require('solhint');
130
131
// Process all Solidity files in contracts directory
132
const reports = processPath('contracts/**/*.sol');
133
console.log(`Processed ${reports.length} files`);
134
135
// Calculate totals across all files
136
const totalErrors = reports.reduce((sum, report) => sum + report.errorCount, 0);
137
const totalWarnings = reports.reduce((sum, report) => sum + report.warningCount, 0);
138
console.log(`Total errors: ${totalErrors}, warnings: ${totalWarnings}`);
139
140
// Process with configuration and file exclusions
141
const config = {
142
rules: {
143
'compiler-version': ['error', '^0.8.0'],
144
'no-unused-vars': 'warn'
145
},
146
excludedFiles: ['contracts/test/**', 'contracts/mocks/**']
147
};
148
const filteredReports = processPath('contracts/**/*.sol', config);
149
150
// Process specific patterns
151
const testReports = processPath('test/**/*.sol', {
152
rules: {
153
'foundry-test-functions': 'error',
154
'no-console': 'off'
155
}
156
});
157
158
// With explicit root directory
159
const libReports = processPath(
160
'lib/**/*.sol',
161
config,
162
'/path/to/project'
163
);
164
```
165
166
## Internal Processing Details
167
168
### AST Parsing
169
170
All processing functions use the `@solidity-parser/parser` to parse Solidity code:
171
172
- First attempts parsing with location and range information
173
- Falls back to basic parsing if the enhanced parsing fails
174
- Handles parser errors gracefully by returning them as linting errors
175
176
### Configuration Resolution
177
178
- `processStr` uses configuration as-is with `applyExtends` applied
179
- `processFile` loads configuration via `loadConfigForFile` unless explicit config provided
180
- `processPath` loads base configuration for file filtering, then per-file configs for processing
181
182
### Caching System
183
184
When caching is enabled:
185
186
- Cache is stored in `node_modules/.cache/solhint/.solhintcache.json` by default
187
- Files are skipped if unchanged and previous results had no errors
188
- Cache entries include file hash, config hash, and modification time
189
- Cache is updated after successful processing without errors
190
191
### Error Handling
192
193
- Parse errors are converted to linting reports with ERROR severity
194
- File system errors (missing files, permission issues) throw exceptions
195
- Configuration errors throw exceptions during config loading
196
- Rule execution errors are caught and reported as linting issues
197
198
## Performance Considerations
199
200
- Use `processPath` for batch processing as it optimizes caching across files
201
- Enable caching for repeated runs on large codebases
202
- Consider using explicit configuration to avoid repeated config resolution
203
- Exclude test and mock files when not needed to reduce processing time
204
205
## Cache Management APIs
206
207
The following APIs from `solhint/lib/cache/cache-manager` provide low-level cache functionality:
208
209
### Read Cache
210
211
```javascript { .api }
212
/**
213
* Reads cache data from file system
214
* @param {string} cachePath - Path to cache file
215
* @returns {Object} Cache data object (empty object if file doesn't exist)
216
*/
217
function readCache(cachePath);
218
```
219
220
### Write Cache
221
222
```javascript { .api }
223
/**
224
* Writes cache data to file system
225
* @param {string} cachePath - Path to cache file
226
* @param {Object} cacheData - Cache data to write
227
*/
228
function writeCache(cachePath, cacheData);
229
```
230
231
### Should Lint
232
233
```javascript { .api }
234
/**
235
* Determines if a file should be linted based on cache
236
* @param {string} filePath - Path to file being checked
237
* @param {string} content - Current file content
238
* @param {Object} config - Configuration object
239
* @param {Object} cacheData - Current cache data
240
* @returns {boolean} True if file should be linted
241
*/
242
function shouldLint(filePath, content, config, cacheData);
243
```
244
245
### Update Cache Entry
246
247
```javascript { .api }
248
/**
249
* Updates cache entry for a file
250
* @param {string} filePath - Path to file
251
* @param {string} content - File content
252
* @param {Object} config - Configuration object
253
* @param {Object} cacheData - Cache data to update
254
*/
255
function updateCacheEntry(filePath, content, config, cacheData);
256
```
257
258
**Usage Examples:**
259
260
```javascript
261
const { readCache, writeCache, shouldLint, updateCacheEntry } = require('solhint/lib/cache/cache-manager');
262
263
// Read existing cache
264
const cachePath = 'node_modules/.cache/solhint/.solhintcache.json';
265
const cacheData = readCache(cachePath);
266
267
// Check if file needs linting
268
const filePath = './contracts/Token.sol';
269
const content = fs.readFileSync(filePath, 'utf8');
270
const config = { rules: { 'func-visibility': 'error' } };
271
272
if (shouldLint(filePath, content, config, cacheData)) {
273
// Perform linting...
274
console.log('File needs linting');
275
276
// Update cache after successful linting (no errors)
277
updateCacheEntry(filePath, content, config, cacheData);
278
writeCache(cachePath, cacheData);
279
} else {
280
console.log('File skipped due to cache');
281
}
282
```