-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathlinter.go
More file actions
641 lines (547 loc) · 17.5 KB
/
linter.go
File metadata and controls
641 lines (547 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
/*
* Flow CLI
*
* Copyright Flow Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cadence
import (
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/onflow/flow-cli/internal/util"
cdclint "github.com/onflow/cadence-tools/lint"
cdctests "github.com/onflow/cadence-tools/test/helpers"
"github.com/onflow/cadence/ast"
"github.com/onflow/cadence/common"
cdcerrors "github.com/onflow/cadence/errors"
"github.com/onflow/cadence/parser"
"github.com/onflow/cadence/sema"
"github.com/onflow/cadence/stdlib"
"github.com/onflow/cadence/tools/analysis"
"github.com/onflow/flow-core-contracts/lib/go/contracts"
flowGo "github.com/onflow/flow-go-sdk"
"github.com/onflow/flowkit/v2"
"golang.org/x/exp/maps"
)
type linter struct {
checkers map[string]*sema.Checker
exportedIdentifiers map[string][]ast.Identifier
state *flowkit.State
checkerStandardConfig *sema.Config
checkerScriptConfig *sema.Config
currentLocation common.Location
}
type positionedError interface {
error
ast.HasPosition
}
// Error diagnostic categories
const (
SemanticErrorCategory = "semantic-error"
SyntaxErrorCategory = "syntax-error"
ErrorCategory = "error"
)
var analyzers = maps.Values(cdclint.Analyzers)
func newLinter(state *flowkit.State) *linter {
l := &linter{
checkers: make(map[string]*sema.Checker),
exportedIdentifiers: make(map[string][]ast.Identifier),
state: state,
}
// Create checker configs for both standard and script
// Scripts have a different stdlib than contracts and transactions
l.checkerStandardConfig = l.newCheckerConfig(util.NewStandardLibrary())
l.checkerScriptConfig = l.newCheckerConfig(util.NewScriptStandardLibrary())
return l
}
func (l *linter) lintFile(
filePath string,
) (diagnostics []analysis.Diagnostic, err error) {
code, readErr := l.state.ReadFile(filePath)
if readErr != nil {
return nil, readErr
}
return l.lintCode(code, common.StringLocation(filePath))
}
func (l *linter) lintCode(
code []byte,
location common.Location,
) (diagnostics []analysis.Diagnostic, err error) {
// Recover from panics in the Cadence checker
defer func() {
if r := recover(); r != nil {
// Convert panic to error instead of crashing
err = fmt.Errorf("internal error: %v", r)
}
}()
diagnostics = make([]analysis.Diagnostic, 0)
codeStr := string(code)
l.currentLocation = location
// Parse program & convert any parsing errors to diagnostics
program, parseProgramErr := parser.ParseProgram(nil, code, parser.Config{})
if parseProgramErr != nil {
var parserErr *parser.Error
if !errors.As(parseProgramErr, &parserErr) {
return nil, fmt.Errorf("could not process parsing error: %s", parseProgramErr)
}
checkerDiagnostics, err := getDiagnosticsFromParentError(parserErr, location, codeStr)
if err != nil {
return nil, err
}
diagnostics = append(diagnostics, checkerDiagnostics...)
}
// If the program is nil, nothing can be checked & analyzed so return early
if program == nil {
return diagnostics, nil
}
// Create checker based on program type
checker, err := sema.NewChecker(
program,
location,
nil,
l.decideCheckerConfig(program),
)
if err != nil {
return nil, err
}
// Check the program & convert any checking errors to diagnostics
checkProgramErr := checker.Check()
if checkProgramErr != nil {
var checkerErr *sema.CheckerError
if !errors.As(checkProgramErr, &checkerErr) {
return nil, fmt.Errorf("could not process checking error: %s", checkProgramErr)
}
checkerDiagnostics, err := getDiagnosticsFromParentError(checkerErr, location, codeStr)
if err != nil {
return nil, err
}
diagnostics = append(diagnostics, checkerDiagnostics...)
}
// Run analysis on the program
analysisProgram := analysis.Program{
Program: program,
Checker: checker,
Location: checker.Location,
Code: []byte(code),
}
report := func(diagnostic analysis.Diagnostic) {
diagnostics = append(diagnostics, diagnostic)
}
analysisProgram.Run(analyzers, report)
// Generate synthetic replacements for replacement category diagnostics
// that don't have suggested fixes
for i := range diagnostics {
diagnostic := &diagnostics[i]
if diagnostic.Category == cdclint.ReplacementCategory &&
len(diagnostic.SuggestedFixes) == 0 &&
diagnostic.SecondaryMessage != "" {
// Create a synthetic suggested fix from the secondary message
diagnostic.SuggestedFixes = []cdcerrors.SuggestedFix[ast.TextEdit]{
{
Message: fmt.Sprintf("%s `%s`", diagnostic.Message, diagnostic.SecondaryMessage),
TextEdits: []ast.TextEdit{
{
Range: diagnostic.Range,
Replacement: diagnostic.SecondaryMessage,
},
},
},
}
}
}
return diagnostics, nil
}
// LintCode runs all registered Cadence lint analyzers on inline code.
// This is the public entry point used by the MCP server.
func LintCode(code string, state *flowkit.State) ([]analysis.Diagnostic, error) {
l := newLinter(state)
return l.lintCode([]byte(code), common.StringLocation("code.cdc"))
}
// isContractName returns true if the location string is a contract name (not a file path)
func isContractName(locationString string) bool {
return !strings.HasSuffix(locationString, ".cdc")
}
// resolveContractName attempts to resolve a location to a contract name
func (l *linter) resolveContractName(location common.StringLocation) string {
locationString := location.String()
// If it's already a contract name, return it
if isContractName(locationString) {
return locationString
}
// Otherwise, try to find the contract by file path
if l.state == nil {
return ""
}
contracts := l.state.Contracts()
if contracts == nil {
return ""
}
// Normalize the location path
absLocation, err := filepath.Abs(locationString)
if err != nil {
absLocation = locationString
}
// Search for matching contract
for _, contract := range *contracts {
contractPath := contract.Location
absContractPath, err := filepath.Abs(contractPath)
if err != nil {
absContractPath = contractPath
}
if absLocation == absContractPath {
return contract.Name
}
}
return ""
}
// checkAccountAccess determines if checker and member locations are on the same account
func (l *linter) checkAccountAccess(checker *sema.Checker, memberLocation common.Location) bool {
// If both are AddressLocation, directly compare addresses
if checkerAddr, ok := checker.Location.(common.AddressLocation); ok {
if memberAddr, ok := memberLocation.(common.AddressLocation); ok {
return checkerAddr.Address == memberAddr.Address
}
}
// For StringLocations, resolve to contract names and check deployments
checkerLocation, ok := checker.Location.(common.StringLocation)
if !ok {
return false
}
memberStringLocation, ok := memberLocation.(common.StringLocation)
if !ok {
return false
}
checkerContractName := l.resolveContractName(checkerLocation)
if checkerContractName == "" {
return false
}
memberContractName := l.resolveContractName(memberStringLocation)
if memberContractName == "" {
return false
}
if l.state == nil {
return false
}
// Check across all networks if they're deployed to the same account
networks := l.state.Networks()
if networks == nil {
return false
}
// Build contract name -> address mapping per network
for _, network := range *networks {
contractNameToAddress := make(map[string]flowGo.Address)
// Add aliases first
contracts := l.state.Contracts()
if contracts != nil {
for _, contract := range *contracts {
if alias := contract.Aliases.ByNetwork(network.Name); alias != nil {
contractNameToAddress[contract.Name] = alias.Address
}
}
}
// Add deployments (overwrites aliases, giving deployments priority)
deployedContracts, err := l.state.DeploymentContractsByNetwork(network)
if err == nil {
for _, deployedContract := range deployedContracts {
contract, err := l.state.Contracts().ByName(deployedContract.Name)
if err == nil {
address, err := l.state.ContractAddress(contract, network)
if err == nil && address != nil {
contractNameToAddress[deployedContract.Name] = *address
}
}
}
}
// Check if both contracts exist at the same address on this network
checkerAddress, checkerExists := contractNameToAddress[checkerContractName]
memberAddress, memberExists := contractNameToAddress[memberContractName]
if checkerExists && memberExists && checkerAddress == memberAddress {
return true
}
}
return false
}
// Create a new checker config with the given standard library
func (l *linter) newCheckerConfig(standardLibrary *util.StandardLibrary) *sema.Config {
return &sema.Config{
BaseValueActivationHandler: func(location common.Location) *sema.VariableActivation {
return standardLibrary.BaseValueActivation
},
MemberAccountAccessHandler: func(checker *sema.Checker, memberLocation common.Location) bool {
return l.checkAccountAccess(checker, memberLocation)
},
AccessCheckMode: sema.AccessCheckModeNotSpecifiedUnrestricted,
PositionInfoEnabled: true, // Must be enabled for linters
ExtendedElaborationEnabled: true, // Must be enabled for linters
ImportHandler: l.handleImport,
LocationHandler: l.resolveLocation,
SuggestionsEnabled: true, // Must be enabled to offer semantic suggestions
}
}
// Choose the checker config based on the assumed type of the program
func (l *linter) decideCheckerConfig(program *ast.Program) *sema.Config {
if program.SoleTransactionDeclaration() != nil || program.SoleContractDeclaration() != nil {
return l.checkerStandardConfig
}
return l.checkerScriptConfig
}
// Resolve any imports found in the program while checking
func (l *linter) handleImport(
checker *sema.Checker,
importedLocation common.Location,
_ ast.Range,
) (
sema.Import,
error,
) {
switch importedLocation {
case stdlib.TestContractLocation:
testChecker := stdlib.GetTestContractType().Checker
return sema.ElaborationImport{
Elaboration: testChecker.Elaboration,
}, nil
case cdctests.BlockchainHelpersLocation:
helpersChecker := cdctests.BlockchainHelpersChecker()
return sema.ElaborationImport{
Elaboration: helpersChecker.Elaboration,
}, nil
case stdlib.CryptoContractLocation:
cryptoChecker, ok := l.checkers[stdlib.CryptoContractLocation.String()]
if !ok {
cryptoCode := contracts.Crypto()
cryptoProgram, err := parser.ParseProgram(nil, cryptoCode, parser.Config{})
if err != nil {
return nil, err
}
if cryptoProgram == nil {
return nil, &sema.CheckerError{
Errors: []error{fmt.Errorf("cannot parse Crypto contract")},
}
}
cryptoChecker, err = sema.NewChecker(
cryptoProgram,
stdlib.CryptoContractLocation,
nil,
l.checkerStandardConfig,
)
if err != nil {
return nil, err
}
err = cryptoChecker.Check()
if err != nil {
return nil, err
}
l.checkers[stdlib.CryptoContractLocation.String()] = cryptoChecker
}
return sema.ElaborationImport{
Elaboration: cryptoChecker.Elaboration,
}, nil
default:
// Normalize relative path imports to absolute paths
if util.IsPathLocation(importedLocation) {
importedLocation = util.NormalizePathLocation(checker.Location, importedLocation)
}
filepath, err := l.resolveImportFilepath(importedLocation, checker.Location)
if err != nil {
return nil, err
}
fileLocation := common.StringLocation(filepath)
importedChecker, ok := l.checkers[filepath]
if !ok {
code, err := l.state.ReadFile(filepath)
if err != nil {
return nil, err
}
importedProgram, err := parser.ParseProgram(nil, code, parser.Config{})
if err != nil {
return nil, err
}
if importedProgram == nil {
return nil, &sema.CheckerError{
Errors: []error{fmt.Errorf("cannot import %s", importedLocation)},
}
}
importedChecker, err = checker.SubChecker(importedProgram, fileLocation)
if err != nil {
return nil, err
}
l.checkers[filepath] = importedChecker
// Pre-populate so resolveLocation doesn't re-parse during sub-checking
l.exportedIdentifiers[filepath] = exportedIdentifiersFromProgram(importedProgram)
prevLocation := l.currentLocation
l.currentLocation = fileLocation
err = importedChecker.Check()
l.currentLocation = prevLocation
if err != nil {
return nil, err
}
}
return sema.ElaborationImport{
Elaboration: importedChecker.Elaboration,
}, nil
}
}
func (l *linter) resolveImportFilepath(
location common.Location,
parentLocation common.Location,
) (
string,
error,
) {
switch location := location.(type) {
case common.StringLocation:
// Resolve by contract name from flowkit config
if !strings.Contains(location.String(), ".cdc") {
contract, err := l.state.Contracts().ByName(location.String())
if err != nil {
return "", err
}
return contract.Location, nil
}
return location.String(), nil
default:
return "", fmt.Errorf("unsupported location: %T", location)
}
}
// resolveLocation is the LocationHandler for the sema.Checker config.
// For implicit imports (no explicit identifiers), it resolves the exported names
// from the imported file so the unused-import analyzer can track usage.
func (l *linter) resolveLocation(
identifiers []ast.Identifier,
location common.Location,
) ([]sema.ResolvedLocation, error) {
defaultResolution := []sema.ResolvedLocation{{
Location: location,
Identifiers: identifiers,
}}
// Explicit imports already carry their identifiers — nothing to add
if len(identifiers) > 0 {
return defaultResolution, nil
}
// Only handle string locations (path-based or contract-name imports)
if _, ok := location.(common.StringLocation); !ok {
return defaultResolution, nil
}
// Normalize relative path imports against the current file's location,
// then resolve to a file path (handles both .cdc paths and contract names)
resolvedLoc := location
if l.currentLocation != nil && util.IsPathLocation(location) {
resolvedLoc = util.NormalizePathLocation(l.currentLocation, location)
}
filePath, err := l.resolveImportFilepath(resolvedLoc, l.currentLocation)
if err != nil {
return defaultResolution, nil
}
exportedIdents := l.getExportedIdentifiers(filePath)
if len(exportedIdents) == 0 {
return defaultResolution, nil
}
return []sema.ResolvedLocation{{
Location: location,
Identifiers: exportedIdents,
}}, nil
}
func (l *linter) getExportedIdentifiers(filePath string) []ast.Identifier {
if cached, ok := l.exportedIdentifiers[filePath]; ok {
return cached
}
code, err := l.state.ReadFile(filePath)
if err != nil {
return nil
}
program, err := parser.ParseProgram(nil, code, parser.Config{})
if err != nil || program == nil {
return nil
}
identifiers := exportedIdentifiersFromProgram(program)
l.exportedIdentifiers[filePath] = identifiers
return identifiers
}
func exportedIdentifiersFromProgram(program *ast.Program) []ast.Identifier {
var identifiers []ast.Identifier
for _, decl := range program.Declarations() {
identifier := decl.DeclarationIdentifier()
if identifier == nil {
continue
}
if decl.DeclarationAccess() != ast.AccessAll {
continue
}
identifiers = append(identifiers, *identifier)
}
return identifiers
}
// helpers
func getDiagnosticsFromParentError(err cdcerrors.ParentError, location common.Location, code string) ([]analysis.Diagnostic, error) {
diagnostics := make([]analysis.Diagnostic, 0)
for _, childErr := range err.ChildErrors() {
var positionedErr positionedError
if !errors.As(childErr, &positionedErr) {
return nil, fmt.Errorf("could not process error: %s", childErr)
}
diagnostic := convertPositionedErrorToDiagnostic(positionedErr, location, code)
if diagnostic == nil {
continue
}
diagnostics = append(diagnostics, *diagnostic)
}
return diagnostics, nil
}
func convertPositionedErrorToDiagnostic(
err positionedError,
location common.Location,
code string,
) *analysis.Diagnostic {
message := err.Error()
startPosition := err.StartPosition()
endPosition := err.EndPosition(nil)
var secondaryMessage string
var secondaryErr cdcerrors.SecondaryError
if errors.As(err, &secondaryErr) {
secondaryMessage = secondaryErr.SecondaryError()
}
var category string
var semanticErr sema.SemanticError
var parseError parser.ParseError
switch {
case errors.As(err, &semanticErr):
category = SemanticErrorCategory
case errors.As(err, &parseError):
category = SyntaxErrorCategory
default:
category = ErrorCategory
}
var suggestedFixes []cdcerrors.SuggestedFix[ast.TextEdit]
var errWithFixes cdcerrors.HasSuggestedFixes[ast.TextEdit]
if errors.As(err, &errWithFixes) {
suggestedFixes = errWithFixes.SuggestFixes(code)
}
diagnostic := analysis.Diagnostic{
Location: location,
Category: category,
Message: message,
SecondaryMessage: secondaryMessage,
Range: ast.Range{
StartPos: startPosition,
EndPos: endPosition,
},
SuggestedFixes: suggestedFixes,
}
return &diagnostic
}
func isErrorDiagnostic(diagnostic analysis.Diagnostic) bool {
return diagnostic.Category == ErrorCategory || diagnostic.Category == SemanticErrorCategory || diagnostic.Category == SyntaxErrorCategory
}