The API reference for sift: 38 modules and 547 exported names,
generated from the source and the docstrings in it. They are 388
procedures, 103 macros, 3 parameters, 9 record types and 44 variables.
Every module has a section of its own and every name links to its
definition; the index filters all of them.
Source under the docstring to read the form the module holds, coloured like the
Scheme it is.
/ and type
in the index filter.
This chapter is generated from the source and the docstrings beside it. To correct a definition, change the source or its docstring and rebuild the manual; an edit to this page is lost.
This is the half of ‘(sift lsp)’ that is a function of a buffer, a cursor and a set of indexed files: positions, documents, the workspace record, definition, references, highlights, the outline, completion, rename, hover, signature help and inlay hints. The other half – the JSON-RPC wire, the server loop, the diagnostics, the code actions and the reading of a project off a disk – stayed there, and needs all of this.
It is a module of its own because a second kind of caller exists: one that holds a single buffer and no project at all. Nothing here touches a file – a workspace is filled by a scan the caller installs, an indexed file is loaded by a loader the caller installs, and a build with neither answers about what it was handed. ‘(sift lsp)’ installs both, because it has a directory to read; a caller that has none installs nothing and passes an empty workspace, and gets the same answers about the one buffer it has.
The questions are the same questions either way, which is the point: an editor in a tab and an editor beside a checkout get one implementation of "where is this defined", not two that agree until they do not.
#f when it is not
one.
#t when deadline has passed.
#f.
(uri text definition) for name’s file-level
definitions.
(uri text) for the indexed files read in dialect.
#f.
#f for no limit.
#t when an open buffer answers for path instead.
file: URI that names path.
WorkspaceEdit renaming the symbol at index
everywhere.
file: URI names, or uri unchanged.
#f.
#t when name can be written as a Lisp symbol.
(uri text definition) for every file-level definition of
name.
(status done total) for the index of workspace.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Default value:
#<procedure 7f1815b8ece0 at sift/analysis.scm:511:3 (dialect name)>
(define current-stdlib
(make-parameter
(lambda (dialect name)
"Return the places @var{dialect}'s standard library defines @var{name}."
'())))
Default value:
#<procedure 7f1815b8ecf0 at sift/analysis.scm:517:3 (dialect prefix)>
(define current-stdlib-names
(make-parameter
(lambda (dialect prefix)
"Return the names @var{dialect}'s standard library offers, matching PREFIX."
'())))
Return the AST of text, read as dialect.
(define (ast-of-text text dialect)
"Return the AST of @var{text}, read as @var{dialect}."
(call-with-values
(lambda () (read-source #:source text #:dialect dialect))
(lambda (ast errors) ast)))
Remember ast as the parse of text for document.
(define (cache-document-ast! document text ast)
"Remember @var{ast} as the parse of @var{text} for @var{document}."
(atomic-box-set! (document-ast-box document) (cons text ast)))
Return value as a document version, or #f when it is not
one.
The protocol says a version is an integer, and a client that sends a
JSON null – or a string, or nothing at all – is a client sift
should keep answering rather than one whose document is stored under a
version no comparison can use.
(define (client-version value)
"Return @var{value} as a document version, or @code{#f} when it is not one.
The protocol says a version is an integer, and a client that sends a JSON
@code{null} -- or a string, or nothing at all -- is a client sift should keep
answering rather than one whose document is stored under a version no
comparison can use."
(and (number? value) value))
Return the names the buffer and the project define, as ranked items.
(define (completion-items workspace documents uri text dialect index)
"Return the names the buffer and the project define, as ranked items."
(let* ((local (filter (lambda (definition) (not (definition-scope definition)))
(parse-definitions (ast-of-text text dialect))))
(prefix (symbol-prefix-at text index))
(kinds (make-hash-table))
(names '()))
(define (add name kind local?)
(unless (hash-ref kinds name)
(hash-set! kinds name (cons (completion-kind kind) local?)))
(unless (member name names) (set! names (cons name names))))
(for-each (lambda (definition)
(add (definition-name definition) (definition-kind definition) #t))
local)
(hash-for-each
(lambda (other-uri document)
(when (and (not (string=? other-uri uri))
(eq? (document-dialect document) dialect))
(let ((ast (document-ast-of document)))
(when ast
(for-each (lambda (definition)
(add (definition-name definition)
(definition-kind definition) #f))
(filter (lambda (definition)
(not (definition-scope definition)))
(parse-definitions ast)))))))
documents)
(for-each (lambda (name) (add name 'variable #f))
(workspace-names workspace dialect #:open (open-paths documents)))
;; The standard library is offered last and only for what is being typed: a
;; library holds twenty thousand names on a machine with one of each
;; installed, and a list that long is not a completion, it is a directory.
(for-each (lambda (entry) (add (car entry) (cdr entry) #f))
((current-stdlib-names) dialect prefix))
(list->vector
(map (lambda (entry)
(let* ((name (cdr entry))
(kind (car (hash-ref kinds name))))
(json-object (field "label" name)
(field "kind" kind)
(field "sortText" (car entry)))))
(sort (map (lambda (name)
(cons (completion-rank name prefix
(cdr (hash-ref kinds name)))
name))
names)
(lambda (a b) (string<? (car a) (car b))))))))
Return #t when deadline has passed.
(define (deadline-expired? deadline)
"Return @code{#t} when @var{deadline} has passed."
(and deadline (>= (now-in-jiffies) deadline)))
Return every place the symbol at index is defined, in the project.
The parse the buffer already has is used when it is the parse of its current text. When it is not, the answer is the one the index can give about the name under the cursor: a jump never replaces a stale parse, because the read that would replace it is the read an editor waits on. A caller that keeps no documents at all – the web editor answers about one buffer and nothing else – has no parse to reuse and no index to fall back on, so the buffer is read here.
(define* (definition-sites workspace documents uri text dialect index
#:key deadline)
"Return every place the symbol at @var{index} is defined, in the project.
The parse the buffer already has is used when it is the parse of its current
text. When it is not, the answer is the one the index can give about the name
under the cursor: a jump never replaces a stale parse, because the read that
would replace it is the read an editor waits on. A caller that keeps no
documents at all -- the web editor answers about one buffer and nothing else --
has no parse to reuse and no index to fall back on, so the buffer is read here."
(let* ((document (hash-ref documents uri #f))
(ast (if document
(document-ast-of document)
(ast-of-text text dialect))))
(if ast
(definition-sites-in ast workspace documents uri text dialect index
#:deadline deadline)
(let ((name (symbol-at-index text index)))
(if (not name)
'()
(append (document-definition-sites documents name dialect uri)
(workspace-definition-sites
workspace name dialect #:open (open-paths documents))
(if (deadline-expired? deadline) '()
((current-stdlib) dialect name))))))))
Return the dialect a buffer is read as.
The client’s language identifier is the first word; the file’s own extension answers when the identifier is something sift has never seen – and when it is not a string at all, which is what a client that has no language for the file sends. A server that raised here would have no document to answer about for the rest of the session.
(define (dialect-of language-id uri)
"Return the dialect a buffer is read as.
The client's language identifier is the first word; the file's own extension
answers when the identifier is something sift has never seen -- and when it is
not a string at all, which is what a client that has no language for the file
sends. A server that raised here would have no document to answer about for
the rest of the session."
(or (and (string? language-id) (string->dialect language-id))
(and (string? uri) (detect-dialect #:file (strip-uri uri)))
'scheme))
Return the parse of document’s current text, or #f.
The answer is #f when the buffer has changed since it was parsed:
the caller then answers from the index, or says it cannot answer yet,
rather than reading a file-sized buffer on the path an editor waits on.
(define (document-ast-of document)
"Return the parse of @var{document}'s current text, or @code{#f}.
The answer is @code{#f} when the buffer has changed since it was parsed: the
caller then answers from the index, or says it cannot answer yet, rather than
reading a file-sized buffer on the path an editor waits on."
(let ((cached (atomic-box-ref (document-ast-box document))))
(and cached
(string=? (car cached) (document-text document))
(cdr cached))))
Return the range that covers all of text.
(define (document-range text)
"Return the range that covers all of @var{text}."
(cons 0 (string-length text)))
Return the extraction actions that apply to start..end.
(define* (extract-actions text dialect start end #:key (uri "") (version #f))
"Return the extraction actions that apply to @var{start}..@var{end}."
(let ((ast (ast-of-text text dialect)))
(filter identity
(list (extract-lambda-definition text ast start end
#:uri uri #:version version)
(extract-lambda text ast start end #:uri uri #:version version)
(extract-to-let text ast start end #:uri uri #:version version)
(extract-to-procedure text ast start end
#:uri uri #:version version)))))
Return the JSON object member name with value.
(define (field name value)
"Return the JSON object member @var{name} with @var{value}."
(cons name value))
Undocumented procedure.
(define (form-end node) (source-location-index (node-end node)))
Undocumented procedure.
(define (form-start node) (source-location-index (node-start node)))
Return the names the indexed files define in dialect, without repeats.
A name only an open buffer still defines is not a name the index has, so open takes those files out of the answer.
(define* (index-names-of index dialect #:key (open #f))
"Return the names the indexed files define in @var{dialect}, without repeats.
A name only an open buffer still defines is not a name the index has, so
@var{open} takes those files out of the answer."
(let ((names '()))
(hash-for-each
(lambda (name entries)
(when (any (lambda (entry)
(and (eq? dialect (indexed-file-dialect entry))
(not (open-buffer-path? open (indexed-file-path entry)))))
entries)
(set! names (cons name names))))
(index-names index))
(reverse names)))
Return an index holding entries, with generation as its own.
(define (index-of-files entries generation)
"Return an index holding @var{entries}, with @var{generation} as its own."
(let ((files (make-hash-table)) (names (make-hash-table)))
(for-each
(lambda (entry)
(hash-set! files (indexed-file-path entry) entry)
(for-each (lambda (name)
(hash-set! names name
(cons entry (hash-ref names name '()))))
(indexed-file-names entry)))
entries)
(make-index files names generation)))
Return the character index of an LSP position in text.
(define (index-of-text-position text position)
"Return the character index of an LSP @var{position} in @var{text}."
(index-of-position text
(json-ref position "line" 0)
(json-ref position "character" 0)))
Return (uri text definition) for name’s file-level
definitions.
Only the files whose remembered names include name are looked at, and a file the cache did not read is not read here: a jump is answered from the snapshot, or not at all until the indexer has the file. That is what keeps the answer to a request independent of the size of the project.
open is the paths the editor holds a buffer for, and they are not answered from here: the buffer is the authority on its own text.
(define* (index-sites index name dialect #:key (open #f))
"Return @code{(uri text definition)} for @var{name}'s file-level definitions.
Only the files whose remembered names include @var{name} are looked at, and a
file the cache did not read is not read here: a jump is answered from the
snapshot, or not at all until the indexer has the file. That is what keeps
the answer to a request independent of the size of the project.
@var{open} is the paths the editor holds a buffer for, and they are not
answered from here: the buffer is the authority on its own text."
(let ((sites '()))
(for-each
(lambda (entry)
(when (and (eq? dialect (indexed-file-dialect entry))
(indexed-file-definitions entry)
(not (open-buffer-path? open (indexed-file-path entry))))
(for-each
(lambda (definition)
(when (and (not (definition-scope definition))
(string=? name (definition-name definition)))
(set! sites
(cons (list (path->uri (indexed-file-path entry))
(indexed-file-text entry) definition)
sites))))
(indexed-file-definitions entry))))
(hash-ref (index-names index) name '()))
(reverse sites)))
Return (uri text) for the indexed files read in dialect.
except-uri is the buffer the question came from, and open the paths the editor holds a buffer for: their text is the buffer’s, not this copy’s.
(define* (index-texts index dialect except-uri #:key (open #f))
"Return @code{(uri text)} for the indexed files read in @var{dialect}.
@var{except-uri} is the buffer the question came from, and @var{open} the
paths the editor holds a buffer for: their text is the buffer's, not this
copy's."
(let ((texts '()))
(hash-for-each
(lambda (path entry)
(let ((uri (path->uri path)))
(when (and (indexed-file-text entry)
(eq? dialect (indexed-file-dialect entry))
(not (string=? uri except-uri))
(not (open-buffer-path? open path)))
(set! texts (cons (list uri (indexed-file-text entry)) texts)))))
(index-files index))
(reverse texts)))
Return the inlining actions that apply to start..end.
(define* (inline-actions text dialect start end #:key (uri "") (version #f))
"Return the inlining actions that apply to @var{start}..@var{end}."
(let ((ast (ast-of-text text dialect)))
(filter identity
(list (inline-call text ast start end #:uri uri #:version version)))))
Return the LSP range from start to end in text.
(define (json-range text start end)
"Return the LSP range from @var{start} to @var{end} in @var{text}."
(json-object
(field "start" (json-position text start))
(field "end" (json-position text end))))
Return the locations the symbol at index is defined at, as an array.
(define* (lsp-definition workspace documents uri text dialect index #:key deadline)
"Return the locations the symbol at @var{index} is defined at, as an array."
(list->vector
(map (lambda (site)
(definition-location (car site) (cadr site) (caddr site)))
(definition-sites workspace documents uri text dialect index
#:deadline deadline))))
Return every mention of the symbol at index in text.
(define (lsp-document-highlights text dialect index)
"Return every mention of the symbol at @var{index} in @var{text}."
(let* ((ast (ast-of-text text dialect))
(name (resolve-name ast index)))
(if (not name)
(vector)
(let ((declarations
(map (lambda (definition) (definition-index definition))
(definitions-by-name ast name))))
(list->vector
(map (lambda (node)
(json-object
(field "range" (json-range text (form-start node) (form-end node)))
;; 2 is a read, 3 a write: the declaration is where the name
;; is written, and its mentions are where it is read.
(field "kind" (if (memv (form-start node) declarations) 3 2))))
(occurrences-of ast name)))))))
Return the outline of text: every definition, nested.
(define* (lsp-document-symbols text #:key (dialect 'scheme))
"Return the outline of @var{text}: every definition, nested."
(list->vector
(map (lambda (entry) (document-symbol-of entry text))
(document-symbol-tree (ast-of-text text dialect)))))
Return the inlay hints for the calls of text between start and end, as the array an editor expects.
The range decides what is answered, not only what is looked at: a hint is emitted for an argument that *starts* inside it, which is what an editor asks for – the part of the file it is showing – and which keeps a long file from being resolved a form at a time for hints nobody will see.
The walk is over forms rather than over every list, because a parameter list is a list and is not a call: ‘(define (make-window parent width) ...)’ has a ‘parent’ in argument position that nothing is being passed to, and a hint there would be sift describing a definition as if it were a call to itself.
kinds is what the configuration asked for: ‘parameters’ names a call’s positional arguments from the definition, and ‘types’ says what type an argument states outright. Both can be on at once, and then a reader gets ‘width’ followed by ‘number’ on the same argument – the name from the definition, the type from the source.
(define* (lsp-inlay-hints workspace documents uri text dialect start end
#:key (kinds '(parameters)))
"Return the inlay hints for the calls of @var{text} between @var{start} and
@var{end}, as the array an editor expects.
The range decides what is answered, not only what is looked at: a hint is
emitted for an argument that *starts* inside it, which is what an editor asks
for -- the part of the file it is showing -- and which keeps a long file from
being resolved a form at a time for hints nobody will see.
The walk is over forms rather than over every list, because a parameter list
is a list and is not a call: `(define (make-window parent width) ...)' has a
`parent' in argument position that nothing is being passed to, and a hint
there would be sift describing a definition as if it were a call to itself.
@var{kinds} is what the configuration asked for: `parameters' names a call's
positional arguments from the definition, and `types' says what type an
argument states outright. Both can be on at once, and then a reader gets
`width' followed by `number' on the same argument -- the name from the
definition, the type from the source."
(let ((hints '())
(ast (ast-of-text text dialect))
(wanted? (lambda (kind) (memq kind kinds))))
(for-each-form
(lambda (node)
(when (and (call-form? node)
(let ((head (node-head node)))
(and head (node-atom? head)
(eq? (node-atom-type head) 'symbol))))
(let ((arguments (form-arguments node)))
;; the cheap question first: is any of this call's arguments in the
;; part of the file the editor is showing?
(when (any (lambda (argument)
(let ((index (source-location-index (node-start argument))))
(and (>= index start) (<= index end))))
arguments)
(let ((formals (and (wanted? 'parameters)
(call-formals ast workspace documents uri text
dialect node))))
(let loop ((rest arguments) (position 0) (named? #t))
(unless (null? rest)
(let* ((argument (car rest))
(index (source-location-index (node-start argument)))
(keyword? (keyword-node? argument))
(name (and named? (not keyword?)
(argument-name-at formals position)))
(type (and (wanted? 'types) (obvious-type argument)))
(here? (and (>= index start) (<= index end))))
(when here?
;; the name first: `width' is what the argument is, and
;; `number' is what it is made of
(when name
(set! hints
(cons (inlay-hint name (json-position text index) 2)
hints)))
(when type
(set! hints
(cons (inlay-hint type (json-position text index) 1)
hints))))
(loop (cdr rest)
(if (or (not named?) keyword?) position (+ position 1))
(and named? (not keyword?)))))))))))
ast)
(list->vector (reverse hints))))
Return every location in the project that mentions the symbol at index.
A name bound by a form is not a name the project has: ‘(let ((x 1)) x)’ makes an ‘x’ that has nothing to do with the ‘x’ of the file next door, and answering with every ‘x’ in the project would be answering a question nobody asked. So a mention of a binding is looked for inside the form that binds it, and a mention of anything else is looked for in the project, which is where a definition lives.
(define* (lsp-references workspace documents uri text dialect index
#:key (include-declaration #t) deadline)
"Return every location in the project that mentions the symbol at @var{index}.
A name bound by a form is not a name the project has: `(let ((x 1)) x)' makes
an `x' that has nothing to do with the `x' of the file next door, and answering
with every `x' in the project would be answering a question nobody asked. So a
mention of a binding is looked for inside the form that binds it, and a mention
of anything else is looked for in the project, which is where a definition
lives."
(let* ((document (hash-ref documents uri #f))
(ast (and document (document-ast-of document)))
(name (or (and ast (resolve-name ast index))
(symbol-at-index text index)))
(definition (and ast name (resolve-definition ast index)))
(scope (and definition (definition-scope definition))))
(cond
[(not name) (vector)]
[scope
(let ((start (form-start scope))
(end (form-end scope)))
(list->vector
(filter-map
(lambda (node)
(and (<= start (form-start node))
(< (form-start node) end)
(or include-declaration
(not (eq? node (definition-node definition))))
(reference-location uri text node)))
(occurrences-of ast name))))]
[else
(let ((locations '()))
(for-each
(lambda (site)
(unless (deadline-expired? deadline)
(let* ((site-uri (car site))
(site-text (cadr site))
(site-document (hash-ref documents site-uri #f))
(site-ast (or (and site-document
(document-ast-of site-document))
(ast-of-text site-text dialect)))
(declarations
(map (lambda (candidate) (definition-index candidate))
(definitions-by-name site-ast name))))
(for-each
(lambda (node)
(unless (and (not include-declaration)
(memv (form-start node) declarations))
(set! locations
(cons (reference-location site-uri site-text node)
locations))))
(occurrences-of site-ast name)))))
(project-texts workspace documents uri text dialect))
(list->vector (reverse locations)))])))
Return the signature of the call the cursor is in, or #f.
The signature is the one sift can know: the definition’s parameter list, read the way the arity rule reads it, so the editor shows the keyword names, the optional and rest parameters, and which of them is being written. A procedure from a library sift cannot read has no signature here, and answering with an invented one would be worse than answering nothing.
(define* (lsp-signature-help workspace documents uri text dialect index)
"Return the signature of the call the cursor is in, or @code{#f}.
The signature is the one sift can know: the definition's parameter list, read
the way the arity rule reads it, so the editor shows the keyword names, the
optional and rest parameters, and which of them is being written. A procedure
from a library sift cannot read has no signature here, and answering with an
invented one would be worse than answering nothing."
(let* ((ast (ast-of-text text dialect))
(call (or (call-at ast index)
;; A call that takes nothing has no argument for the cursor
;; to be in, which is exactly the call whose signature a
;; reader most wants to be shown.
(call-with-values (lambda () (form-at ast index))
(lambda (node ancestors)
(let ((form (cond
[(and node (node-list? node)) node]
[(and node (pair? ancestors))
(car ancestors)]
[else #f])))
(and form (node-list? form)
(let ((head (node-head form)))
(and head (node-atom? head)
(eq? (node-atom-type head) 'symbol)
(null? (form-arguments form))
form)))))))))
(and call
(let ((head (node-head call)))
(let* ((sites (signature-sites ast workspace documents uri text dialect
(source-location-index (node-start head))))
(site (and (pair? sites) (car sites)))
(definition (and site (caddr site)))
(definition-text (and site (cadr site)))
(signature (and definition (definition-form definition)
(form-signature (definition-form definition))))
(parameters (and signature (caddr signature))))
(and signature (list? parameters)
(let* ((name (definition-name definition))
(labels (map (lambda (parameter)
(parameter-label parameter definition-text dialect))
parameters))
(label (if (null? labels)
(format #f "(~a)" name)
(format #f "(~a ~a)" name (string-join labels " "))))
(arity (cons (car signature) (cadr signature)))
(summary (arity-summary arity dialect))
(documentation (documentation-text
(definition-docstring definition))))
(json-object
(field "signatures"
(vector
(json-object
(field "label" label)
(field "parameters"
(list->vector
(map (lambda (parameter-text)
(json-object (field "label" parameter-text)))
labels)))
(field "documentation"
(json-object
(field "kind" "markdown")
(field "value"
(if (string? documentation)
documentation
summary)))))))
(field "activeSignature" 0)
(field "activeParameter" (active-parameter call index parameters))))))))))
Return a moment milliseconds from now, or #f for no limit.
A request that must answer within a bound checks the clock between the steps that can take a while. Threads cannot be interrupted safely here, so the bound is kept by not starting work that would pass it, which is why every loop that can be long takes a deadline.
(define (make-deadline milliseconds)
"Return a moment @var{milliseconds} from now, or @code{#f} for no limit.
A request that must answer within a bound checks the clock between the steps
that can take a while. Threads cannot be interrupted safely here, so the
bound is kept by not starting work that would pass it, which is why every loop
that can be long takes a deadline."
(and milliseconds
(+ (now-in-jiffies)
(quotient (* milliseconds (jiffies-per-second)) 1000))))
Return a document about which nothing has been published yet.
(define (new-document uri text language-id version dialect) "Return a document about which nothing has been published yet." (make-document uri text language-id version dialect #f (make-atomic-box #f)))
Return an empty workspace, with filter for the globs a project names.
A workspace starts with no root and nothing in it. ‘(sift index)’ fills it from a directory in a thread of its own; a caller that has no directory reads the empty index and answers about the buffers it was given.
(define* (new-workspace #:optional (filter #f))
"Return an empty workspace, with @var{filter} for the globs a project names.
A workspace starts with no root and nothing in it. `(sift index)' fills it
from a directory in a thread of its own; a caller that has no directory reads
the empty index and answers about the buffers it was given."
(make-workspace #f filter (make-atomic-box empty-index)
(make-atomic-box 'uninitialized)
(make-atomic-box 0) (make-atomic-box 0) #f #f))
Return #t when an open buffer answers for path instead.
(define (open-buffer-path? open path)
"Return @code{#t} when an open buffer answers for @var{path} instead."
(and open (hash-ref open path)))
Return the file paths the editor holds a buffer for, as a hash table.
A buffer that is not a file – an editor’s scratch document – names no path and is left out; nothing in the index is about it.
(define (open-paths documents)
"Return the file paths the editor holds a buffer for, as a hash table.
A buffer that is not a file -- an editor's scratch document -- names no path
and is left out; nothing in the index is about it."
(let ((paths (make-hash-table)))
(hash-for-each
(lambda (uri document)
(when (string-prefix? "file://" uri)
(hash-set! paths (strip-uri uri) #t)))
documents)
paths))
Return the file: URI that names path.
(define (path->uri path)
"Return the @code{file:} URI that names @var{path}."
(format #f "file://~a" (percent-encode path)))
Return text with everything outside the URI path alphabet escaped.
(define (percent-encode text)
"Return @var{text} with everything outside the URI path alphabet escaped."
(call-with-output-string
(lambda (out)
(string-for-each
(lambda (character)
(if (or (char-alphabetic? character) (char-numeric? character)
(memv character '(#\/ #\- #\_ #\. #\~ #\+)))
(display character out)
(let ((hex (string-upcase (number->string (char->integer character) 16))))
(display #\% out)
(when (< (string-length hex) 2) (display #\0 out))
(display hex out))))
text))))
Return (line . column) for the character index of
text.
(define (position-of text index)
"Return @code{(line . column)} for the character @var{index} of @var{text}."
(let ((limit (min (max index 0) (string-length text))))
(let loop ((i 0) (line 0) (column 0))
(if (>= i limit)
(cons line column)
(let ((c (string-ref text i)))
(if (char=? c #\newline)
(loop (+ i 1) (+ line 1) 0)
(loop (+ i 1) line (+ column (utf16-width c)))))))))
Publish index as the workspace’s own, and say how far the scan is.
(define (publish-workspace-index! workspace index status done total)
"Publish @var{index} as the workspace's own, and say how far the scan is."
(atomic-box-set! (workspace-done-box workspace) done)
(atomic-box-set! (workspace-total-box workspace) total)
(atomic-box-set! (workspace-status-box workspace) status)
(when (eq? status 'ready)
(set-workspace-scanned! workspace #t))
(atomic-box-set! (workspace-index-box workspace) index))
Return (start . end) character indices for a request’s range.
(define (range-of-request text params)
"Return @code{(start . end)} character indices for a request's range."
(let ((range (json-ref params "range" (json-object))))
(cons (index-of-text-position text (json-ref range "start" (json-object)))
(index-of-text-position text (json-ref range "end" (json-object))))))
Return a WorkspaceEdit renaming the symbol at index
everywhere.
A name bound by a form is renamed inside the form that binds it: the ‘x’ of one ‘let’ is not the ‘x’ of the next, and a project-wide rename of a parameter would rewrite code the reader never pointed at. A file-level definition has no such scope and is renamed across the project.
The buffer the rename started in carries the version it was computed from, so an editor will not apply the edit over typing that arrived in the meantime.
(define* (rename-edit workspace documents uri text dialect index new-name
#:key (version #f))
"Return a @code{WorkspaceEdit} renaming the symbol at @var{index} everywhere.
A name bound by a form is renamed inside the form that binds it: the `x' of
one `let' is not the `x' of the next, and a project-wide rename of a
parameter would rewrite code the reader never pointed at. A file-level
definition has no such scope and is renamed across the project.
The buffer the rename started in carries the version it was computed from, so
an editor will not apply the edit over typing that arrived in the meantime."
(let* ((ast (ast-of-text text dialect))
(name (resolve-name ast index))
(scope (and name (definition-scope (resolve-definition ast index)))))
(if (not name)
(json-object (field "documentChanges" (vector)))
(let ((changes '()))
(define (add-change site-uri site-text nodes site-version)
(when (pair? nodes)
(set! changes
(cons (json-object
(field "textDocument"
(text-document-of site-uri site-version))
(field "edits"
(list->vector
(map (lambda (node)
(json-object
(field "range"
(json-range site-text
(form-start node)
(form-end node)))
(field "newText" new-name)))
nodes))))
changes))))
(if scope
(let ((start (form-start scope))
(end (form-end scope)))
(add-change uri text
(filter (lambda (node)
(and (<= start (form-start node))
(< (form-start node) end)))
(occurrences-of ast name))
version))
(for-each
(lambda (site)
(let ((site-uri (car site))
(site-text (cadr site)))
(add-change site-uri site-text
(occurrences-of (ast-of-text site-text dialect) name)
(and version (string=? site-uri uri) version))))
(project-texts workspace documents uri text dialect)))
(json-object (field "documentChanges" (list->vector (reverse changes))))))))
Replace the text of document, dropping the parse of the old text.
(define (set-document-text! document text)
"Replace the text of @var{document}, dropping the parse of the old text."
(document-text-set! document text)
(atomic-box-set! (document-ast-box document) #f))
Return the file path a file: URI names, or uri unchanged.
(define (strip-uri uri)
"Return the file path a @code{file:} URI names, or @var{uri} unchanged."
(if (string-prefix? "file://" uri)
(uri-decode (substring uri 7))
uri))
Return the Lisp name around index in text, or #f.
This is the answer to a jump when the buffer has no parse of its current text: reading the name under the cursor needs no tree, and the name is the whole of what the index is asked about.
(define (symbol-at-index text index)
"Return the Lisp name around @var{index} in @var{text}, or @code{#f}.
This is the answer to a jump when the buffer has no parse of its current text:
reading the name under the cursor needs no tree, and the name is the whole of
what the index is asked about."
(let* ((length (string-length text))
(at (min (max index 0) length))
(start (let loop ((i at))
(if (and (> i 0) (symbol-character? (string-ref text (- i 1))))
(loop (- i 1))
i)))
(end (let loop ((i at))
(if (and (< i length) (symbol-character? (string-ref text i)))
(loop (+ i 1))
i))))
(and (> end start) (substring text start end))))
Return the hover that describes a definition rather than a rule.
A procedure is described by what it takes as well as by what it is: the form is what the outline shows, and the sentence beside it is the same reading of the parameter list the arity rule makes, so a hover and a finding cannot disagree about how many arguments a definition wants.
(define (symbol-hover text dialect definition)
"Return the hover that describes a definition rather than a rule.
A procedure is described by what it takes as well as by what it is: the form
is what the outline shows, and the sentence beside it is the same reading of
the parameter list the arity rule makes, so a hover and a finding cannot
disagree about how many arguments a definition wants."
(let* ((dialect-name (symbol->string dialect))
(signature (and (memq (definition-kind definition) '(function method))
(definition-form definition)
(form-signature (definition-form definition))))
(summary (and signature
(arity-summary (cons (car signature) (cadr signature))
dialect))))
(json-object
(field "contents"
(json-object
(field "kind" "markdown")
(field "value"
(format #f "**~a** — ~a~%~%```~a~%~a~%```~@[~%~%~a~]~@[~%~%~a~]"
(definition-name definition)
(definition-kind definition)
dialect-name
(symbol-detail definition text)
summary
(definition-documentation text definition))))))))
Return the ‘textDocument’ of a workspace edit, with a version when known.
An edit that names the version it was computed from is applied only while the buffer still is that version, which is the difference between renaming a symbol and renaming whatever is in that spot now.
(define (text-document-of uri version)
"Return the `textDocument' of a workspace edit, with a version when known.
An edit that names the version it was computed from is applied only while the
buffer still is that version, which is the difference between renaming a
symbol and renaming whatever is in that spot now."
(if (and version (number? version))
(json-object (field "uri" uri) (field "version" version))
(json-object (field "uri" uri))))
Return #t when name can be written as a Lisp symbol.
(define (valid-symbol-name? name)
"Return @code{#t} when @var{name} can be written as a Lisp symbol."
(and (string? name)
(not (string-null? name))
(and (every-char (lambda (character)
(not (or (char-whitespace? character)
(memv character
'(#\( #\) #\[ #\] #\{ #\} #\" #\' #\` #\, #\; #\| #\#)))))
name)
#t)))
Return (uri text definition) for every file-level definition of
name.
(define* (workspace-definition-sites workspace name dialect #:key (open #f))
"Return @code{(uri text definition)} for every file-level definition of @var{name}."
(index-sites (workspace-index workspace) name dialect #:open open))
Return a ‘WorkspaceEdit’ replacing start..end of text.
(define (workspace-edit uri version text start end replacement)
"Return a `WorkspaceEdit' replacing @var{start}..@var{end} of @var{text}."
(json-object
(field "documentChanges"
(vector
(json-object
(field "textDocument" (text-document-of uri version))
(field "edits"
(vector
(json-object
(field "range" (json-range text start end))
(field "newText" replacement)))))))))
Return the files of the current index, by path.
(define (workspace-files workspace) "Return the files of the current index, by path." (index-files (workspace-index workspace)))
Return the workspace’s index as it is now, without waiting for a scan.
(define (workspace-index workspace) "Return the workspace's index as it is now, without waiting for a scan." (atomic-box-ref (workspace-index-box workspace)))
Return the names the workspace defines in dialect, without repeats.
(define* (workspace-names workspace dialect #:key (open #f))
"Return the names the workspace defines in @var{dialect}, without repeats."
(index-names-of (workspace-index workspace) dialect #:open open))
Return (status done total) for the index of workspace.
(define (workspace-progress workspace)
"Return @code{(status done total)} for the index of @var{workspace}."
(list (workspace-status workspace)
(atomic-box-ref (workspace-done-box workspace))
(atomic-box-ref (workspace-total-box workspace))))
Return the directory an ‘initialize’ request says the workspace is under.
(define (workspace-root-of params)
"Return the directory an `initialize' request says the workspace is under."
(let* ((folders (json-ref params "workspaceFolders" #f))
(first (and (vector? folders) (> (vector-length folders) 0)
(vector-ref folders 0)))
(uri (or (and first (json-ref first "uri" #f))
(json-ref params "rootUri" #f))))
(cond
[(and (string? uri) (string-prefix? "file://" uri)) (strip-uri uri)]
[else
(let ((path (json-ref params "rootPath" #f)))
(and (string? path) (not (string-null? path)) path))])))
Return the index’s state: ‘uninitialized’, ‘scanning’, ‘indexing’ or ‘ready’.
(define (workspace-status workspace) "Return the index's state: `uninitialized', `scanning', `indexing' or `ready'." (atomic-box-ref (workspace-status-box workspace)))
Return the definitions whose name contains query, as ‘workspace/symbol’.
dialect #f means every dialect, which is what the request
means: ‘workspace/symbol’ names no buffer to take a language from.
(define (workspace-symbols workspace documents query dialect)
"Return the definitions whose name contains @var{query}, as `workspace/symbol'.
@var{dialect} @code{#f} means every dialect, which is what the request means:
`workspace/symbol' names no buffer to take a language from."
(let ((needle (string-downcase query))
(entries '())
(open (open-paths documents)))
(define (consider uri text definition)
(let ((name (definition-name definition)))
(when (string-find (string-downcase name) needle)
(set! entries
(cons (json-object
(field "name" name)
(field "kind" (symbol-kind (definition-kind definition)))
(field "location" (definition-location uri text definition)))
entries)))))
(hash-for-each
(lambda (uri document)
(when (or (not dialect) (eq? (document-dialect document) dialect))
(let ((ast (document-ast-of document)))
(when ast
(for-each (lambda (definition)
(unless (definition-scope definition)
(consider uri (document-text document) definition)))
(parse-definitions ast))))))
documents)
(hash-for-each
(lambda (path entry)
(when (and (or (not dialect) (eq? (indexed-file-dialect entry) dialect))
(indexed-file-definitions entry)
(not (open-buffer-path? open path)))
(for-each (lambda (definition)
(unless (definition-scope definition)
(consider (path->uri path) (indexed-file-text entry)
definition)))
(indexed-file-definitions entry))))
(index-files (workspace-index workspace)))
(list->vector (reverse entries))))
This record type has 7 fields: uri, text,
language-id, version, dialect, published,
ast.
(define-record-type <document> (make-document uri text language-id version dialect published ast) document? (uri document-uri) (text document-text document-text-set!) (language-id document-language-id) (version document-version set-document-version!) (dialect document-dialect) ;; what the editor was last told, and about which text, as ;; `(diagnostics . text)' -- see `publish!' for why the text is kept beside ;; the findings rather than the findings alone (published document-published set-document-published!) ;; `(text . ast)', or #f: the parse of the buffer as a value a request can ;; take without reading the buffer again. A request that finds a parse of ;; other text here does not parse the buffer to replace it -- the slower ;; answer to a jump is a stale one, and the editor is told so instead. (ast document-ast-box))
This record type has 3 fields: files, names,
generation.
(define-record-type <index> (make-index files names generation) index? (files index-files) (names index-names) (generation index-generation))
This record type has 5 fields: path, text, dialect,
definitions, names.
(define-record-type <indexed-file> (make-indexed-file path text dialect definitions names) indexed-file? (path indexed-file-path) ;; #f for an entry the cache remembered without reading: the names are ;; known and the text is not, which answers completion and says nothing ;; about a jump rather than making one wait for a read. (text indexed-file-text) (dialect indexed-file-dialect) (definitions indexed-file-definitions) (names indexed-file-names))
This record type has 8 fields: root, filter,
worker, index, status, done, total,
scanned?.
(define-record-type <workspace> (make-workspace root filter index status done total scanned? worker) workspace? (root workspace-root set-workspace-root!) (filter workspace-filter set-workspace-filter!) ;; the indexer thread and its queue, which `(sift index)' owns: the record ;; here decides what a workspace *is*, and that module owns how it is built (worker workspace-worker set-workspace-worker!) ;; The index is one value, replaced whole: a reader takes the pointer in one ;; step and never sees a half-built table, because the writer builds the ;; next one outside every lock and publishes it with an atomic store. (index workspace-index-box) (status workspace-status-box) (done workspace-done-box) (total workspace-total-box) (scanned? workspace-scanned? set-workspace-scanned!))
Every rule sift ships, rendered as one Org document. The document is generated from the checker records – the same records ‘list-checkers’ prints and the driver runs – so it cannot describe a rule that does not exist, and a rule that is added cannot escape it: the test suite compares ‘doc/rules.org’ with what this module produces and fails when they differ.
The prose that explains *why* a rule exists is in doc/style.org, written by hand; what is here is the part that must not drift: the codes, the dialects, the severities, the examples and the fixes.
#t when path is exactly what this module generates.
Turn ‘like this’ into ~like this~, which is what Org calls code.
The descriptions are written with backticks because that is what a markdown reader and a Lisp reader both understand; Org wants tildes, and this is the one place where the two meet.
(define (backticks->org text)
"Turn `like this' into ~like this~, which is what Org calls code.
The descriptions are written with backticks because that is what a markdown
reader and a Lisp reader both understand; Org wants tildes, and this is the
one place where the two meet."
(let loop ((chars (string->list text)) (in-code #f) (out '()))
(cond
[(null? chars) (list->string (reverse out))]
[(char=? (car chars) #\`)
(loop (cdr chars) (not in-code) (cons (if in-code #\~ #\~) out))]
[else (loop (cdr chars) in-code (cons (car chars) out))])))
Return the whole rule catalogue as an Org document.
(define (catalogue->org)
"Return the whole rule catalogue as an Org document."
(let ((checkers (all-checkers)))
(string-append
"# SPDX-License-Identifier: MIT
;; Copyright © Josep Bigorra <jjbigorra@gmail.com>\n\n"
"#+title: sift — the rule catalogue\n"
"#+author: generated by sift from the checker records\n"
"#+options: toc:2 num:nil\n"
"#+language: en\n\n"
"/Do not edit this file by hand./ It is written by ~maak docs~ from the\n"
"same records that ~sift list-checkers~ prints and that the linter runs,\n"
"and the test suite fails when it falls behind. What each rule is\n"
"*for* -- the reasoning, and the style the rules belong to -- is in\n"
"[[file:style.org][style.org]].\n\n"
(format #f "There are ~a rules in sift ~a.\n\n" (length checkers)
sift-version)
"* Summary\n\n"
(summary-table checkers)
"\n* The rules, one by one\n\n"
(rule-sections checkers))))
;
Return #t when path is exactly what this module generates.
(define* (catalogue-check #:key (path catalogue-file))
"Return @code{#t} when @var{path} is exactly what this module generates."
(and (file-exists? path)
(string=? (call-with-input-file path get-string-all)
(catalogue->org))))
Undocumented procedure.
(define (rule-sections checkers) (string-join (map rule-section checkers) "\n"))
Escape text for an Org table cell.
A vertical bar ends a cell, so a description that contains one – ‘–brackets square|parens’ is the example – has to be written \vert.
(define (table-cell text)
"Escape @var{text} for an Org table cell.
A vertical bar ends a cell, so a description that contains one -- `--brackets
square|parens' is the example -- has to be written \\vert."
(backticks->org
(string-replace-substring text "|" "\\vert")))
Every checker is a procedure of (ast source dialect) that returns
a list of warnings and never mutates the tree. This module holds what
all of them need to do that: a walk over the data nodes that stays out
of datum comments and opaque objects, the handful of accessors that read
a form as a program rather than as text, and the line arithmetic that
the checkers working on raw text rather than on forms need.
#f.
#t when text holds nothing but whitespace.
#t when node is a call: a list that is neither.
#t when argument position of head is a clause.
#t when a rule may read node as a form.
#t when node is a form that declares rather than
calls.
#f.
#t when node is a definition form.
#f.
#t when node structures a formal list rather than
naming a parameter.
#t when node is a form whose shape includes
parameters.
#f.
#t when node sits inside a parameter list.
#t when node sits inside a vector literal.
#t when index falls inside one of ranges.
#t when node is the keyword :name.
#t when the operator of node is a keyword.
#t when node is a keyword: ‘:key’ or ‘#:key’.
(values line column) of character index in
source.
#t when node is a list whose operator is name.
#f.
#f.
#t for a node that carries a datum, trivia aside.
#f.
#f.
#t when node is a comment that follows code on its
line.
#t when node is a pattern or a clause datum.
#t when the innermost quoted form is still in effect.
#t when node is the symbol name.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Default value:
()
(define current-check-options (make-parameter '()))
Return how many arguments (everything after the operator) node has.
(define (argument-count node)
"Return how many arguments (everything after the operator) @var{node} has."
(length (form-arguments node)))
Return the name of an atom as a symbol, or #f.
A keyword is returned with its colon dropped, so that ‘:export’ and ‘export’ compare the same way: a checker asking whether a clause is an export clause should not have to know which spelling the author used.
(define (atom-symbol node)
"Return the name of an atom as a symbol, or @code{#f}.
A keyword is returned with its colon dropped, so that `:export' and `export'
compare the same way: a checker asking whether a clause is an export clause
should not have to know which spelling the author used."
(and node
(node-atom? node)
(let ((value (node-value node))
(type (node-atom-type node))
(marker (node-package-marker node)))
(cond
[(eq? type 'keyword)
(string->symbol (if (string-prefix? ":" value)
(substring value 1)
value))]
;; `#:run' and `app:run' name the symbol `run'; the marker says
;; which package it belongs to, not what it is called.
[(and marker (< (string-length marker) (string-length value)))
(string->symbol (substring value (string-length marker)))]
[(eq? type 'symbol) (string->symbol value)]
[else #f]))))
Return #t when text holds nothing but whitespace.
start and end narrow the question to one line of a larger text, which is what a checker that has the offsets already wants: asking it of a substring would be a copy of the line to find out that it is blank.
(define* (blank-line? text #:optional (start 0) (end (string-length text)))
"Return @code{#t} when @var{text} holds nothing but whitespace.
@var{start} and @var{end} narrow the question to one line of a larger text,
which is what a checker that has the offsets already wants: asking it of a
substring would be a copy of the line to find out that it is blank."
(let loop ((i start))
(cond
[(>= i end) #t]
[(memv (string-ref text i) '(#\space #\tab #\return)) (loop (+ i 1))]
[else #f])))
Return the body of node: its elements after the first skip.
A docstring is not a body form, so it is dropped when it comes first. A form shorter than skip has no body at all, and asking for one is not an error: ‘(defun f ())‘ defines a function with no body, which is a different problem from a crash.
(define (body-elements node skip)
"Return the body of @var{node}: its elements after the first @var{skip}.
A docstring is not a body form, so it is dropped when it comes first. A
form shorter than @var{skip} has no body at all, and asking for one is not an
error: `(defun f ())` defines a function with no body, which is a different
problem from a crash."
(let* ((elements (form-elements node))
(rest (drop elements (min skip (length elements)))))
(if (and (pair? rest) (string-atom? (car rest)))
(cdr rest)
rest)))
Return #t when node is a call: a list that is neither.
The distinction is deliberate rather than exhaustive: a form whose operator is a symbol this file has never heard of is a call, and a rule about calls says what it has to say about it.
(define (call-form? node)
"Return @code{#t} when @var{node} is a call: a list that is neither.
The distinction is deliberate rather than exhaustive: a form whose operator is
a symbol this file has never heard of is a call, and a rule about calls says
what it has to say about it."
(and (node-list? node)
(not (declaration-form? node))
(not (definition-form? node))))
Build a <lint-checker> with its documentation attached.
The record is the whole contract: a name to select it by, a description for ‘list-checkers’, the dialects it applies to, the severity of what it reports and, for ‘explain’, a failing example and the fix it expects.
(define* (checker name description dialects proc
#:key (severity 'warning) example code)
"Build a <lint-checker> with its documentation attached.
The record is the whole contract: a name to select it by, a description for
`list-checkers', the dialects it applies to, the severity of what it reports
and, for `explain', a failing example and the fix it expects."
(make-lint-checker name description dialects proc severity example code))
Return #t when argument position of head is a clause.
(define (clause-argument? head position)
"Return @code{#t} when argument @var{position} of @var{head} is a clause."
(or (memq head '(match-lambda match-lambda*))
(and (memq head case-form-heads)
(>= position (clause-leading-arguments head)))))
Return how many arguments of head are read before its clauses start.
(define (clause-leading-arguments head)
"Return how many arguments of @var{head} are read before its clauses start."
(case head
[(condition-case syntax-case) 2]
[(case ecase ccase typecase etypecase ctypecase
cl-case cl-ecase cl-typecase cl-etypecase
pcase handler-case restart-case
match match* syntax-parse) 1]
[else 0]))
Return #t when a rule may read node as a form.
Four places are data rather than code: anything inside a quote, a pattern or a clause datum, a parameter list, and a vector literal. A vector literal is not a form itself, and nothing inside one is, so ‘#(if a b)’ is left alone. Every rule that asks about the shape of a form asks this first.
(define (code-position? node ancestors)
"Return @code{#t} when a rule may read @var{node} as a form.
Four places are data rather than code: anything inside a quote, a pattern or
a clause datum, a parameter list, and a vector literal. A vector literal is
not a form itself, and nothing inside one is, so `#(if a b)' is left alone.
Every rule that asks about the shape of a form asks this first."
(not (or (node-vector? node)
(node-bytevector? node)
(quoted-context? ancestors)
(pattern-context? node ancestors)
(in-formals? node ancestors)
(in-vector? ancestors))))
Return #t when node is a form that declares rather than
calls.
A clause headed by a keyword – ‘#:export (...)’ in Guile, ‘(:export ...)’ in a Common Lisp package definition – is a declaration too: the keyword is what the clause *is*, not what it is applied to.
(define (declaration-form? node)
"Return @code{#t} when @var{node} is a form that declares rather than calls.
A clause headed by a keyword -- `#:export (...)' in Guile, `(:export ...)' in a
Common Lisp package definition -- is a declaration too: the keyword is what the
clause *is*, not what it is applied to."
(and (node-list? node)
(let ((head (node-head node)))
(or (keyword-clause? node)
(and head
(node-atom? head)
(memq (atom-symbol head) declaration-heads))))))
Return the atom that names what node defines, or #f.
‘(define (f a) ...)’ keeps the name inside its second element, ‘(define x 1)’ keeps it in the second element whole, and ‘(defun f (a) ...)’ in the second as well; reading the second element answers all three.
(define (defined-name node)
"Return the atom that names what @var{node} defines, or @code{#f}.
`(define (f a) ...)' keeps the name inside its second element, `(define x 1)'
keeps it in the second element whole, and `(defun f (a) ...)' in the second as
well; reading the second element answers all three."
(let ((elements (form-elements node)))
(cond
[(and (pair? elements) (pair? (cdr elements)))
(let ((second (cadr elements)))
(if (node-list? second) (node-head second) second))]
[else #f])))
Return #t when node is a definition form.
(define (definition-form? node)
"Return @code{#t} when @var{node} is a definition form."
(and (node-list? node)
(memq (node-head-name node) definition-heads)))
Build a warning about node on behalf of checker.
(define* (diagnose checker severity message node #:key fix range)
"Build a warning about @var{node} on behalf of @var{checker}."
(make-lint-warning checker severity message (node-start node) fix range))
Return the docstring of node, the way each dialect spells it.
A function form (Scheme ‘define’ with a head, Emacs Lisp ‘defun’, Common Lisp ‘defun’) keeps its docstring after the argument list; a variable form after the value. A docstring is a string literal, and it is the only string that is not a value here.
(define (docstring-node node)
"Return the docstring of @var{node}, the way each dialect spells it.
A function form (Scheme `define' with a head, Emacs Lisp `defun', Common Lisp
`defun') keeps its docstring after the argument list; a variable form after
the value. A docstring is a string literal, and it is the only string that
is not a value here."
(let* ((head (and (node-list? node) (node-head-name node)))
(args (form-arguments node)))
(define (after k)
(if (<= k (length args))
(let ((rest (list-tail args k)))
(and (pair? rest) (string-atom? (car rest)) (car rest)))
#f))
(case head
[(define define* define-public)
(let ((first (and (pair? args) (car args))))
;; (define (f a) "doc" ...) versus (define x "value")
(if (and first (node-list? first)) (after 1) #f))]
[(defun defmacro defsubst defmethod cl-defun cl-defmacro cl-defsubst
defgeneric)
(after 2)]
[(lambda lambda* cl-lambda)
(after 1)]
[(defvar defconst defcustom defparameter defface)
(after 2)]
[else #f])))
Fold kons over every datum in ast.
(define (fold-nodes kons knil ast)
"Fold @var{kons} over every datum in @var{ast}."
(let ((acc knil))
(for-each-node (lambda (node) (set! acc (kons node acc))) ast)
acc))
Call proc on every node that is a form, outermost first.
A *form* is a node in a position where code is evaluated. Four places are not: anything inside a quote, the datum of a ‘case‘ clause, a parameter list and a vector literal. A rule about the shape of a form asks this walker and never has to ask whether what it is looking at is code at all – which is what stops ‘(if . 2)’ in an alist from being reported as an ‘if‘ with no else branch, and ‘#(if a b)’ from being reported as one either.
(define (for-each-form proc ast)
"Call @var{proc} on every node that is a form, outermost first.
A *form* is a node in a position where code is evaluated. Four places are
not: anything inside a quote, the datum of a `case` clause, a parameter list
and a vector literal. A rule about the shape of a form asks this walker and
never has to ask whether what it is looking at is code at all -- which is what
stops `(if . 2)' in an alist from being reported as an `if` with no else
branch, and `#(if a b)' from being reported as one either."
(walk-forms (lambda (node ancestors) (proc node)) ast #:ancestors? #f))
Call proc on every datum in ast, outermost first.
The walk does not enter a datum comment, an opaque object or a form that is commented out: the linter has no business reporting on code the reader was told not to read as code.
(define (for-each-node proc ast)
"Call @var{proc} on every datum in @var{ast}, outermost first.
The walk does not enter a datum comment, an opaque object or a form that is
commented out: the linter has no business reporting on code the reader was
told not to read as code."
(define (walk node)
(unless (node-commented-out? node)
(proc node)
(cond
[(node-list? node)
(for-each walk (node-elements node))]
[(node-prefix? node)
(let ((child (node-child node)))
(when (and child (not (node-datum-comment? node)))
(walk child)))]
[(node-conditional? node)
(let ((feature (node-feature node))
(guarded (node-guarded-form node)))
(when feature (walk feature))
(when guarded (walk guarded)))])))
(for-each (lambda (node) (when (node-data? node) (walk node))) ast))
Call proc on the data nodes of ast that are not inside anything.
(define (for-each-top-level proc ast)
"Call @var{proc} on the data nodes of @var{ast} that are not inside anything."
(for-each (lambda (node) (when (node-data? node) (proc node))) ast))
Return the elements of node after its first one.
(define (form-arguments node)
"Return the elements of @var{node} after its first one."
(let ((elements (form-elements node)))
(if (null? elements) '() (cdr elements))))
Return the data elements of node; empty when it is not a list.
(define (form-elements node)
"Return the data elements of @var{node}; empty when it is not a list."
(if (node-list? node) (node-elements node) '()))
Return the nodes that name the parameters of node, or #f.
‘(define (f a b) ...)’ keeps its parameters after the name, inside its second element; ‘(defun f (a b) ...)’ keeps them in its third, which holds nothing else; ‘(define-values (a b) expr)’ names all of its second. Which shape the form is decides, and it is read here so that a rule about parameters asks the form rather than guessing an element position – the guess that made a ‘defun‘ look like a call of its first parameter.
(define (formal-elements node)
"Return the nodes that name the parameters of @var{node}, or @code{#f}.
`(define (f a b) ...)' keeps its parameters after the name, inside its second
element; `(defun f (a b) ...)' keeps them in its third, which holds nothing
else; `(define-values (a b) expr)' names all of its second. Which shape the
form is decides, and it is read here so that a rule about parameters asks the
form rather than guessing an element position -- the guess that made a `defun`
look like a call of its first parameter."
(let ((head (and (node-list? node) (node-head-name node)))
(formals (and (definition-form? node) (formals-of-form node))))
(and formals
(cond
[(memq head '(define define* define-public define-inlinable
define-macro))
;; the second element is `(name parameters...)' for a procedure and a
;; value for a variable, and only the first of those has parameters
(and (node-list? formals)
(let ((elements (node-elements formals)))
(and (pair? elements) (cdr elements))))]
[(memq head '(define-values))
(and (node-list? formals) (node-elements formals))]
[(node-list? formals) (node-elements formals)]
[else #f]))))
Return #t when node structures a formal list rather than
naming a parameter.
Common Lisp’s ‘&optional’ and ‘&rest’, Guile’s ‘#:optional’, ‘#:key’ and ‘#:rest’, the dot of a rest parameter and CL’s ‘&allow-other-keys’ all say something about the rest of the list rather than being an argument a caller passes, so they are markers in both of the places a formal list is read: the count of required arguments, and the question of which nodes are parameters.
(define (formal-marker? node)
"Return @code{#t} when @var{node} structures a formal list rather than naming a parameter.
Common Lisp's `&optional' and `&rest', Guile's `#:optional', `#:key' and
`#:rest', the dot of a rest parameter and CL's `&allow-other-keys' all say
something about the rest of the list rather than being an argument a caller
passes, so they are markers in both of the places a formal list is read: the
count of required arguments, and the question of which nodes are parameters."
(and (node-atom? node)
(let ((value (node-value node)))
(or (keyword-node? node)
(string=? value ".")
(string=? value "...")
(and (> (string-length value) 1)
(string=? (substring value 0 1) "&"))))))
Return #t when node is a form whose shape includes
parameters.
(define (formals-holder? node)
"Return @code{#t} when @var{node} is a form whose shape includes parameters."
(and (node-list? node)
(assq-ref formals-positions (node-head-name node))
#t))
Return the element of node that holds its parameter list, or
#f.
For ‘(define (f a) ...)’ that element is the whole ‘(f a)’: the parameters are its tail, and a rule that wants them says so. For ‘(define x 1)’ it is the name, which has no parameters under it – and answering the name is what keeps a rule from reading the value as one.
(define (formals-of-form node)
"Return the element of @var{node} that holds its parameter list, or @code{#f}.
For `(define (f a) ...)' that element is the whole `(f a)': the parameters are
its tail, and a rule that wants them says so. For `(define x 1)' it is the
name, which has no parameters under it -- and answering the name is what keeps
a rule from reading the value as one."
(let* ((head (and (node-list? node) (node-head-name node)))
(position (and head (assq-ref formals-positions head))))
(and position
(let ((elements (node-elements node)))
(and (<= position (length elements))
(list-ref elements (- position 1)))))))
Return the operator of node when it is one of names, else #f.
(define (head-is-one-of? node names)
"Return the operator of @var{node} when it is one of @var{names}, else #f."
(let ((head (and (node-list? node) (node-head-name node))))
(and head (memq head names) head)))
Return #t when node sits inside a parameter list.
‘(define* (f (labels #f)) ...)’ has a pair in its formals that looks exactly like a ‘labels‘ form; it is a parameter with a default, and no rule about bodies has any business reading it as code.
Where the parameter list is depends on the form, so the answer comes
from formals-of-form rather than from counting to the second
element: in ‘(defun f (a) ...)’ the second element is the name.
(define (in-formals? node ancestors)
"Return @code{#t} when @var{node} sits inside a parameter list.
`(define* (f (labels #f)) ...)' has a pair in its formals that looks exactly
like a `labels` form; it is a parameter with a default, and no rule about
bodies has any business reading it as code.
Where the parameter list is depends on the form, so the answer comes from
@code{formals-of-form} rather than from counting to the second element: in
`(defun f (a) ...)' the second element is the name."
(let loop ((rest ancestors))
(cond
[(null? rest) #f]
[(formals-holder? (car rest))
(let ((formals (formals-of-form (car rest))))
(and formals
(<= (node-index formals) (node-index node))
(<= (node-end-index node) (node-end-index formals))))]
[else (loop (cdr rest))])))
Return #t when node sits inside a vector literal.
‘#(if a b)’ is a vector that holds three symbols, not an ‘if’ with no
else branch: a vector literal is data, so a rule about the shape of a
form has no business reading what is inside one. An unquote – ‘,’,
‘,@’ or one of their syntax-case spellings – ends the data again,
exactly as it does in quoted-context?: what is inside it is
evaluated.
(define (in-vector? ancestors)
"Return @code{#t} when @var{node} sits inside a vector literal.
`#(if a b)' is a vector that holds three symbols, not an `if' with no else
branch: a vector literal is data, so a rule about the shape of a form has no
business reading what is inside one. An unquote -- `,', `,@@' or one of their
syntax-case spellings -- ends the data again, exactly as it does in
@code{quoted-context?}: what is inside it is evaluated."
(let loop ((rest ancestors))
(cond
[(null? rest) #f]
[(or (node-vector? (car rest)) (node-bytevector? (car rest))) #t]
[(and (node-prefix? (car rest))
(member (node-token (car rest)) '("," ",@" "#," "#,@")))
#f]
[(and (node-list? (car rest))
(memq (node-head-name (car rest))
'(unquote unquote-splicing unsyntax unsyntax-splicing)))
#f]
[else (loop (cdr rest))])))
Return how many columns the whitespace from start to end spans.
A tab stops at the next multiple of eight, which is the convention every editor uses for a file it has not been told about.
(define (indent-width-of source start end)
"Return how many columns the whitespace from @var{start} to @var{end} spans.
A tab stops at the next multiple of eight, which is the convention every
editor uses for a file it has not been told about."
(let loop ((i start) (column 0))
(if (>= i end)
column
(loop (+ i 1)
(if (char=? (string-ref source i) #\tab)
(* 8 (+ 1 (quotient column 8)))
(+ column 1))))))
Return #t when index falls inside one of ranges.
(define (index-in-ranges? index ranges)
"Return @code{#t} when @var{index} falls inside one of @var{ranges}."
(any (lambda (range) (and (>= index (car range)) (< index (cdr range))))
ranges))
Return #t when node is the keyword :name.
(define (keyword-atom? node name)
"Return @code{#t} when @var{node} is the keyword @code{:name}."
(and node
(node-atom? node)
(eq? (node-atom-type node) 'keyword)
(string=? (node-value node) (string-append ":" (symbol->string name)))))
Return #t when the operator of node is a keyword.
‘#:export’, ‘#:use-module’ and ‘(:export ...)’ head a clause of a declaration. Reading one as a procedure that takes seven arguments is reading a list of names as a call.
(define (keyword-clause? node)
"Return @code{#t} when the operator of @var{node} is a keyword.
`#:export', `#:use-module' and `(:export ...)' head a clause of a declaration.
Reading one as a procedure that takes seven arguments is reading a list of
names as a call."
(and (node-list? node)
(let ((head (node-head node)))
(and head (node-atom? head) (eq? (node-atom-type head) 'keyword)))))
Return #t when node is a keyword: ‘:key’ or ‘#:key’.
The two dialects spell a keyword differently and the reader keeps them differently: Common Lisp’s ‘:key’ is an atom of type ‘keyword‘, and Guile’s ‘#:key’ is a symbol whose package marker is ‘#:’. A rule that asks whether an argument is a keyword has to ask this, because a call that passes one is not a call that passes positional arguments.
(define (keyword-node? node)
"Return @code{#t} when @var{node} is a keyword: `:key' or `#:key'.
The two dialects spell a keyword differently and the reader keeps them
differently: Common Lisp's `:key' is an atom of type `keyword`, and Guile's
`#:key' is a symbol whose package marker is `#:'. A rule that asks whether an
argument is a keyword has to ask this, because a call that passes one is not a
call that passes positional arguments."
(and (node-atom? node)
(or (eq? (node-atom-type node) 'keyword)
(let ((marker (node-package-marker node)))
(and marker (string=? marker "#:"))))))
Return (values line column) of character index in
source.
Both count from one. An index past the end of the text is answered the way the line list always answered it: the line after the last one, at its first column.
(define (line-and-column source index)
"Return @code{(values line column)} of character @var{index} in @var{source}.
Both count from one. An index past the end of the text is answered the way
the line list always answered it: the line after the last one, at its first
column."
(let* ((entry (line-index source))
(starts (vector-ref entry 0))
(number (line-number-of index starts)))
(if (<= index (string-length source))
(values number
(+ 1 (- index (vector-ref starts (- number 1)))))
(values (+ (vector-length starts) 1) 1))))
Return the 1-based line of character index in source.
(define (line-of-index source index)
"Return the 1-based line of character @var{index} in @var{source}."
(call-with-values (lambda () (line-and-column source index))
(lambda (line column) line)))
Return (start . end) character offsets for every line of
source.
(define (line-spans source)
"Return @code{(start . end)} character offsets for every line of @var{source}."
(vector-ref (line-index source) 1))
Return line line (1-based) of source, without its break.
(define* (line-text source line #:optional (lines #f))
"Return line @var{line} (1-based) of @var{source}, without its break."
(let ((spans (or lines (line-spans source))))
(and (>= line 1) (<= line (length spans))
(let ((span (list-ref spans (- line 1))))
(substring source (car span) (cdr span))))))
Return #t when node is a list whose operator is name.
(define (list-headed-by? node name)
"Return @code{#t} when @var{node} is a list whose operator is @var{name}."
(and (node-list? node)
(eq? (node-head-name node) name)))
Build a location from an index alone.
A checker is handed the AST and the text, not the file name, so the file
is left #f here and the driver fills it in from the run’s
context. The line and column are counted in characters, exactly as the
reader counts them.
(define (location-at-index source index)
"Build a location from an index alone.
A checker is handed the AST and the text, not the file name, so the file is
left @code{#f} here and the driver fills it in from the run's context. The
line and column are counted in characters, exactly as the reader counts
them."
(call-with-values (lambda () (line-and-column source index))
(lambda (line column)
(make-source-location #f line column index index))))
Undocumented procedure.
(define* (make-checker name description dialects proc
#:key (severity 'warning) example code)
(checker name description dialects proc #:severity severity #:example example
#:code code))
Return a warning about checker at location.
fix, when given, is a procedure of three arguments – the whole source string, the start character offset and the end character offset – that returns the replacement text for that range. The procedure is only called when range is also known (either passed here or derived from location), because a fix that does not know what it replaces cannot be applied safely.
Return a warning whose fix, when applied, replaces the range START..END.
Return the classification of an atom: symbol, keyword, number, string ...
Return the datum a prefix node applies to, or #f.
Return every child of a list node, trivia included.
Return the closing token a list node was closed with, or #f.
Undocumented procedure.
(define (node-column node) (source-location-column (node-start node)))
Return #t for a node that carries a datum, trivia aside.
A datum comment ("#;form") is trivia: the form it holds is preserved but is not part of the program, and neither the formatter nor the linter may treat it as code.
Return the children of node that carry a datum, trivia aside.
Comments and whitespace are dropped, and so is a datum comment, so the result is the form as a program sees it. The list is shared with every other caller – a node is immutable, so sharing it is free.
Undocumented procedure.
(define (node-end-index node) (source-location-index (node-end node)))
Return the first datum of a list node, or #f.
Return the head of a list node as a symbol, or #f.
Only an unquoted, unprefixed atom names an operator: ('foo x) and
(#'foo x) have no operator, which is what the indentation table
keys on.
A vector has no operator either. #(progn a) is a literal that
holds two symbols; reading the first of them as an operator is how a
linter ends up offering to replace a vector with its contents, and a
formatter ends up indenting a literal like a call.
The answer is computed once and kept on the node: every checker asks it about every node, and interning the same name again for each of them is the largest single cost a lint has.
Undocumented procedure.
(define (node-index node) (source-location-index (node-start node)))
Return #t when node is a comment that follows code on its
line.
Return the number of newline characters in a whitespace node.
Return the opening token of a list node: "(", "[", "#(" ...
Return the package marker of a Common Lisp symbol: "cl:", "cl::", ...
Return the source text node was read from.
(define (node-source source node)
"Return the source text @var{node} was read from."
(substring source (node-index node) (node-end-index node)))
Return the token of a prefix or conditional node: "’", "#;", "#+" ...
Return the configured value of key, or default.
(define* (option key #:optional (default #f))
"Return the configured value of @var{key}, or @var{default}."
(let ((cell (assq key (current-check-options))))
(if cell (cdr cell) default)))
Return #t when node is a pattern or a clause datum.
The ancestors are read from the outermost in, because whether a ‘(? pred)’ form’s first argument is code depends on whether the ‘?’ is a pattern operator at all: in the pattern of a ‘match’ clause it is, and in an ordinary call it is not.
(define (pattern-context? node ancestors)
"Return @code{#t} when @var{node} is a pattern or a clause datum.
The ancestors are read from the outermost in, because whether a `(? pred)'
form's first argument is code depends on whether the `?' is a pattern
operator at all: in the pattern of a `match' clause it is, and in an ordinary
call it is not."
(let ((path (reverse (cons node ancestors)))) ; outermost first, node last
(let loop ((rest path) (state #f))
(if (null? (cdr rest))
(eq? state 'pattern)
(loop (cdr rest)
(next-state (car rest)
(position-of (car rest) (cadr rest))
state))))))
Return #t when the innermost quoted form is still in effect.
Walking up from a node, the first ancestor that is a quote, a quasiquote, a quasisyntax or a ‘quote‘-style form decides: inside it the node is data, and a list that happens to start with ‘cond‘ is not a ‘cond‘ form.
An unquote ends the data, whichever of its spellings it is written in – ‘,‘/‘(unquote ...)‘, ‘,@‘/‘(unquote-splicing ...)‘, and the syntax-case ‘#,’ and ‘#,@’ – because what is inside it is evaluated again.
(define (quoted-context? ancestors)
"Return @code{#t} when the innermost quoted form is still in effect.
Walking up from a node, the first ancestor that is a quote, a quasiquote, a
quasisyntax or a `quote`-style form decides: inside it the node is data, and a
list that happens to start with `cond` is not a `cond` form.
An unquote ends the data, whichever of its spellings it is written in --
`,`/`(unquote ...)`, `,@@`/`(unquote-splicing ...)`, and the syntax-case
`#,' and `#,@@' -- because what is inside it is evaluated again."
(let loop ((rest ancestors))
(cond
[(null? rest) #f]
[(and (node-prefix? (car rest))
(member (node-token (car rest)) '("'" "`" "#`")))
#t]
[(and (node-list? (car rest))
(memq (node-head-name (car rest)) '(quote quasiquote quasisyntax)))
#t]
;; what a declaration says is data: the names in `#:export (a b)', the
;; libraries in `(use-modules (a) (b))', the situations in `(eval-when
;; (compile) ...)' -- which is why the second is a declaration that holds
;; code and the first two are not
[(and (node-list? (car rest))
(memq (node-head-name (car rest)) data-declaration-heads))
#t]
[(and (node-prefix? (car rest))
(member (node-token (car rest)) '("," ",@" "#," "#,@")))
#f]
[(and (node-list? (car rest))
(memq (node-head-name (car rest))
'(unquote unquote-splicing unsyntax unsyntax-splicing)))
#f]
[else (loop (cdr rest))])))
Return the source ranges of every node in ast satisfying predicate.
(define (ranges-of ast predicate)
"Return the source ranges of every node in @var{ast} satisfying @var{predicate}."
(reverse
(fold-nodes (lambda (node acc)
(if (predicate node)
(cons (cons (node-index node) (node-end-index node)) acc)
acc))
'() ast)))
Return how many parameters of formals a caller must pass positionally.
Everything from the first marker onwards is optional, keyword or rest, so a rule about a parameter list that has grown too long stops there: ‘(defun f (a b c &rest rest))’ takes three arguments a call has to name, and every one after that is the caller’s choice.
(define (required-positional-formals formals)
"Return how many parameters of @var{formals} a caller must pass positionally.
Everything from the first marker onwards is optional, keyword or rest, so a
rule about a parameter list that has grown too long stops there: `(defun f (a b
c &rest rest))' takes three arguments a call has to name, and every one after
that is the caller's choice."
(let loop ((rest formals) (count 0))
(cond
[(null? rest) count]
[(not (node-atom? (car rest))) (+ count 1)]
[(formal-marker? (car rest)) count]
[else (loop (cdr rest) (+ count 1))])))
Undocumented procedure.
(define (string-atom? node) (and node (node-atom? node) (eq? (node-atom-type node) 'string)))
Return #t when node is the symbol name.
(define (symbol-atom? node name)
"Return @code{#t} when @var{node} is the symbol @var{name}."
(and node
(node-atom? node)
(eq? (node-atom-type node) 'symbol)
(string=? (node-value node) (symbol->string name))))
Return the ranges in which source text is not code.
Strings and block comments are what a text-level checker must not look inside: a tab in a string literal is data, and a line that starts inside a multi-line block comment is not indentation. One pass, because the walk is over the whole tree and doing it twice doubles the cost of every checker that asks.
(define (text-ranges-of ast)
"Return the ranges in which source text is not code.
Strings and block comments are what a text-level checker must not look
inside: a tab in a string literal is data, and a line that starts inside a
multi-line block comment is not indentation. One pass, because the walk is
over the whole tree and doing it twice doubles the cost of every checker that
asks."
(reverse
(fold-nodes (lambda (node acc)
(if (or (node-block-comment? node) (node-string? node))
(cons (cons (node-index node) (node-end-index node)) acc)
acc))
'() ast)))
Call proc on every node in a position where code is evaluated.
proc receives the node and, when ancestors? is true, the forms that enclose it, nearest first.
Whether a node is code is decided while descending – from three flags that say whether the walk is inside a quotation, a vector or a parameter list, and from a state that says whether the node is a pattern or a clause – so a whole tree is walked once rather than once per level of nesting. A ‘case‘ datum and a ‘match’ pattern are data, and so is everything inside them except what ‘?’, ‘app’ and ‘==’ go on to evaluate.
(define* (walk-forms proc ast #:key (ancestors? #t))
"Call @var{proc} on every node in a position where code is evaluated.
@var{proc} receives the node and, when @var{ancestors?} is true, the forms
that enclose it, nearest first.
Whether a node is code is decided while descending -- from three flags that
say whether the walk is inside a quotation, a vector or a parameter list, and
from a state that says whether the node is a pattern or a clause -- so a
whole tree is walked once rather than once per level of nesting. A `case`
datum and a `match' pattern are data, and so is everything inside them
except what `?', `app' and `==' go on to evaluate."
(define (walk node quoted? in-vector? in-formals? state ancestors)
(unless (node-commented-out? node)
(when (and (not (node-trivia? node))
(not (node-vector? node))
(not (node-bytevector? node))
(not quoted?)
(not in-vector?)
(not in-formals?)
;; a pattern is data, but a clause is a form -- rules read the
;; `else' of a `cond' and the `_' of a `match' -- and only its
;; first element is the pattern
(not (eq? state 'pattern)))
(proc node (if ancestors? ancestors '())))
(cond
[(node-list? node)
(let* ((head (node-head-name node))
(quoted-next (cond [(memq head quote-opening-heads) #t]
[(memq head quote-closing-heads) #f]
[(memq head data-declaration-heads) #t]
[else quoted?]))
(vector-next (if (memq head quote-closing-heads) #f in-vector?))
(data-children? (or (node-vector? node) (node-bytevector? node)))
(container? (and head (assq-ref formals-positions head) #t))
(formals (and container? (formals-of-form node)))
(child-ancestors (and ancestors? (cons node ancestors))))
(let loop ((elements (node-elements node)) (position 0))
(unless (null? elements)
(let ((child (car elements)))
(walk child
quoted-next
;; a vector literal is data, and so is everything in it
(if data-children? #t vector-next)
(if container?
(and formals
(<= (node-index formals) (node-index child))
(<= (node-end-index child) (node-end-index formals)))
in-formals?)
(next-state node position state)
child-ancestors)
(loop (cdr elements) (+ position 1))))))]
[(node-prefix? node)
(let ((child (node-child node)))
(when (and child (not (node-datum-comment? node)))
(walk child
(cond [(member (node-token node) quote-opening-tokens) #t]
[(member (node-token node) quote-closing-tokens) #f]
[else quoted?])
(if (member (node-token node) quote-closing-tokens)
#f in-vector?)
in-formals?
(next-state node 0 state)
(if ancestors? (cons node ancestors) '()))))]
;; a conditional is not an ancestor: `#+foo (if a b)' is an `if' in
;; the same place the reader found it
[(node-conditional? node)
(let ((feature (node-feature node))
(guarded (node-guarded-form node)))
(when feature
(walk feature quoted? in-vector? in-formals? state ancestors))
(when guarded
(walk guarded quoted? in-vector? in-formals? state ancestors)))]
[else #f])))
(for-each (lambda (node)
(when (node-data? node)
(walk node #f #f #f #f '())))
ast))
Call proc with each datum and the list of forms that enclose it.
The ancestors come nearest-first, which is the order a checker asks them in: "is there a ‘let’ between me and that ‘lambda’?"
Unlike for-each-form this visits every node, comments and
whitespace included, because a checker that asks this question is asking
about positions rather than about shapes.
(define (walk-with-ancestors proc ast)
"Call @var{proc} with each datum and the list of forms that enclose it.
The ancestors come nearest-first, which is the order a checker asks them in:
\"is there a `let' between me and that `lambda'?\"
Unlike @code{for-each-form} this visits every node, comments and whitespace
included, because a checker that asks this question is asking about
positions rather than about shapes."
(define (walk node ancestors)
(unless (node-commented-out? node)
(proc node ancestors)
(cond
[(node-list? node)
(for-each (lambda (child) (walk child (cons node ancestors)))
(node-elements node))]
[(node-prefix? node)
;; a prefix is a parent like any other: a checker asking whether a
;; node is inside a quote has to see the quote mark it is inside of
(let ((child (node-child node)))
(when (and child (not (node-datum-comment? node)))
(walk child (cons node ancestors))))]
[(node-conditional? node)
(let ((feature (node-feature node))
(guarded (node-guarded-form node)))
(when feature (walk feature ancestors))
(when guarded (walk guarded ancestors)))])))
(for-each (lambda (node) (when (node-data? node) (walk node '()))) ast))
Run thunk with options – an alist – visible to the checkers.
The checker protocol is three arguments, (ast source dialect), so
anything configurable – the line limit, the indentation width, the LOOP
keyword style – travels beside it rather than through every signature.
A checker reads what it needs with option, which always has a
default.
(define* (with-check-options options thunk)
"Run @var{thunk} with @var{options} -- an alist -- visible to the checkers.
The checker protocol is three arguments, @code{(ast source dialect)}, so
anything configurable -- the line limit, the indentation width, the LOOP
keyword style -- travels beside it rather than through every signature. A
checker reads what it needs with @code{option}, which always has a default."
(parameterize ((current-check-options options)) (thunk)))
(case ecase ccase typecase etypecase ctypecase cl-case cl-ecase cl-typecase cl-etypecase pcase condition-case handler-case restart-case match match* match-lambda match-lambda* syntax-case syntax-parse)
(case x ((a b) ...))' the list
;;; `(a b)' is a list of *values* to match, not a call; a `match' pattern is
;;; the same kind of thing one level further: `(list a b)' in
;;; `(match x [(list a b) ...])' names a shape, and a rule that read it as a
;;; call to `list' would report code that is not there.
;;;
;;; A pattern is not entirely data, though. `(? pred pat)' and `(app f pat)'
;;; evaluate their first argument, and `(== expr)' evaluates all of it, so
;;; those children are read as code again -- which is why the walk carries a
;;; state rather than a flag.
(define case-form-heads
'(case ecase ccase typecase etypecase ctypecase
cl-case cl-ecase cl-typecase cl-etypecase
pcase condition-case handler-case restart-case
match match* match-lambda match-lambda* syntax-case syntax-parse))
(define-module use-modules import export re-export include include-ci include-library-declarations require provide require-theme declare-function defpackage in-package declare declaim proclaim)
(one two three four five six)' in `#:export (one two ...)' is a list of
;; names to a reader and must be one to a rule as well.
;;
;; The declarations that hold *code* are deliberately not here: the body of
;; `(eval-when (compile) (define x 1))', the `:config' of a `use-package' and
;; the clauses of a `cond-expand' are forms, and a rule has business with them.
(define data-declaration-heads
'(define-module use-modules import export re-export
include include-ci include-library-declarations
require provide require-theme declare-function
defpackage in-package declare declaim proclaim))
(define-module use-modules import export re-export include include-ci include-library-declarations library define-library cond-expand declare in-package defpackage require provide use-package require-theme declare-function eval-after-load with-eval-after-load eval-when-compile eval-when proclaim declaim)
(case x ((a b) ...))' the list `(a b)' is a list of *values* to match, not
;; a call, so a rule about the shape of a form has no business looking inside
;; it. A `match' pattern is the same kind of thing one level further: `(list a
;; b)' in `(match x [(list a b) ...])' names a shape, and a rule that read it
;; as a call to `list' -- which is what `apply-of-list` and `let-sibling' would
;; do -- would report code that is not there. Scheme has `match' too, through
;; `(ice-9 match)'; the pattern position is the same one.
;;; --- declarations, definitions and calls ------------------------------
;;;
;;; A rule about calls -- how many arguments are too many, whether an argument
;;; list has grown past reading as a sentence -- is a rule about *calls*, and
;;; two other kinds of form look like one. A declaration says what the file or
;;; the package is: `(use-modules (srfi srfi-1))' names six libraries in one
;;; form, and `(defpackage :demo (:export #:a ...))' names an export list, and
;;; neither is a call anybody could make shorter by passing keywords. A
;;; definition names something and gives it a body; how many parameters it takes
;;; is `too-many-arguments`' question, and the body is not an argument list.
;;;
;;; The three tables below are the whole of that knowledge, per dialect, so that
;;; a rule asks `declaration-form?' rather than keeping a list of its own that
;;; drifts from the next rule's.
;; The operators of forms that describe a file or a package rather than compute
;; a value: what it imports, what it exports, what it implements, what it tells
;; the compiler. None of them is a call, so none of its elements is an
;; argument.
(define declaration-heads
'(;; Guile and R6RS/R7RS module and library declarations
define-module use-modules import export re-export
include include-ci include-library-declarations
library define-library cond-expand declare
;; a file's own name, in each dialect
in-package defpackage
;; Emacs Lisp
require provide use-package require-theme declare-function
eval-after-load with-eval-after-load eval-when-compile
;; situations, not arguments
eval-when
;; Common Lisp
proclaim declaim))
(define define* define-public define-inlinable define-values define-syntax define-syntax-rule define-record-type define-class define-macro defun defmacro defsubst defalias defvar defconst defcustom defgroup defface defstruct defclass defparameter defconstant cl-defun cl-defmacro cl-defsubst cl-defmethod cl-defgeneric defmethod defgeneric)
(define definition-heads
'(define define* define-public define-inlinable define-values define-syntax
define-syntax-rule define-record-type define-class define-macro
defun defmacro defsubst defalias defvar defconst defcustom defgroup
defface defstruct defclass defparameter defconstant
cl-defun cl-defmacro cl-defsubst cl-defmethod cl-defgeneric
defmethod defgeneric))
((lambda . 2) (lambda* . 2) (case-lambda . 2) (define . 2) (define* . 2) (define-public . 2) (define-inlinable . 2) (define-values . 2) (destructuring-bind . 2) (defun . 3) (defmacro . 3) (defsubst . 3) (cl-defun . 3) (cl-defmacro . 3) (cl-defsubst . 3) (cl-defmethod . 3) (defmethod . 3) (defgeneric . 3) (cl-defgeneric . 3) (defsetf . 3) (define-setf-expander . 3))
(lambda (a) ...)' keeps them in the second element,
;;; `(define (f a) ...)' inside the name in the second, and `(defun f (a) ...)'
;;; in the third. A rule that counts parameters and a rule that must not read a
;;; parameter list as a call both have to ask this rather than guess "the second
;;; element", which is what made `(defun f (a b c d e f))' look like a call of
;;; `a' with six arguments.
;;;
;;; The number is the element's position, counting the operator as one.
(define formals-positions
'((lambda . 2)
(lambda* . 2)
(case-lambda . 2)
(define . 2)
(define* . 2)
(define-public . 2)
(define-inlinable . 2)
(define-values . 2)
(destructuring-bind . 2)
(defun . 3)
(defmacro . 3)
(defsubst . 3)
(cl-defun . 3)
(cl-defmacro . 3)
(cl-defsubst . 3)
(cl-defmethod . 3)
(defmethod . 3)
(defgeneric . 3)
(cl-defgeneric . 3)
(defsetf . 3)
(define-setf-expander . 3)))
Forms whose body is missing, or whose body is a ‘progn’ that need not be there. A body that is empty is usually a form that was written for its side effect and then edited; a body of one ‘progn’ is a form that was spliced by hand and never cleaned up.
(#<<lint-checker> name: empty-body code: "SIFT005" description: "A `cond`, `let` or `lambda` form with no body" dialects: all proc: #<procedure empty-body-warnings (ast source dialect)> severity: warning example: ((input . "(cond ((= x 1)))") (fix . "no automatic fix; write the body the clause needs"))> #<<lint-checker> name: redundant-progn code: "SIFT006" description: "`progn` used as the sole body of a form that already has an implicit `progn`" dialects: all proc: #<procedure redundant-progn-warnings (ast source dialect)> severity: warning example: ((input . "(define (f x) (progn (a) (b)))") (fix . "splice the `progn` body into the enclosing form"))> #<<lint-checker> name: when-without-body code: "SIFT013" description: "`when` form with no body" dialects: (scheme racket cl) proc: #<procedure 7f1815749ea0 at sift/checkers/bodies.scm:137:2 (ast source dialect)> severity: warning example: ((input . "(when (ready?))") (fix . "no automatic fix; add the body or drop the form"))> #<<lint-checker> name: unless-without-body code: "SIFT014" description: "`unless` form with no body" dialects: (scheme racket cl) proc: #<procedure 7f1815749e80 at sift/checkers/bodies.scm:137:2 (ast source dialect)> severity: warning example: ((input . "(unless (ready?))") (fix . "no automatic fix; add the body or drop the form"))> #<<lint-checker> name: negated-if code: "SIFT033" description: "`if` or `when` with a negated test, which `unless` says directly" dialects: (scheme elisp cl) proc: #<procedure negated-if-warnings (ast source dialect)> severity: warning example: ((input . "(if (not (ready?)) (wait) (go))") (fix . "(unless (ready?) (wait) (go))"))> #<<lint-checker> name: empty-form code: "SIFT008" description: "`()` used where a value is expected" dialects: (scheme racket) proc: #<procedure empty-form-warnings (ast source dialect)> severity: warning example: ((input . "(define (f) (list ()))") (fix . "no automatic fix; write `'()` or the value the form should return"))> #<<lint-checker> name: duplicate-keyword code: "SIFT009" description: "A keyword argument given more than once in the same call" dialects: all proc: #<procedure duplicate-keyword-warnings (ast source dialect)> severity: warning example: ((input . "(make-window :width 10 :width 20)") (fix . "no automatic fix; deciding which value was meant is the author's"))> #<<lint-checker> name: duplicate-binding code: "SIFT037" description: "The same name bound twice in one binding list" dialects: all proc: #<procedure duplicate-binding-warnings (ast source dialect)> severity: warning example: ((input . "(let ((x 1) (x 2)) x)") (fix . "no automatic fix; one of the two bindings is a mistake"))>)
(define bodies-checkers
(list empty-body-checker
redundant-progn-checker
when-without-body-checker
unless-without-body-checker
negated-if-checker
empty-form-checker
duplicate-keyword-checker
duplicate-binding-checker))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define duplicate-binding-checker
(checker 'duplicate-binding
"The same name bound twice in one binding list"
'all
duplicate-binding-warnings
#:severity 'warning
#:example '((input . "(let ((x 1) (x 2)) x)")
(fix . "no automatic fix; one of the two bindings is a mistake"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define duplicate-keyword-checker
(checker 'duplicate-keyword
"A keyword argument given more than once in the same call"
'all
duplicate-keyword-warnings
#:severity 'warning
#:example '((input . "(make-window :width 10 :width 20)")
(fix . "no automatic fix; deciding which value was meant is the author's"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define empty-body-checker
(checker 'empty-body
"A `cond`, `let` or `lambda` form with no body"
'all
empty-body-warnings
#:severity 'warning
#:example '((input . "(cond ((= x 1)))")
(fix . "no automatic fix; write the body the clause needs"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define empty-form-checker
(checker 'empty-form
"`()` used where a value is expected"
'(scheme racket)
empty-form-warnings
#:severity 'warning
#:example '((input . "(define (f) (list ()))")
(fix . "no automatic fix; write `'()` or the value the form should return"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define negated-if-checker
(checker 'negated-if
"`if` or `when` with a negated test, which `unless` says directly"
'(scheme elisp cl)
negated-if-warnings
#:severity 'warning
#:example '((input . "(if (not (ready?)) (wait) (go))")
(fix . "(unless (ready?) (wait) (go))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define redundant-progn-checker
(checker 'redundant-progn
"`progn` used as the sole body of a form that already has an implicit `progn`"
'all
redundant-progn-warnings
#:severity 'warning
#:example '((input . "(define (f x) (progn (a) (b)))")
(fix . "splice the `progn` body into the enclosing form"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define unless-without-body-checker
(checker 'unless-without-body
"`unless` form with no body"
'(scheme racket cl)
(without-body-warnings 'unless-without-body 'unless)
#:severity 'warning
#:example '((input . "(unless (ready?))")
(fix . "no automatic fix; add the body or drop the form"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define when-without-body-checker
(checker 'when-without-body
"`when` form with no body"
'(scheme racket cl)
(without-body-warnings 'when-without-body 'when)
#:severity 'warning
#:example '((input . "(when (ready?))")
(fix . "no automatic fix; add the body or drop the form"))))
Common Lisp names symbols through packages, and the Google Common Lisp style guide asks production code to say which package a symbol comes from instead of relying on the reader’s current one. These checkers report a missing package prefix, a ‘::‘ access to an internal symbol, a missing docstring, a LOOP that mixes keyword spellings, and two forms that say nothing their argument does not already say.
(#<<lint-checker> name: package-prefix code: "SIFT025" description: "Exported symbols referenced without a package prefix" dialects: (cl) proc: #<procedure package-prefix-warnings (ast source dialect)> severity: warning example: ((input . "(defpackage :app (:export #:run))\n(run)") (fix . "no automatic fix; write `app:run`"))> #<<lint-checker> name: double-colon code: "SIFT026" description: "Use of `package::internal-symbol` in production code" dialects: (cl) proc: #<procedure double-colon-warnings (ast source dialect)> severity: warning example: ((input . "(other::internal-thing 1)") (fix . "no automatic fix; export the symbol or use its public name"))> #<<lint-checker> name: defun-no-docstring code: "SIFT028" description: "`defun`, `defmacro` or `defgeneric` without a docstring" dialects: (cl) proc: #<procedure defun-no-docstring-warnings (ast source dialect)> severity: info example: ((input . "(defun f (x) (+ x 1))") (fix . "no automatic fix; write the docstring"))> #<<lint-checker> name: loop-keyword-style code: "SIFT029" description: "Symbolic LOOP keywords where the project style asks for literal `:keywords`" dialects: (cl) proc: #<procedure loop-keyword-style-warnings (ast source dialect)> severity: info example: ((input . "(loop for x in xs do (print x))") (fix . "(loop :for x :in xs :do (print x))"))> #<<lint-checker> name: redundant-identity code: "SIFT030" description: "`(identity x)` or `(funcall #'foo ...)` where the value suffices" dialects: (cl) proc: #<procedure redundant-identity-warnings (ast source dialect)> severity: info example: ((input . "(mapcar (lambda (x) (identity x)) xs)") (fix . "no automatic fix; drop the call"))> #<<lint-checker> name: defpackage-use code: "SIFT071" description: "A `defpackage` that `:use`s a package other than `:cl`" dialects: (cl) proc: #<procedure defpackage-use-warnings (ast source dialect)> severity: warning example: ((input . "(defpackage #:demo (:use #:cl #:alexandria))") (fix . "(defpackage #:demo (:use #:cl) (:import-from #:alexandria #:with-gensyms))"))> #<<lint-checker> name: ecase-otherwise code: "SIFT072" description: "A default clause in `ecase`, `etypecase`, `ccase` or `ctypecase`" dialects: (cl) proc: #<procedure ecase-otherwise-warnings (ast source dialect)> severity: warning example: ((input . "(ecase x (a 1) (t 2))") (fix . "(case x (a 1) (t 2))"))> #<<lint-checker> name: mixed-lambda-list code: "SIFT073" description: "A lambda list with both `&optional` and `&key`" dialects: (cl) proc: #<procedure mixed-lambda-list-warnings (ast source dialect)> severity: warning example: ((input . "(defun f (x &optional y &key z) (list x y z))") (fix . "(defun f (x &key y z) (list x y z))"))>)
(define cl-checkers
(list package-prefix-checker
double-colon-checker
defun-no-docstring-checker
loop-keyword-style-checker
redundant-identity-checker
defpackage-use-checker
ecase-otherwise-checker
mixed-lambda-list-checker))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define defpackage-use-checker
(checker 'defpackage-use
"A `defpackage` that `:use`s a package other than `:cl`"
'(cl)
defpackage-use-warnings
#:severity 'warning
#:example '((input . "(defpackage #:demo (:use #:cl #:alexandria))")
(fix . "(defpackage #:demo (:use #:cl) (:import-from #:alexandria #:with-gensyms))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define defun-no-docstring-checker
(checker 'defun-no-docstring
"`defun`, `defmacro` or `defgeneric` without a docstring"
'(cl)
defun-no-docstring-warnings
#:severity 'info
#:example '((input . "(defun f (x) (+ x 1))")
(fix . "no automatic fix; write the docstring"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define double-colon-checker
(checker 'double-colon
"Use of `package::internal-symbol` in production code"
'(cl)
double-colon-warnings
#:severity 'warning
#:example '((input . "(other::internal-thing 1)")
(fix . "no automatic fix; export the symbol or use its public name"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define ecase-otherwise-checker
(checker 'ecase-otherwise
"A default clause in `ecase`, `etypecase`, `ccase` or `ctypecase`"
'(cl)
ecase-otherwise-warnings
#:severity 'warning
#:example '((input . "(ecase x (a 1) (t 2))")
(fix . "(case x (a 1) (t 2))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define loop-keyword-style-checker
(checker 'loop-keyword-style
"Symbolic LOOP keywords where the project style asks for literal `:keywords`"
'(cl)
loop-keyword-style-warnings
#:severity 'info
#:example '((input . "(loop for x in xs do (print x))")
(fix . "(loop :for x :in xs :do (print x))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define mixed-lambda-list-checker
(checker 'mixed-lambda-list
"A lambda list with both `&optional` and `&key`"
'(cl)
mixed-lambda-list-warnings
#:severity 'warning
#:example '((input . "(defun f (x &optional y &key z) (list x y z))")
(fix . "(defun f (x &key y z) (list x y z))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define package-prefix-checker
(checker 'package-prefix
"Exported symbols referenced without a package prefix"
'(cl)
package-prefix-warnings
#:severity 'warning
#:example '((input . "(defpackage :app (:export #:run))\n(run)")
(fix . "no automatic fix; write `app:run`"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define redundant-identity-checker
(checker 'redundant-identity
"`(identity x)` or `(funcall #'foo ...)` where the value suffices"
'(cl)
redundant-identity-warnings
#:severity 'info
#:example '((input . "(mapcar (lambda (x) (identity x)) xs)")
(fix . "no automatic fix; drop the call"))))
A comment in a Lisp file is not written the same way wherever it sits. Riastradh’s rules give each position its own number of semicolons – four for a heading, three for a top-level comment, two for a comment inside a form, one for a comment at the end of a line – and the number is how a reader tells, at a glance, whether the comment is about the next form, about the form it is written in, or about the line it ends.
Only the line comments are judged. A block comment has no semicolons to count, and a comment inside a "#;" datum comment is part of code the reader was told not to read, so neither is reported.
The rule carries a fix, and it is the mechanical half of the rule: how many semicolons a comment takes is decided by the position it sits in – one at the end of a line, two inside a form, three at top level, four for a heading – and the position is something the reader knows, not something the author has to be asked about. What the fix does not decide is *what the comment says*: a comment that is about the next form and one that is about the form it sits in are both rewritten to the level of the place they are in, and if that place is the wrong one for the sentence, moving the comment is still the author’s work.
Return the number of semicolons a line comment takes at this position.
One at the end of a line, two inside a form, three at top level. A heading – four – is not a level this answers: it is a level the rule accepts and never asks for, because deciding that a comment is a heading is deciding what the comment is for.
Racket is the exception at top level, and it is not a detail: a Racket file writes a comment on its own line with two semicolons, which is what the style guide shows, what ‘raco fmt’ keeps, and what a three-semicolon comment means there – a section heading. Asking for three would demote every heading in the file to a plain comment.
(define (comment-level inside? dialect)
"Return the number of semicolons a line comment takes at this position.
One at the end of a line, two inside a form, three at top level. A heading --
four -- is not a level this answers: it is a level the rule accepts and never
asks for, because deciding that a comment is a heading is deciding what the
comment is for.
Racket is the exception at top level, and it is not a detail: a Racket file
writes a comment on its own line with two semicolons, which is what the style
guide shows, what `raco fmt' keeps, and what a three-semicolon comment means
there -- a section heading. Asking for three would demote every heading in
the file to a plain comment."
(cond
[inside? 2]
[(eq? dialect 'racket) 2]
[else 3]))
Return text with level semicolons and a space after them.
text is a comment as the reader kept it, leading semicolons included. The sentence of the comment is left exactly as it was – only the number of semicolons and the space between them and the sentence are rewritten – so a fix run over a buffer changes nothing a person wrote.
(define (normalise-comment text level)
"Return @var{text} with @var{level} semicolons and a space after them.
@var{text} is a comment as the reader kept it, leading semicolons included.
The sentence of the comment is left exactly as it was -- only the number of
semicolons and the space between them and the sentence are rewritten -- so a
fix run over a buffer changes nothing a person wrote."
(let ((body (trim-comment-body (comment-text text))))
(if (string-null? body)
(make-string level #\;)
(string-append (make-string level #\;) " " body))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define comment-semicolons-checker
(checker 'comment-semicolons
"A comment's semicolon level does not say where it belongs"
'all
comment-semicolons-warnings
#:severity 'info
#:example '((input . "(define (f x)\n ;; two semicolons, in a body\n x)\n;; one semicolon, at top level\n")
(fix . "use three at top level, two inside a form, one at the end of a line"))))
(#<<lint-checker> name: comment-semicolons code: "SIFT051" description: "A comment's semicolon level does not say where it belongs" dialects: all proc: #<procedure comment-semicolons-warnings (ast source dialect)> severity: info example: ((input . "(define (f x)\n ;; two semicolons, in a body\n x)\n;; one semicolon, at top level\n") (fix . "use three at top level, two inside a form, one at the end of a line"))>)
(define comments-checkers (list comment-semicolons-checker))
Emacs Lisp is the dialect with the most to say about how code is written down. The Emacs Lisp Reference Manual asks every command, function and variable intended for users to carry a docstring, asks the first line of that docstring to be a complete sentence that fits in 74 columns for ‘apropos’, asks continuation lines to start at column zero, and asks the first sentence to be in the imperative – "Return ...", not "Returns ...". These checkers report what the manual asks for, each one separately, so a project can take the ones it wants.
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define checkdoc-style-verb-checker
(checker 'checkdoc-style-verb
"Docstring first sentence uses the third person instead of the imperative"
'(elisp)
checkdoc-style-verb-warnings
#:severity 'info
#:example '((input . "(defun f (x)\n \"Returns x.\"\n x)")
(fix . "no automatic fix; write \"Return x.\""))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define declare-indent-checker
(checker 'declare-indent
"`declare` not indented two columns from the enclosing `defun`"
'(elisp)
declare-indent-warnings
#:severity 'info
#:example '((input . "(defun f (x)\n (declare (indent 1))\n x)")
(fix . "indent the `declare` two columns from the `defun`"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define docstring-arguments-checker
(checker 'docstring-arguments
"An Emacs Lisp docstring that does not mention one of its arguments"
'(elisp)
docstring-arguments-warnings
#:severity 'info
#:example '((input . "(defun add (a b)\n \"Add two numbers.\"\n (+ a b))")
(fix . "(defun add (a b)\n \"Add A and B.\"\n (+ a b))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define docstring-before-interactive-checker
(checker 'docstring-before-interactive
"A docstring that is not the first form in the body, so Emacs never reads it"
'(elisp)
docstring-before-interactive-warnings
#:severity 'warning
#:example '((input . "(defun f ()\n (interactive)\n \"Say hi.\"\n (message \"hi\"))")
(fix . "no automatic fix; move the docstring above `interactive`"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define docstring-first-line-checker
(checker 'docstring-first-line
"The first line of a docstring is not a capitalised sentence ending in a period"
'(elisp)
docstring-first-line-warnings
#:severity 'warning
#:example '((input . "(defun f (x)\n \"returns x.\"\n x)")
(fix . "no automatic fix; rewrite the first line"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define docstring-indent-checker
(checker 'docstring-indent
"Docstring continuation lines are indented instead of starting at column zero"
'(elisp)
docstring-indent-warnings
#:severity 'warning
#:example '((input . "(defun f (x)\n \"Doc.\n More.\"\n x)")
(fix . "no automatic fix; unindent the continuation lines"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define docstring-missing-checker
(checker 'docstring-missing
"`defun`, `defmacro`, `defsubst`, `defvar` or `defcustom` without a docstring"
'(elisp)
docstring-missing-warnings
#:severity 'warning
#:example '((input . "(defun f (x) (+ x 1))")
(fix . "no automatic fix; write the docstring"))))
(#<<lint-checker> name: docstring-missing code: "SIFT017" description: "`defun`, `defmacro`, `defsubst`, `defvar` or `defcustom` without a docstring" dialects: (elisp) proc: #<procedure docstring-missing-warnings (ast source dialect)> severity: warning example: ((input . "(defun f (x) (+ x 1))") (fix . "no automatic fix; write the docstring"))> #<<lint-checker> name: docstring-first-line code: "SIFT018" description: "The first line of a docstring is not a capitalised sentence ending in a period" dialects: (elisp) proc: #<procedure docstring-first-line-warnings (ast source dialect)> severity: warning example: ((input . "(defun f (x)\n \"returns x.\"\n x)") (fix . "no automatic fix; rewrite the first line"))> #<<lint-checker> name: docstring-indent code: "SIFT019" description: "Docstring continuation lines are indented instead of starting at column zero" dialects: (elisp) proc: #<procedure docstring-indent-warnings (ast source dialect)> severity: warning example: ((input . "(defun f (x)\n \"Doc.\n More.\"\n x)") (fix . "no automatic fix; unindent the continuation lines"))> #<<lint-checker> name: lexical-binding-missing code: "SIFT020" description: "The file header lacks `-*- lexical-binding: t; -*-`" dialects: (elisp) proc: #<procedure lexical-binding-missing-warnings (ast source dialect)> severity: warning example: ((input . ";;; foo.el --- a package\n") (fix . "insert \"-*- lexical-binding: t; -*-\" in the file header"))> #<<lint-checker> name: interactive-without-docstring code: "SIFT021" description: "An `interactive` command without a docstring" dialects: (elisp) proc: #<procedure interactive-without-docstring-warnings (ast source dialect)> severity: warning example: ((input . "(defun my-command ()\n (interactive)\n (message \"hi\"))") (fix . "no automatic fix; document the command"))> #<<lint-checker> name: checkdoc-style-verb code: "SIFT022" description: "Docstring first sentence uses the third person instead of the imperative" dialects: (elisp) proc: #<procedure checkdoc-style-verb-warnings (ast source dialect)> severity: info example: ((input . "(defun f (x)\n \"Returns x.\"\n x)") (fix . "no automatic fix; write \"Return x.\""))> #<<lint-checker> name: provide-missing code: "SIFT023" description: "The file defines a package but has no final `(provide 'feature)`" dialects: (elisp) proc: #<procedure provide-missing-warnings (ast source dialect)> severity: warning example: ((input . "(defun my-f ()\n \"Do it.\"\n nil)") (fix . "no automatic fix; add (provide 'my-feature) at the end"))> #<<lint-checker> name: declare-indent code: "SIFT024" description: "`declare` not indented two columns from the enclosing `defun`" dialects: (elisp) proc: #<procedure declare-indent-warnings (ast source dialect)> severity: info example: ((input . "(defun f (x)\n (declare (indent 1))\n x)") (fix . "indent the `declare` two columns from the `defun`"))> #<<lint-checker> name: docstring-arguments code: "SIFT034" description: "An Emacs Lisp docstring that does not mention one of its arguments" dialects: (elisp) proc: #<procedure docstring-arguments-warnings (ast source dialect)> severity: info example: ((input . "(defun add (a b)\n \"Add two numbers.\"\n (+ a b))") (fix . "(defun add (a b)\n \"Add A and B.\"\n (+ a b))"))> #<<lint-checker> name: docstring-before-interactive code: "SIFT038" description: "A docstring that is not the first form in the body, so Emacs never reads it" dialects: (elisp) proc: #<procedure docstring-before-interactive-warnings (ast source dialect)> severity: warning example: ((input . "(defun f ()\n (interactive)\n \"Say hi.\"\n (message \"hi\"))") (fix . "no automatic fix; move the docstring above `interactive`"))> #<<lint-checker> name: require-cl code: "SIFT074" description: "A `require` of the deprecated `cl` library instead of `cl-lib`" dialects: (elisp) proc: #<procedure require-cl-warnings (ast source dialect)> severity: warning example: ((input . "(require 'cl)") (fix . "no automatic fix; `cl-lib` renames every symbol the file uses"))> #<<lint-checker> name: save-excursion-set-buffer code: "SIFT075" description: "A `set-buffer` inside `save-excursion`, where `with-current-buffer` belongs" dialects: (elisp) proc: #<procedure save-excursion-set-buffer-warnings (ast source dialect)> severity: warning example: ((input . "(save-excursion (set-buffer buffer) (goto-char (point-min))))") (fix . "(with-current-buffer buffer (save-excursion (goto-char (point-min))))"))> #<<lint-checker> name: interactive-without-arguments code: "SIFT076" description: "A command with required parameters whose `interactive` form supplies none" dialects: (elisp) proc: #<procedure interactive-without-arguments-warnings (ast source dialect)> severity: warning example: ((input . "(defun my-command (arg)\n \"Do ARG.\"\n (interactive)\n (message \"%s\" arg))") (fix . "(defun my-command (arg)\n \"Do ARG.\"\n (interactive \"p\")\n (message \"%s\" arg))"))>)
(define elisp-checkers
(list docstring-missing-checker
docstring-first-line-checker
docstring-indent-checker
lexical-binding-missing-checker
interactive-without-docstring-checker
checkdoc-style-verb-checker
provide-missing-checker
declare-indent-checker
docstring-arguments-checker
docstring-before-interactive-checker
require-cl-checker
save-excursion-set-buffer-checker
interactive-without-arguments-checker))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define interactive-without-arguments-checker
(checker 'interactive-without-arguments
"A command with required parameters whose `interactive` form supplies none"
'(elisp)
interactive-without-arguments-warnings
#:severity 'warning
#:example '((input . "(defun my-command (arg)\n \"Do ARG.\"\n (interactive)\n (message \"%s\" arg))")
(fix . "(defun my-command (arg)\n \"Do ARG.\"\n (interactive \"p\")\n (message \"%s\" arg))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define interactive-without-docstring-checker
(checker 'interactive-without-docstring
"An `interactive` command without a docstring"
'(elisp)
interactive-without-docstring-warnings
#:severity 'warning
#:example '((input . "(defun my-command ()\n (interactive)\n (message \"hi\"))")
(fix . "no automatic fix; document the command"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define lexical-binding-missing-checker
(checker 'lexical-binding-missing
"The file header lacks `-*- lexical-binding: t; -*-`"
'(elisp)
lexical-binding-missing-warnings
#:severity 'warning
#:example '((input . ";;; foo.el --- a package\n")
(fix . "insert \"-*- lexical-binding: t; -*-\" in the file header"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define provide-missing-checker
(checker 'provide-missing
"The file defines a package but has no final `(provide 'feature)`"
'(elisp)
provide-missing-warnings
#:severity 'warning
#:example '((input . "(defun my-f ()\n \"Do it.\"\n nil)")
(fix . "no automatic fix; add (provide 'my-feature) at the end"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define require-cl-checker
(checker 'require-cl
"A `require` of the deprecated `cl` library instead of `cl-lib`"
'(elisp)
require-cl-warnings
#:severity 'warning
#:example '((input . "(require 'cl)")
(fix . "no automatic fix; `cl-lib` renames every symbol the file uses"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define save-excursion-set-buffer-checker
(checker 'save-excursion-set-buffer
"A `set-buffer` inside `save-excursion`, where `with-current-buffer` belongs"
'(elisp)
save-excursion-set-buffer-warnings
#:severity 'warning
#:example '((input . "(save-excursion (set-buffer buffer) (goto-char (point-min))))")
(fix . "(with-current-buffer buffer (save-excursion (goto-char (point-min))))"))))
Suggestions about the *shape* of a form rather than about its correctness. Lisp has two ways of keeping a form readable: bind the part that got long, and name the arguments that stopped fitting. Two checkers say when one of those moments has arrived; neither has an automatic fix, because choosing the name and the split is the author’s work. The other three are about how much a definition asks of a reader: how deep its conditionals chain, how much the whole definition costs, and how many paths it hides.
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define cognitive-complexity-checker
(checker 'cognitive-complexity
"A definition whose cognitive complexity is over the configured budget"
'all
cognitive-complexity-warnings
#:severity 'info
#:example '((input . "(define (f x)\n (if (a) (if (b) (if (c) (if (d) (if (e) 1 2))))))")
(fix . "no automatic fix; extract the innermost branch into a procedure"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define cyclomatic-complexity-checker
(checker 'cyclomatic-complexity
"A definition with more paths than the configured budget"
'all
cyclomatic-complexity-warnings
#:severity 'info
#:example '((input . "(define (f x)\n (if (a) 1 (if (b) 2 (if (c) 3 (if (d) 4 5)))))")
(fix . "no automatic fix; a path is a test to write, so name it in a procedure"))))
(#<<lint-checker> name: wrap-in-let code: "SIFT031" description: "A body form that is too deep or too long to read as one expression" dialects: all proc: #<procedure wrap-in-let-warnings (ast source dialect)> severity: info example: ((input . "(define (f x)\n (list (car (cdr (assq 'a (cdr x))))))") (fix . "no automatic fix; bind the repeated part in a `let`"))> #<<lint-checker> name: keyword-arguments code: "SIFT032" description: "A call with more positional arguments than a reader can keep in mind" dialects: all proc: #<procedure keyword-arguments-warnings (ast source dialect)> severity: info example: ((input . "(make-window a b c d e f g)") (fix . "no automatic fix; name the arguments and pass them as keywords"))> #<<lint-checker> name: unused-argument code: "SIFT043" description: "A parameter that the definition never refers to" dialects: all proc: #<procedure unused-argument-warnings (ast source dialect)> severity: info example: ((input . "(define (f x y) (list x))") (fix . "no automatic fix; use it, drop it, or name it `_y`"))> #<<lint-checker> name: nesting-depth code: "SIFT044" description: "A definition whose body nests deeper than the configured limit" dialects: all proc: #<procedure nesting-depth-warnings (ast source dialect)> severity: warning example: ((input . "(define (f x)\n (if (a) (if (b) (if (c)\n (if (d) (if (e) 1 2))))))") (fix . "no automatic fix; extract the inner form into its own procedure"))> #<<lint-checker> name: cognitive-complexity code: "SIFT094" description: "A definition whose cognitive complexity is over the configured budget" dialects: all proc: #<procedure cognitive-complexity-warnings (ast source dialect)> severity: info example: ((input . "(define (f x)\n (if (a) (if (b) (if (c) (if (d) (if (e) 1 2))))))") (fix . "no automatic fix; extract the innermost branch into a procedure"))> #<<lint-checker> name: cyclomatic-complexity code: "SIFT095" description: "A definition with more paths than the configured budget" dialects: all proc: #<procedure cyclomatic-complexity-warnings (ast source dialect)> severity: info example: ((input . "(define (f x)\n (if (a) 1 (if (b) 2 (if (c) 3 (if (d) 4 5)))))") (fix . "no automatic fix; a path is a test to write, so name it in a procedure"))>)
(define ergonomics-checkers
(list wrap-in-let-checker
keyword-arguments-checker
unused-argument-checker
nesting-depth-checker
cognitive-complexity-checker
cyclomatic-complexity-checker))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define keyword-arguments-checker
(checker 'keyword-arguments
"A call with more positional arguments than a reader can keep in mind"
'all
keyword-arguments-warnings
#:severity 'info
#:example '((input . "(make-window a b c d e f g)")
(fix . "no automatic fix; name the arguments and pass them as keywords"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define wrap-in-let-checker
(checker 'wrap-in-let
"A body form that is too deep or too long to read as one expression"
'all
wrap-in-let-warnings
#:severity 'info
#:example '((input . "(define (f x)\n (list (car (cdr (assq 'a (cdr x))))))")
(fix . "no automatic fix; bind the repeated part in a `let`"))))
Guix is Scheme with three things added: gexps – the ‘#~’ family of reader prefixes – a package record whose fields are a vocabulary of their own, and a build stratum that a phase lambda runs in rather than the one the file runs in. Most of what goes wrong in a package definition goes wrong at one of those three seams, and every rule here reads it off the text.
The gexp rules are about the seam itself: a gexp that is quoted is the form and not the object, an ‘#$’ with no gexp around it is a token with no meaning, a ‘#$output‘ in a file-making gexp is a ‘getenv‘ that answers false, and a build module imported without ‘with-imported-modules’ is a module the builder will not find. The ‘assoc-ref’ and ‘string-append’ rules are the same seam seen from the older spelling: what the gexp machinery substitutes, the alists made the build compute by hand.
The package rules are the manual’s own: a synopsis is a lower-case phrase without a period, a description is a literal string because xgettext has to be able to read it, a hash is 52 base32 characters, and an input list needs no labels.
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define assoc-ref-outputs-checker
(checker 'assoc-ref-outputs
"`(assoc-ref %outputs \"out\")` inside a gexp, where `#$output` says it"
'(scheme)
assoc-ref-outputs-warnings
#:severity 'warning
#:example '((input . "#~(mkdir (assoc-ref %outputs \"out\"))")
(fix . "#~(mkdir #$output)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define gexp-output-script-checker
(checker 'gexp-output-script
"A `#$output` in a gexp that makes a file rather than a derivation"
'(scheme)
gexp-output-script-warnings
#:severity 'warning
#:example '((input . "(program-file \"run.sh\" #~(execl #$output \"x\" #f))")
(fix . "(program-file \"run.sh\" #~(execl #$(file-append coreutils \"/bin/ls\") \"ls\" #f))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define gexp-quoted-checker
(checker 'gexp-quoted
"A gexp written under a quote, where what is quoted is the form"
'(scheme)
gexp-quoted-warnings
#:severity 'warning
#:example '((input . "'#~(mkdir #$output)")
(fix . "#~(mkdir #$output)"))))
(#<<lint-checker> name: gexp-quoted code: "SIFT077" description: "A gexp written under a quote, where what is quoted is the form" dialects: (scheme) proc: #<procedure gexp-quoted-warnings (ast source dialect)> severity: warning example: ((input . "'#~(mkdir #$output)") (fix . "#~(mkdir #$output)"))> #<<lint-checker> name: ungexp-outside-gexp code: "SIFT078" description: "An `#$`, `#$@@`, `#+` or `#+@@` with no gexp around it" dialects: (scheme) proc: #<procedure ungexp-outside-gexp-warnings (ast source dialect)> severity: warning example: ((input . "(list #$output)") (fix . "(list #$output)"))> #<<lint-checker> name: gexp-output-script code: "SIFT079" description: "A `#$output` in a gexp that makes a file rather than a derivation" dialects: (scheme) proc: #<procedure gexp-output-script-warnings (ast source dialect)> severity: warning example: ((input . "(program-file \"run.sh\" #~(execl #$output \"x\" #f))") (fix . "(program-file \"run.sh\" #~(execl #$(file-append coreutils \"/bin/ls\") \"ls\" #f))"))> #<<lint-checker> name: assoc-ref-outputs code: "SIFT080" description: "`(assoc-ref %outputs \"out\")` inside a gexp, where `#$output` says it" dialects: (scheme) proc: #<procedure assoc-ref-outputs-warnings (ast source dialect)> severity: warning example: ((input . "#~(mkdir (assoc-ref %outputs \"out\"))") (fix . "#~(mkdir #$output)"))> #<<lint-checker> name: string-append-file-append code: "SIFT081" description: "A gexp `string-append` of a package and a literal path, where `file-append` says it" dialects: (scheme) proc: #<procedure string-append-file-append-warnings (ast source dialect)> severity: info example: ((input . "#~(system* (string-append #$coreutils \"/bin/ls\"))") (fix . "#~(system* #$(file-append coreutils \"/bin/ls\"))"))> #<<lint-checker> name: phase-name-quoting code: "SIFT082" description: "A phase named by an unquoted symbol or a string in `modify-phases`" dialects: (scheme) proc: #<procedure phase-name-quoting-warnings (ast source dialect)> severity: warning example: ((input . "(modify-phases %standard-phases (delete configure))") (fix . "(modify-phases %standard-phases (delete 'configure))"))> #<<lint-checker> name: use-modules-in-gexp code: "SIFT083" description: "A build module imported inside a gexp that `with-imported-modules` does not mark" dialects: (scheme) proc: #<procedure use-modules-in-gexp-warnings (ast source dialect)> severity: warning example: ((input . "#~(use-modules (guix build utils))") (fix . "(with-imported-modules '((guix build utils))\n #~(use-modules (guix build utils)))"))> #<<lint-checker> name: package-synopsis code: "SIFT084" description: "A synopsis that opens with an article, ends with a period, or starts in lower case" dialects: (scheme) proc: #<procedure package-synopsis-warnings (ast source dialect)> severity: warning example: ((input . "(package (synopsis \"A file frobber.\"))") (fix . "(package (synopsis \"File frobber\"))"))> #<<lint-checker> name: package-description-literal code: "SIFT085" description: "A description built by `string-append` rather than written as one string" dialects: (scheme) proc: #<procedure package-description-literal-warnings (ast source dialect)> severity: warning example: ((input . "(package (description (string-append \"Frob \" \"files.\")))") (fix . "(package (description \"Frob files.\"))"))> #<<lint-checker> name: sha256-base32 code: "SIFT086" description: "A `sha256` that is not `(base32 \"...\")` of 52 lower-case characters" dialects: (scheme) proc: #<procedure sha256-base32-warnings (ast source dialect)> severity: warning example: ((input . "(origin (sha256 (base32 \"abc\")))") (fix . "(origin (sha256 (base32 \"0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i\")))"))> #<<lint-checker> name: inputs-label-alist code: "SIFT087" description: "An `inputs` written as a labelled alist instead of a list of packages" dialects: (scheme) proc: #<procedure inputs-label-alist-warnings (ast source dialect)> severity: warning example: ((input . "(package (inputs `((\"gawk\" ,gawk))))") (fix . "(package (inputs (list gawk)))"))>)
(define guix-checkers
(list gexp-quoted-checker
ungexp-outside-gexp-checker
gexp-output-script-checker
assoc-ref-outputs-checker
string-append-file-append-checker
phase-name-quoting-checker
use-modules-in-gexp-checker
package-synopsis-checker
package-description-literal-checker
sha256-base32-checker
inputs-label-alist-checker))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define inputs-label-alist-checker
(checker 'inputs-label-alist
"An `inputs` written as a labelled alist instead of a list of packages"
'(scheme)
inputs-label-alist-warnings
#:severity 'warning
#:example '((input . "(package (inputs `((\"gawk\" ,gawk))))")
(fix . "(package (inputs (list gawk)))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define package-description-literal-checker
(checker 'package-description-literal
"A description built by `string-append` rather than written as one string"
'(scheme)
package-description-literal-warnings
#:severity 'warning
#:example '((input . "(package (description (string-append \"Frob \" \"files.\")))")
(fix . "(package (description \"Frob files.\"))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define package-synopsis-checker
(checker 'package-synopsis
"A synopsis that opens with an article, ends with a period, or starts in lower case"
'(scheme)
package-synopsis-warnings
#:severity 'warning
#:example '((input . "(package (synopsis \"A file frobber.\"))")
(fix . "(package (synopsis \"File frobber\"))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define phase-name-quoting-checker
(checker 'phase-name-quoting
"A phase named by an unquoted symbol or a string in `modify-phases`"
'(scheme)
phase-name-quoting-warnings
#:severity 'warning
#:example '((input . "(modify-phases %standard-phases (delete configure))")
(fix . "(modify-phases %standard-phases (delete 'configure))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define sha256-base32-checker
(checker 'sha256-base32
"A `sha256` that is not `(base32 \"...\")` of 52 lower-case characters"
'(scheme)
sha256-base32-warnings
#:severity 'warning
#:example '((input . "(origin (sha256 (base32 \"abc\")))")
(fix . "(origin (sha256 (base32 \"0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i\")))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define string-append-file-append-checker
(checker 'string-append-file-append
"A gexp `string-append` of a package and a literal path, where `file-append` says it"
'(scheme)
string-append-file-append-warnings
#:severity 'info
#:example '((input . "#~(system* (string-append #$coreutils \"/bin/ls\"))")
(fix . "#~(system* #$(file-append coreutils \"/bin/ls\"))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define ungexp-outside-gexp-checker
(checker 'ungexp-outside-gexp
"An `#$`, `#$@`, `#+` or `#+@` with no gexp around it"
'(scheme)
ungexp-outside-gexp-warnings
#:severity 'warning
#:example '((input . "(list #$output)")
(fix . "(list #$output)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define use-modules-in-gexp-checker
(checker 'use-modules-in-gexp
"A build module imported inside a gexp that `with-imported-modules` does not mark"
'(scheme)
use-modules-in-gexp-warnings
#:severity 'warning
#:example '((input . "#~(use-modules (guix build utils))")
(fix . "(with-imported-modules '((guix build utils))\n #~(use-modules (guix build utils)))"))))
Four questions a single form cannot answer, and the line every one of them stops at. A call’s arity is a fact about the definition it resolves to, a literal’s type is a fact about the literal, a comparison’s right predicate is a fact about the literal it compares against, and an import is unused only when the whole file has been read. None of them needs a type system: each is decided from what the source says outright, and a value whose type the source does not state is left alone rather than guessed at.
That is also why these are separate from the shape rules. A shape rule can be answered while the form is in front of the reader; these need the definition table, which is the whole file, so they are the ones the language server computes after it has published the findings it can answer at once.
(CLAUSES KEYWORDS PARAMETERS) for the procedure form
(CLAUSES KEYWORDS PARAMETERS) for one parameter list, or
#f.
Return a sentence saying what arity accepts, for a hover.
The words are the ones a finding uses – ‘takes 1 to 2 arguments’ – with the keywords a definition takes named after them, because an editor showing a signature has the room to say which keyword and a message has to stay short.
(define* (arity-summary arity #:optional (dialect 'scheme))
"Return a sentence saying what @var{arity} accepts, for a hover.
The words are the ones a finding uses -- `takes 1 to 2 arguments' -- with the
keywords a definition takes named after them, because an editor showing a
signature has the room to say which keyword and a message has to stay short."
(let ((keywords (cdr arity))
(sigil (if (eq? dialect 'scheme) "#:" ":")))
(string-append
(format #f "takes ~a" (arity-phrase arity))
(cond
[(eq? keywords #f) ", and any keyword"]
[(null? keywords) ""]
[else
(format #f ", and the keyword~a ~a"
(if (= 1 (length keywords)) "" "s")
(string-join
(map (lambda (keyword)
(format #f "`~a~a`" sigil keyword))
keywords)
", "))]))))
Return (CLAUSES KEYWORDS PARAMETERS) for the procedure form
defines, or #f.
A definition states one in three shapes: the parameter list beside the name (‘(define (f a) ...)’, ‘(defun f (a) ...)’), a procedure value (‘(define f (lambda (a) ...))’), or a list of clauses (‘(define f (case-lambda (() ...) ((a) ...)))’). ‘define-syntax’ states none: a macro’s arguments are a pattern, and a pattern is not a parameter list.
(define (form-signature form)
"Return @code{(CLAUSES KEYWORDS PARAMETERS)} for the procedure @var{form}
defines, or @code{#f}.
A definition states one in three shapes: the parameter list beside the name
(`(define (f a) ...)', `(defun f (a) ...)'), a procedure value
(`(define f (lambda (a) ...))'), or a list of clauses
(`(define f (case-lambda (() ...) ((a) ...)))'). `define-syntax' states none:
a macro's arguments are a pattern, and a pattern is not a parameter list."
(let ((head (and (node-list? form) (node-head-name form)))
(arguments (form-arguments form)))
(cond
[(memq head '(define define* define-public define-inlinable define-macro))
(let ((first (and (pair? arguments) (car arguments))))
(if (and first (node-list? first))
(signature-of-formals (cdr (node-elements first)))
(and (pair? (cdr arguments)) (lambda-signature (cadr arguments)))))]
[(memq head '(defun defsubst defmacro cl-defun cl-defsubst cl-defmacro
defmethod cl-defmethod defgeneric cl-defgeneric
define-minor-mode define-derived-mode define-generic-mode))
(and (pair? (cdr arguments))
(signature-of-formals (parameters-of (cadr arguments))))]
[(memq head '(defvar defvar-local defcustom defparameter defface defalias))
(and (pair? (cdr arguments)) (lambda-signature (cadr arguments)))]
[else #f])))
Return (CLAUSES KEYWORDS PARAMETERS) for one parameter list, or
#f.
elements is the list of nodes a parameter list is made of. CLAUSES
and KEYWORDS are the arity; PARAMETERS is the same list read for
display, one (KIND . NODE) per argument a caller passes, KIND
being ‘required’, ‘optional’, ‘key’ or ‘rest’. A marker is not a
parameter: ‘#:optional’ says what the rest of the list means, and an
editor that showed it as an argument would be showing sift’s vocabulary
instead of the procedure’s.
#f is the answer to a parameter list this rule cannot read – a
marker it does not know, a keyword specification with no name in it –
because a count guessed from half a list is a finding about sift rather
than about the program, and an omission is cheaper than a wrong answer.
(define (signature-of-formals elements)
"Return @code{(CLAUSES KEYWORDS PARAMETERS)} for one parameter list, or #f.
@var{elements} is the list of nodes a parameter list is made of. CLAUSES and
KEYWORDS are the arity; PARAMETERS is the same list read for display, one
@code{(KIND . NODE)} per argument a caller passes, KIND being `required',
`optional', `key' or `rest'. A marker is not a parameter: `#:optional' says
what the rest of the list means, and an editor that showed it as an argument
would be showing sift's vocabulary instead of the procedure's.
@code{#f} is the answer to a parameter list this rule cannot read -- a marker
it does not know, a keyword specification with no name in it -- because a
count guessed from half a list is a finding about sift rather than about the
program, and an omission is cheaper than a wrong answer."
(let loop ((rest elements) (required 0) (optional 0) (state 'required)
(keywords '()) (parameters '()))
(define (finish)
(list (list (cons required (+ required optional))) keywords
(reverse parameters)))
(define (passed kind node)
(loop (cdr rest)
(if (eq? state 'required) (+ required 1) required)
(if (eq? state 'optional) (+ optional 1) optional)
state keywords (cons (cons kind node) parameters)))
(cond
[(null? rest) (finish)]
;; a destructuring parameter, or a `(name default)' pair: one argument,
;; whichever part of the parameter list it is written in
[(not (node-atom? (car rest)))
(if (eq? state 'key)
(let ((name (keyword-parameter-name (car rest))))
(and name
(loop (cdr rest) required optional state (cons name keywords)
(cons (cons 'key (key-display-node (car rest))) parameters))))
(passed (if (eq? state 'optional) 'optional 'required) (car rest)))]
[else
(let ((name (marker-name (car rest))))
(cond
;; a dotted tail is a rest parameter spelled with a dot
[(and (eq? (node-atom-type (car rest)) 'symbol)
(string=? (node-value (car rest)) "."))
(list (list (cons required #f)) #f
(reverse (if (pair? (cdr rest))
(cons (cons 'rest (cadr rest)) parameters)
parameters)))]
[(not name)
(if (eq? state 'key)
(loop (cdr rest) required optional state
(cons (atom-symbol (car rest)) keywords)
(cons (cons 'key (car rest)) parameters))
(passed (if (eq? state 'optional) 'optional 'required)
(car rest)))]
[(member name '("rest" "body"))
(list (list (cons required #f)) #f
(reverse (if (pair? (cdr rest))
(cons (cons 'rest (cadr rest)) parameters)
parameters)))]
[(equal? name "optional")
(loop (cdr rest) required optional 'optional keywords parameters)]
[(equal? name "key")
(loop (cdr rest) required optional 'key keywords parameters)]
[(equal? name "aux")
(loop (cdr rest) required optional 'aux keywords parameters)]
[(equal? name "allow-other-keys")
(loop (cdr rest) required optional state #f parameters)]
[(member name '("whole" "environment"))
(loop (cdr rest) required optional state keywords parameters)]
[else #f]))])))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define call-arity-checker
(checker 'call-arity
"A call whose arguments do not match the definition in this file: too few, too many, or a keyword it does not take"
'(scheme elisp cl)
call-arity-warnings
#:severity 'info
#:example '((input . "(define (area width height) 0)\n(area 2)\n")
(fix . "(area 2 3)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define eq-non-symbol-checker
(checker 'eq-non-symbol
"`eq`/`eq?` of a literal that identity cannot decide, where the value predicate can"
'(scheme racket elisp cl)
eq-non-symbol-warnings
#:severity 'warning
#:example '((input . "(eq? x 1)")
(fix . "(eqv? x 1)"))))
(call-arity string-literal-argument number-literal-argument eq-non-symbol unused-import-from)
(define inference-checker-names
'(call-arity string-literal-argument number-literal-argument
eq-non-symbol unused-import-from))
(#<<lint-checker> name: call-arity code: "SIFT088" description: "A call whose arguments do not match the definition in this file: too few, too many, or a keyword it does not take" dialects: (scheme elisp cl) proc: #<procedure call-arity-warnings (ast source dialect)> severity: info example: ((input . "(define (area width height) 0)\n(area 2)\n") (fix . "(area 2 3)"))> #<<lint-checker> name: string-literal-argument code: "SIFT089" description: "A number or boolean passed where the operator's convention says a string" dialects: (scheme racket elisp cl) proc: #<procedure string-literal-argument-warnings (ast source dialect)> severity: warning example: ((input . "(string-append \"a\" 1)") (fix . "(string-append \"a\" \"1\")"))> #<<lint-checker> name: number-literal-argument code: "SIFT090" description: "A string passed to an operator whose arguments are numbers" dialects: (scheme racket elisp cl) proc: #<procedure number-literal-argument-warnings (ast source dialect)> severity: warning example: ((input . "(+ 1 \"2\")") (fix . "(+ 1 2)"))> #<<lint-checker> name: eq-non-symbol code: "SIFT092" description: "`eq`/`eq?` of a literal that identity cannot decide, where the value predicate can" dialects: (scheme racket elisp cl) proc: #<procedure eq-non-symbol-warnings (ast source dialect)> severity: warning example: ((input . "(eq? x 1)") (fix . "(eqv? x 1)"))> #<<lint-checker> name: unused-import-from code: "SIFT091" description: "A name a `defpackage` imports with `:import-from` and the file never uses" dialects: (cl) proc: #<procedure unused-import-from-warnings (ast source dialect)> severity: info example: ((input . "(defpackage :demo (:use :cl) (:import-from :alexandria #:curry))\n(in-package :demo)\n") (fix . "(defpackage :demo (:use :cl))\n(in-package :demo)\n"))>)
(define inference-checkers
(list call-arity-checker
string-literal-argument-checker
number-literal-argument-checker
eq-non-symbol-checker
unused-import-from-checker))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define number-literal-argument-checker
(checker 'number-literal-argument
"A string passed to an operator whose arguments are numbers"
'(scheme racket elisp cl)
number-literal-argument-warnings
#:severity 'warning
#:example '((input . "(+ 1 \"2\")")
(fix . "(+ 1 2)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define string-literal-argument-checker
(checker 'string-literal-argument
"A number or boolean passed where the operator's convention says a string"
'(scheme racket elisp cl)
string-literal-argument-warnings
#:severity 'warning
#:example '((input . "(string-append \"a\" 1)")
(fix . "(string-append \"a\" \"1\")"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define unused-import-from-checker
(checker 'unused-import-from
"A name a `defpackage` imports with `:import-from` and the file never uses"
'(cl)
unused-import-from-warnings
#:severity 'info
#:example '((input . "(defpackage :demo (:use :cl) (:import-from :alexandria #:curry))\n(in-package :demo)\n")
(fix . "(defpackage :demo (:use :cl))\n(in-package :demo)\n"))))
A Lisp has no type declarations to lean on, so a name is most of what a reader knows about a value: that it is a predicate, that it is special, that it is a constant. These three rules are about the name rather than about the code under it.
None of them has a fix. Renaming a definition is a refactor: it changes every call site in every file, and a formatter that renames one of them has broken the program. So the rules report, and the author decides.
(#<<lint-checker> name: naming-convention code: "SIFT040" description: "An underscore or camelCase in the name of a definition" dialects: all proc: #<procedure naming-convention-warnings (ast source dialect)> severity: warning example: ((input . "(define (read_file path) ...)") (fix . "no automatic fix; renaming changes every call site"))> #<<lint-checker> name: predicate-name code: "SIFT041" description: "A procedure that answers a question but is not named like one" dialects: all proc: #<procedure predicate-name-warnings (ast source dialect)> severity: info example: ((input . "(define (positive x) (> x 0))") (fix . "no automatic fix; rename it to `positive?`"))> #<<lint-checker> name: special-variable-name code: "SIFT042" description: "A special variable or constant whose name does not say so" dialects: (elisp cl) proc: #<procedure special-variable-name-warnings (ast source dialect)> severity: info example: ((input . "(defparameter port 8080)") (fix . "no automatic fix; rename it to `*port*`"))> #<<lint-checker> name: single-letter-name code: "SIFT053" description: "A variable named with a single letter" dialects: all proc: #<procedure single-letter-name-warnings (ast source dialect)> severity: info example: ((input . "(define (area w h) (* w h))") (fix . "no automatic fix; rename the parameter to a word"))>)
(define naming-checkers
(list naming-convention-checker
predicate-name-checker
special-variable-name-checker
single-letter-name-checker))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define naming-convention-checker
(checker 'naming-convention
"An underscore or camelCase in the name of a definition"
'all
naming-convention-warnings
#:severity 'warning
#:example '((input . "(define (read_file path) ...)")
(fix . "no automatic fix; renaming changes every call site"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define predicate-name-checker
(checker 'predicate-name
"A procedure that answers a question but is not named like one"
'all
predicate-name-warnings
#:severity 'info
#:example '((input . "(define (positive x) (> x 0))")
(fix . "no automatic fix; rename it to `positive?`"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define single-letter-name-checker
(checker 'single-letter-name
"A variable named with a single letter"
'all
single-letter-name-warnings
#:severity 'info
#:example '((input . "(define (area w h) (* w h))")
(fix . "no automatic fix; rename the parameter to a word"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define special-variable-name-checker
(checker 'special-variable-name
"A special variable or constant whose name does not say so"
'(elisp cl)
special-variable-name-warnings
#:severity 'info
#:example '((input . "(defparameter port 8080)")
(fix . "no automatic fix; rename it to `*port*`"))))
Three checkers about delimiters: one that reports a file whose brackets do not balance, one that reports the dangling style in Common Lisp, and one that reports a reader prefix separated from the datum it applies to.
The first never guesses. A missing ‘)’ is reported where the form was opened, not where sift would like it to be, because an editor that inserts a delimiter on a guess can silently change what a program means.
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define dangling-paren-checker
(checker 'dangling-paren
"Closing parenthesis on its own line"
'(cl)
dangling-paren-warnings
#:severity 'warning
#:example '((input . "(defun f (x)\n x\n )")
(fix . "pull the closing parenthesis onto the previous line"))))
(#<<lint-checker> name: unmatched-parens code: "SIFT004" description: "Unbalanced or unmatched parentheses or brackets" dialects: all proc: #<procedure unmatched-parens-warnings (ast source dialect)> severity: error example: ((input . "(define (f x)\n x") (fix . "no automatic fix; sift never guesses where a `)' goes"))> #<<lint-checker> name: dangling-paren code: "SIFT027" description: "Closing parenthesis on its own line" dialects: (cl) proc: #<procedure dangling-paren-warnings (ast source dialect)> severity: warning example: ((input . "(defun f (x)\n x\n )") (fix . "pull the closing parenthesis onto the previous line"))> #<<lint-checker> name: reader-prefix-break code: "SIFT007" description: "A newline between a reader prefix and its datum" dialects: all proc: #<procedure reader-prefix-break-warnings (ast source dialect)> severity: warning example: ((input . "'\n(foo)") (fix . "join the prefix to the datum it applies to"))>)
(define parens-checkers
(list unmatched-parens-checker
dangling-paren-checker
reader-prefix-break-checker))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define reader-prefix-break-checker
(checker 'reader-prefix-break
"A newline between a reader prefix and its datum"
'all
reader-prefix-break-warnings
#:severity 'warning
#:example '((input . "'\n(foo)")
(fix . "join the prefix to the datum it applies to"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define unmatched-parens-checker
(checker 'unmatched-parens
"Unbalanced or unmatched parentheses or brackets"
'all
unmatched-parens-warnings
#:severity 'error
#:example '((input . "(define (f x)\n x")
(fix . "no automatic fix; sift never guesses where a `)' goes"))))
Every rule here is about a form that reads as if it were safe and is not quite. A quoted number is a puzzle before it is a bug – the quote does nothing, so why is it there? ‘eq?’ on a number or a string compares identity where the author meant value, and two equal-looking literals are not the same object. A ‘cond’ clause after ‘else’ is code nobody can reach, and a ‘case’ datum listed in two clauses is a branch that never runs. A parameter list longer than a handful is a call nobody writes without looking it up, and a ‘defcustom’ without ‘:type’ is a setting Customize cannot render.
The second group is about a form that says the same thing twice or not quite what it means: an ‘apply’ that builds the list it is about to spread, a ‘let’ whose initializer reaches for a name the same ‘let’ is still binding, a ‘let*’ with nothing to sequence, an ‘append’ of the empty list, and a ‘case’ clause keyed on a string, which ‘eqv?’ cannot match.
All but the first report and stop there. Which comparison an author meant, and what to name the sixth parameter, are decisions; the quote is not, which is why it is the one rule here with a fix.
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define append-nothing-checker
(checker 'append-nothing
"An `append` with the empty list among its arguments"
'(scheme racket elisp cl)
append-nothing-warnings
#:severity 'info
#:example '((input . "(append xs '())")
(fix . "xs"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define apply-of-list-checker
(checker 'apply-of-list
"`apply` of a `list`, or of the empty list, where a call says it once"
'(scheme racket elisp cl)
apply-of-list-warnings
#:severity 'info
#:example '((input . "(apply f 1 (list 2 3))")
(fix . "(f 1 2 3)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define case-literal-datum-checker
(checker 'case-literal-datum
"A `case` datum that `eqv?` cannot decide, such as a string"
'(scheme cl)
case-literal-datum-warnings
#:severity 'warning
#:example '((input . "(case x ((\"a\") 1))")
(fix . "(cond ((string=? x \"a\") 1))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define cond-else-not-last-checker
(checker 'cond-else-not-last
"A `cond` clause after `else`, which can never run"
'(scheme racket elisp cl)
cond-else-not-last-warnings
#:severity 'warning
#:example '((input . "(cond ((a) 1) (else 2) ((b) 3))")
(fix . "(cond ((a) 1) ((b) 3) (else 2))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define defcustom-without-type-checker
(checker 'defcustom-without-type
"A `defcustom` whose value Customize cannot render for lack of `:type`"
'(elisp)
defcustom-without-type-warnings
#:severity 'warning
#:example '((input . "(defcustom sift-thing nil :group 'sift)")
(fix . "(defcustom sift-thing nil :type 'boolean :group 'sift)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define duplicate-case-datum-checker
(checker 'duplicate-case-datum
"A `case` datum matched by an earlier clause"
'(scheme racket elisp cl)
duplicate-case-datum-warnings
#:severity 'warning
#:example '((input . "(case x ((a) 1) ((a b) 2))")
(fix . "(case x ((a) 1) ((b) 2))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define eq-nil-checker
(checker 'eq-nil
"`eq?` or `equal?` against `nil`, where `null` asks the question"
'(scheme racket elisp cl)
eq-nil-warnings
#:severity 'warning
#:example '((input . "(eq? x '())")
(fix . "(null? x)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define eq-on-literal-checker
(checker 'eq-on-literal
"`eq?` asked about a number or a string, where identity is not the question"
'(scheme racket elisp cl)
eq-on-literal-warnings
#:severity 'warning
#:example '((input . "(eq? (length items) 3)")
(fix . "(eqv? (length items) 3)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define let-sibling-checker
(checker 'let-sibling
"A `let` initializer that refers to a name the same `let` binds"
'(scheme racket elisp cl)
let-sibling-warnings
#:severity 'warning
#:example '((input . "(let ((a (f)) (b (g a))) b)")
(fix . "(let* ((a (f)) (b (g a))) b)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define needless-let*-checker
(checker 'needless-let*
"A `let*` none of whose initializers depends on an earlier binding"
'(scheme racket elisp cl)
needless-let*-warnings
#:severity 'info
#:example '((input . "(let* ((a (f)) (b (g))) (+ a b))")
(fix . "(let ((a (f)) (b (g))) (+ a b))"))))
(#<<lint-checker> name: quote-of-constant code: "SIFT054" description: "A quote around a datum that already evaluates to itself" dialects: (scheme racket elisp cl) proc: #<procedure quote-of-constant-warnings (ast source dialect)> severity: info example: ((input . "'5") (fix . "5"))> #<<lint-checker> name: eq-on-literal code: "SIFT055" description: "`eq?` asked about a number or a string, where identity is not the question" dialects: (scheme racket elisp cl) proc: #<procedure eq-on-literal-warnings (ast source dialect)> severity: warning example: ((input . "(eq? (length items) 3)") (fix . "(eqv? (length items) 3)"))> #<<lint-checker> name: cond-else-not-last code: "SIFT056" description: "A `cond` clause after `else`, which can never run" dialects: (scheme racket elisp cl) proc: #<procedure cond-else-not-last-warnings (ast source dialect)> severity: warning example: ((input . "(cond ((a) 1) (else 2) ((b) 3))") (fix . "(cond ((a) 1) ((b) 3) (else 2))"))> #<<lint-checker> name: duplicate-case-datum code: "SIFT057" description: "A `case` datum matched by an earlier clause" dialects: (scheme racket elisp cl) proc: #<procedure duplicate-case-datum-warnings (ast source dialect)> severity: warning example: ((input . "(case x ((a) 1) ((a b) 2))") (fix . "(case x ((a) 1) ((b) 2))"))> #<<lint-checker> name: too-many-arguments code: "SIFT058" description: "A parameter list long enough that a call site has to be looked up" dialects: (scheme racket elisp cl) proc: #<procedure too-many-arguments-warnings (ast source dialect)> severity: info example: ((input . "(define (place x y width height colour outline) ...)") (fix . "(define (place x y area colour) ...)"))> #<<lint-checker> name: defcustom-without-type code: "SIFT059" description: "A `defcustom` whose value Customize cannot render for lack of `:type`" dialects: (elisp) proc: #<procedure defcustom-without-type-warnings (ast source dialect)> severity: warning example: ((input . "(defcustom sift-thing nil :group 'sift)") (fix . "(defcustom sift-thing nil :type 'boolean :group 'sift)"))> #<<lint-checker> name: apply-of-list code: "SIFT064" description: "`apply` of a `list`, or of the empty list, where a call says it once" dialects: (scheme racket elisp cl) proc: #<procedure apply-of-list-warnings (ast source dialect)> severity: info example: ((input . "(apply f 1 (list 2 3))") (fix . "(f 1 2 3)"))> #<<lint-checker> name: let-sibling code: "SIFT065" description: "A `let` initializer that refers to a name the same `let` binds" dialects: (scheme racket elisp cl) proc: #<procedure let-sibling-warnings (ast source dialect)> severity: warning example: ((input . "(let ((a (f)) (b (g a))) b)") (fix . "(let* ((a (f)) (b (g a))) b)"))> #<<lint-checker> name: needless-let* code: "SIFT066" description: "A `let*` none of whose initializers depends on an earlier binding" dialects: (scheme racket elisp cl) proc: #<procedure needless-let*-warnings (ast source dialect)> severity: info example: ((input . "(let* ((a (f)) (b (g))) (+ a b))") (fix . "(let ((a (f)) (b (g))) (+ a b))"))> #<<lint-checker> name: eq-nil code: "SIFT067" description: "`eq?` or `equal?` against `nil`, where `null` asks the question" dialects: (scheme racket elisp cl) proc: #<procedure eq-nil-warnings (ast source dialect)> severity: warning example: ((input . "(eq? x '())") (fix . "(null? x)"))> #<<lint-checker> name: append-nothing code: "SIFT068" description: "An `append` with the empty list among its arguments" dialects: (scheme racket elisp cl) proc: #<procedure append-nothing-warnings (ast source dialect)> severity: info example: ((input . "(append xs '())") (fix . "xs"))> #<<lint-checker> name: case-literal-datum code: "SIFT069" description: "A `case` datum that `eqv?` cannot decide, such as a string" dialects: (scheme cl) proc: #<procedure case-literal-datum-warnings (ast source dialect)> severity: warning example: ((input . "(case x ((\"a\") 1))") (fix . "(cond ((string=? x \"a\") 1))"))>)
(define practices-checkers
(list quote-of-constant-checker
eq-on-literal-checker
cond-else-not-last-checker
duplicate-case-datum-checker
too-many-arguments-checker
defcustom-without-type-checker
apply-of-list-checker
let-sibling-checker
needless-let*-checker
eq-nil-checker
append-nothing-checker
case-literal-datum-checker))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define quote-of-constant-checker
(checker 'quote-of-constant
"A quote around a datum that already evaluates to itself"
'(scheme racket elisp cl)
quote-of-constant-warnings
#:severity 'info
#:example '((input . "'5")
(fix . "5"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define too-many-arguments-checker
(checker 'too-many-arguments
"A parameter list long enough that a call site has to be looked up"
'(scheme racket elisp cl)
too-many-arguments-warnings
#:severity 'info
#:example '((input . "(define (place x y width height colour outline) ...)")
(fix . "(define (place x y area colour) ...)"))))
Checkers for idioms that read one way in Scheme and another in the other two dialects: internal definitions, an ‘if’ that is really a ‘when’, a ‘letrec’ that is really a ‘let’, and a quasiquote that unquotes a constant.
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define clause-brackets-checker
(checker 'clause-brackets
"A `cond` or `case` clause written with the other kind of bracket"
'(scheme racket)
clause-brackets-warnings
#:severity 'warning
#:example '((input . "(cond ((= x 1) 'one)\n (else 'other))")
(fix . "(cond [(= x 1) 'one]\n [else 'other])"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define docstring-texinfo-checker
(checker 'docstring-texinfo
"A Guile docstring that does not document its arguments with `@var{}`"
'(scheme)
docstring-texinfo-warnings
#:severity 'info
#:example '((input . "(define (f x) \"Return X.\" x)")
(fix . "(define (f x) \"Return @var{x}.\" x)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define if-without-else-checker
(checker 'if-without-else
"`if` with no else branch, where `when` expresses the intent"
'(scheme racket)
if-without-else-warnings
#:severity 'warning
#:example '((input . "(if (ready?) (go))")
(fix . "(when (ready?) (go))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define internal-define-checker
(checker 'internal-define
"`define` inside a procedure body, after the first expression"
'(scheme)
internal-define-warnings
#:severity 'warning
#:example '((input . "(define (f)\n (define y 1)\n (if y 2 3))")
(fix . "no automatic fix; use `let' for a local binding"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define letrec-init-reference-checker
(checker 'letrec-init-reference
"A `letrec` initializer that refers to a binding the form has not assigned yet"
'(scheme)
letrec-init-reference-warnings
#:severity 'warning
#:example '((input . "(letrec ((a 1) (b (+ a 1))) b)")
(fix . "(letrec* ((a 1) (b (+ a 1))) b)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define letrec-single-binding-checker
(checker 'letrec-single-binding
"`letrec` with a single binding that does not need recursive scope"
'(scheme racket)
letrec-single-binding-warnings
#:severity 'info
#:example '((input . "(letrec ((x 1)) x)")
(fix . "no automatic fix; `let` expresses the same thing"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define library-not-found-checker
(checker 'library-not-found
"An `import` of a library that neither the file nor the project declares"
'(scheme)
library-not-found-warnings
#:severity 'warning
#:example '((input . "(import (my helpers))\n")
(fix . "no automatic fix; name the library the project declares, or add it"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define quasiquote-dotted-unquote-checker
(checker 'quasiquote-dotted-unquote
"A `(key . ,value)` pair inside a quasiquote, which is the same as `(key unquote value)`"
'(scheme racket)
quasiquote-dotted-unquote-warnings
#:severity 'warning
#:example '((input . "`((key . ,value))")
(fix . "`((key unquote value))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define quasiquote-unquote-constant-checker
(checker 'quasiquote-unquote-constant
"`(quasiquote (unquote constant))` can be simplified"
'(scheme racket)
quasiquote-unquote-constant-warnings
#:severity 'info
#:example '((input . "`(1 ,2)")
(fix . "no automatic fix; write the constant directly"))))
(#<<lint-checker> name: internal-define code: "SIFT011" description: "`define` inside a procedure body, after the first expression" dialects: (scheme) proc: #<procedure internal-define-warnings (ast source dialect)> severity: warning example: ((input . "(define (f)\n (define y 1)\n (if y 2 3))") (fix . "no automatic fix; use `let' for a local binding"))> #<<lint-checker> name: if-without-else code: "SIFT012" description: "`if` with no else branch, where `when` expresses the intent" dialects: (scheme racket) proc: #<procedure if-without-else-warnings (ast source dialect)> severity: warning example: ((input . "(if (ready?) (go))") (fix . "(when (ready?) (go))"))> #<<lint-checker> name: letrec-single-binding code: "SIFT015" description: "`letrec` with a single binding that does not need recursive scope" dialects: (scheme racket) proc: #<procedure letrec-single-binding-warnings (ast source dialect)> severity: info example: ((input . "(letrec ((x 1)) x)") (fix . "no automatic fix; `let` expresses the same thing"))> #<<lint-checker> name: letrec-init-reference code: "SIFT070" description: "A `letrec` initializer that refers to a binding the form has not assigned yet" dialects: (scheme) proc: #<procedure letrec-init-reference-warnings (ast source dialect)> severity: warning example: ((input . "(letrec ((a 1) (b (+ a 1))) b)") (fix . "(letrec* ((a 1) (b (+ a 1))) b)"))> #<<lint-checker> name: quasiquote-unquote-constant code: "SIFT016" description: "`(quasiquote (unquote constant))` can be simplified" dialects: (scheme racket) proc: #<procedure quasiquote-unquote-constant-warnings (ast source dialect)> severity: info example: ((input . "`(1 ,2)") (fix . "no automatic fix; write the constant directly"))> #<<lint-checker> name: quasiquote-dotted-unquote code: "SIFT093" description: "A `(key . ,value)` pair inside a quasiquote, which is the same as `(key unquote value)`" dialects: (scheme racket) proc: #<procedure quasiquote-dotted-unquote-warnings (ast source dialect)> severity: warning example: ((input . "`((key . ,value))") (fix . "`((key unquote value))"))> #<<lint-checker> name: clause-brackets code: "SIFT036" description: "A `cond` or `case` clause written with the other kind of bracket" dialects: (scheme racket) proc: #<procedure clause-brackets-warnings (ast source dialect)> severity: warning example: ((input . "(cond ((= x 1) 'one)\n (else 'other))") (fix . "(cond [(= x 1) 'one]\n [else 'other])"))> #<<lint-checker> name: docstring-texinfo code: "SIFT035" description: "A Guile docstring that does not document its arguments with `@@var@{@}`" dialects: (scheme) proc: #<procedure docstring-texinfo-warnings (ast source dialect)> severity: info example: ((input . "(define (f x) \"Return X.\" x)") (fix . "(define (f x) \"Return @@var@{x@}.\" x)"))> #<<lint-checker> name: unused-binding code: "SIFT039" description: "A binding whose name is never referenced in the form that binds it" dialects: (scheme racket elisp cl) proc: #<procedure unused-binding-warnings (ast source dialect)> severity: warning example: ((input . "(let ((x 1) (y 2)) x)") (fix . "no automatic fix; remove the binding or use it"))> #<<lint-checker> name: unused-import code: "SIFT060" description: "A name or a library an `import` brings in that the file never uses" dialects: (scheme) proc: #<procedure unused-import-warnings (ast source dialect)> severity: info example: ((input . "(import (only (srfi 1) fold car))\n(display (fold + 0 '(1 2)))") (fix . "delete `car` from the `only` clause"))> #<<lint-checker> name: library-not-found code: "SIFT061" description: "An `import` of a library that neither the file nor the project declares" dialects: (scheme) proc: #<procedure library-not-found-warnings (ast source dialect)> severity: warning example: ((input . "(import (my helpers))\n") (fix . "no automatic fix; name the library the project declares, or add it"))> #<<lint-checker> name: unused-definition code: "SIFT062" description: "A definition nothing in the file uses, in a module that does not export it" dialects: (scheme) proc: #<procedure unused-definition-warnings (ast source dialect)> severity: info example: ((input . "(define-module (demo)\n #:export (used))\n\n(define (used) 1)\n(define (forgotten) 2)\n") (fix . "delete it, or export it if another module is meant to call it"))>)
(define scheme-checkers
(list internal-define-checker
if-without-else-checker
letrec-single-binding-checker
letrec-init-reference-checker
quasiquote-unquote-constant-checker
quasiquote-dotted-unquote-checker
clause-brackets-checker
docstring-texinfo-checker
unused-binding-checker
unused-import-checker
library-not-found-checker
unused-definition-checker))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define unused-binding-checker
(checker 'unused-binding
"A binding whose name is never referenced in the form that binds it"
'(scheme racket elisp cl)
unused-binding-warnings
#:severity 'warning
#:example '((input . "(let ((x 1) (y 2)) x)")
(fix . "no automatic fix; remove the binding or use it"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define unused-definition-checker
(checker 'unused-definition
"A definition nothing in the file uses, in a module that does not export it"
'(scheme)
unused-definition-warnings
#:severity 'info
#:example '((input . "(define-module (demo)\n #:export (used))\n\n(define (used) 1)\n(define (forgotten) 2)\n")
(fix . "delete it, or export it if another module is meant to call it"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define unused-import-checker
(checker 'unused-import
"A name or a library an `import` brings in that the file never uses"
'(scheme)
unused-import-warnings
#:severity 'info
#:example '((input . "(import (only (srfi 1) fold car))
(display (fold + 0 '(1 2)))")
(fix . "delete `car` from the `only` clause"))))
A Lisp rewards writing the same meaning in fewer parentheses, and the shapes below are the ones where the shorter form is not a matter of taste: ‘(lambda (x) (f x))’ *is* ‘f’, ‘((lambda (x) body) arg)’ *is* a ‘let’, and ‘(let ((x e)) x)’ *is* ‘e’. The rules say so, and each of them has a fix that writes the short form.
What none of them does is guess. Every condition that would make the rewrite wrong is checked before the warning is reported: the formals are one plain symbol, the call passes exactly that symbol and nothing else, the operator is a procedure rather than a special form or a macro, the binding is not shadowed. A simplification rule that is wrong once is a rule the author turns off and never turns back on.
The readers of the four dialects are the same here, the writers are not: ‘(lambda (x) (f x))’ is a function in Scheme and in Emacs Lisp but not in Common Lisp, where a function is written ‘#’f’ and a bare lambda is not even read; and ‘compose’ is Guile’s, so it is suggested in Scheme only. Racket is in between: the rewrite holds there, but ‘compose’ comes from ‘racket/function’, so the fix names a binding the file may not require – which is the same caveat Guile’s own ‘compose’ carries, and why the rule suggests rather than rewrites.
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define beta-reduction-checker
(checker 'beta-reduction
"A lambda applied in place, where a `let` would say the same thing once"
'(scheme racket elisp cl)
beta-reduction-warnings
#:severity 'info
#:example '((input . "((lambda (x) (f x)) (g))")
(fix . "(let ((x (g))) (f x))"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define composition-checker
(checker 'composition
"A lambda whose body is one call around another, where `compose` names the pipeline"
'(scheme racket)
composition-warnings
#:severity 'info
#:example '((input . "(lambda (x) (f (g x)))")
(fix . "(compose f g)"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define eta-reduction-checker
(checker 'eta-reduction
"A lambda that only passes its argument on, where the procedure itself would do"
'(scheme racket)
eta-reduction-warnings
#:severity 'info
#:example '((input . "(lambda (x) (f x))")
(fix . "f"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define let-simplification-checker
(checker 'let-simplification
"A `let` that binds a name to return it, binds nothing, or binds once with `let*`"
'all
let-simplification-warnings
#:severity 'info
#:example '((input . "(let ((x (f))) x)")
(fix . "(f)"))))
(#<<lint-checker> name: eta-reduction code: "SIFT045" description: "A lambda that only passes its argument on, where the procedure itself would do" dialects: (scheme racket) proc: #<procedure eta-reduction-warnings (ast source dialect)> severity: info example: ((input . "(lambda (x) (f x))") (fix . "f"))> #<<lint-checker> name: beta-reduction code: "SIFT046" description: "A lambda applied in place, where a `let` would say the same thing once" dialects: (scheme racket elisp cl) proc: #<procedure beta-reduction-warnings (ast source dialect)> severity: info example: ((input . "((lambda (x) (f x)) (g))") (fix . "(let ((x (g))) (f x))"))> #<<lint-checker> name: composition code: "SIFT047" description: "A lambda whose body is one call around another, where `compose` names the pipeline" dialects: (scheme racket) proc: #<procedure composition-warnings (ast source dialect)> severity: info example: ((input . "(lambda (x) (f (g x)))") (fix . "(compose f g)"))> #<<lint-checker> name: let-simplification code: "SIFT048" description: "A `let` that binds a name to return it, binds nothing, or binds once with `let*`" dialects: all proc: #<procedure let-simplification-warnings (ast source dialect)> severity: info example: ((input . "(let ((x (f))) x)") (fix . "(f)"))>)
(define simplify-checkers
(list eta-reduction-checker
beta-reduction-checker
composition-checker
let-simplification-checker))
SXML is Lisp used as markup: ‘(element (@ (attribute "value")) child ...)’. A formatter does not need to know that – an element is a list and formats as one, and the attribute list, being the first argument, lines up under itself the way every call does – but a linter can say the three things the shape itself cannot:
the attribute list belongs first, and there is one of it a child is an element, a string or a number, not a list of them an element with attributes and no children is a tag that will not close
All three are about documents, so none of them fires on ordinary code. The test for "is this a document" is the attribute list itself: a list whose head is a symbol and that holds an ‘(@ ...)’ child is an element, and nothing else is. That is the one piece of evidence a file carries, and it is enough – a function called ‘div’ that takes an ‘@’ list is not something anyone writes by accident.
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define sxml-attributes-checker
(checker 'sxml-attributes
"An element's `(@ ...)` list is missing, repeated, empty, or not the first child"
'(scheme)
sxml-attributes-warnings
#:severity 'warning
#:example '((input . "(div (p \"a\") (@ (class \"x\")))")
(fix . "no automatic fix; markup is moved by the author, not by a formatter"))))
(#<<lint-checker> name: sxml-attributes code: "SIFT049" description: "An element's `(@@ ...)` list is missing, repeated, empty, or not the first child" dialects: (scheme) proc: #<procedure sxml-attributes-warnings (ast source dialect)> severity: warning example: ((input . "(div (p \"a\") (@@ (class \"x\")))") (fix . "no automatic fix; markup is moved by the author, not by a formatter"))> #<<lint-checker> name: sxml-child code: "SIFT050" description: "A child of an element that is a list of children rather than a child" dialects: (scheme) proc: #<procedure sxml-child-warnings (ast source dialect)> severity: warning example: ((input . "(ul (((@@ (class \"x\"))) (li \"a\")))") (fix . "no automatic fix; the missing element name is the author's to supply"))> #<<lint-checker> name: sxml-empty-element code: "SIFT063" description: "An element with attributes and no children, which serializes as a self-closing tag" dialects: (scheme) proc: #<procedure sxml-empty-element-warnings (ast source dialect)> severity: warning example: ((input . "(div (@@ (class \"card\")))") (fix . "(div (@@ (class \"card\")) \"\")"))>)
(define sxml-checkers
(list sxml-attributes-checker
sxml-child-checker
sxml-empty-element-checker))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define sxml-child-checker
(checker 'sxml-child
"A child of an element that is a list of children rather than a child"
'(scheme)
sxml-child-warnings
#:severity 'warning
#:example '((input . "(ul (((@ (class \"x\"))) (li \"a\")))")
(fix . "no automatic fix; the missing element name is the author's to supply"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define sxml-empty-element-checker
(checker 'sxml-empty-element
"An element with attributes and no children, which serializes as a self-closing tag"
'(scheme)
sxml-empty-element-warnings
#:severity 'warning
#:example '((input . "(div (@ (class \"card\")))")
(fix . "(div (@ (class \"card\")) \"\")"))))
The four checkers that look at the shape of a line rather than at the shape of a form: trailing whitespace, tabs used for indentation, lines over the soft limit, and blank lines piled up at the end of a file.
Everything here works on the source text directly, because that is what the question is about. A tab inside a string is data and a line that begins inside a block comment is not indentation, so both are excluded using the ranges the reader recorded for those nodes.
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define blank-line-in-body-checker
(checker 'blank-line-in-body
"A blank line in the middle of a body, where one paragraph belongs"
'all
blank-line-in-body-warnings
#:severity 'info
#:example '((input . "(define (f x)
(first x)
(second x))
")
(fix . "delete the blank line, or split the form in two"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define line-length-checker
(checker 'line-length
"Line exceeds the configured soft limit (96 columns, 80 in Emacs Lisp)"
'all
line-length-warnings
#:severity 'warning
#:example '((input . "(define (f x) (some-very-long-call ...)) ; over 96 columns")
(fix . "no automatic fix; break the form by hand"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define tabs-checker
(checker 'tabs
"Tab characters used for indentation"
'all
tabs-warnings
#:severity 'warning
#:example '((input . "(define (f x)\n\tx)")
(fix . "replace the tab with spaces at the indent width"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define trailing-blank-lines-checker
(checker 'trailing-blank-lines
"More than two consecutive blank lines at end of file"
'all
trailing-blank-lines-warnings
#:severity 'info
#:example '((input . "(define x 1)\n\n\n\n\n")
(fix . "trim the end of the file to one blank line"))))
This is a record of the type <lint-checker>, with 7 fields:
name, code, description, dialects,
proc, severity, example.
(define trailing-whitespace-checker
(checker 'trailing-whitespace
"Lines ending with spaces or tabs"
'all
trailing-whitespace-warnings
#:severity 'warning
#:example '((input . "(define (f x) \n x)")
(fix . "strip the trailing whitespace"))))
(#<<lint-checker> name: trailing-whitespace code: "SIFT001" description: "Lines ending with spaces or tabs" dialects: all proc: #<procedure trailing-whitespace-warnings (ast source dialect)> severity: warning example: ((input . "(define (f x) \n x)") (fix . "strip the trailing whitespace"))> #<<lint-checker> name: tabs code: "SIFT002" description: "Tab characters used for indentation" dialects: all proc: #<procedure tabs-warnings (ast source dialect)> severity: warning example: ((input . "(define (f x)\n\tx)") (fix . "replace the tab with spaces at the indent width"))> #<<lint-checker> name: line-length code: "SIFT003" description: "Line exceeds the configured soft limit (96 columns, 80 in Emacs Lisp)" dialects: all proc: #<procedure line-length-warnings (ast source dialect)> severity: warning example: ((input . "(define (f x) (some-very-long-call ...)) ; over 96 columns") (fix . "no automatic fix; break the form by hand"))> #<<lint-checker> name: trailing-blank-lines code: "SIFT010" description: "More than two consecutive blank lines at end of file" dialects: all proc: #<procedure trailing-blank-lines-warnings (ast source dialect)> severity: info example: ((input . "(define x 1)\n\n\n\n\n") (fix . "trim the end of the file to one blank line"))> #<<lint-checker> name: blank-line-in-body code: "SIFT052" description: "A blank line in the middle of a body, where one paragraph belongs" dialects: all proc: #<procedure blank-line-in-body-warnings (ast source dialect)> severity: info example: ((input . "(define (f x)\n (first x)\n\n (second x))\n") (fix . "delete the blank line, or split the form in two"))>)
(define whitespace-checkers
(list trailing-whitespace-checker
tabs-checker
line-length-checker
trailing-blank-lines-checker
blank-line-in-body-checker))
The command line is parsed with SRFI-37 ‘args-fold’, which is what makes abbreviated long options and a ‘–’ that stops parsing work the way a Unix user expects, without the bookkeeping ‘getopt-long’ needs for optional arguments.
Two promises are kept here and nowhere else:
* nothing is written to disk unless ‘–write’ asks for it, and * the exit status is 0 for clean, 1 for findings or formatting differences, and 2 for a usage error, an unreadable file or a file that cannot be parsed at all.
The status is the same whether the run is a person typing or a Makefile calling, which is what makes sift usable in CI and in an editor’s format-on-save hook without special cases.
Return the alist of settings the command line overrides.
Invalid values are usage errors, not silent fallbacks: a ‘–line-length’ of ‘abc’ means the run is wrong, and saying so is the only useful answer.
(define* (build-overrides state)
"Return the alist of settings the command line overrides.
Invalid values are usage errors, not silent fallbacks: a `--line-length' of
`abc' means the run is wrong, and saying so is the only useful answer."
(define (read-option key reader)
(let ((given (assq-ref state key)))
(and given (cons key (reader given)))))
(filter identity
(append
(map (lambda (entry) (read-option (car entry) (cdr entry)))
option-readers)
(map (lambda (key) (and (assq key state) (cons key #t))) option-flags)
(list (read-option 'color string->symbol)
(checker-override state 'checkers "--checker")
(checker-override state 'exclude-checkers "--exclude-checker")
(file-filter-override state)))))
Turn directory operands into the Lisp files they hold, in sorted order.
A linter is pointed at a project, not at a list: ‘sift ci .‘ and ‘sift format –write src/‘ are what people type, so a directory is read as "every Lisp file under here".
patterns is the project’s ‘file-filter’. It decides what a *directory* holds and never what a person named: ‘sift lint notes.txt’ reads the file it was given, because naming a file is the most specific thing anyone can say.
(define* (expand-operands files #:optional (patterns #f))
"Turn directory operands into the Lisp files they hold, in sorted order.
A linter is pointed at a project, not at a list: `sift ci .` and
`sift format --write src/` are what people type, so a directory is read as
\"every Lisp file under here\".
@var{patterns} is the project's `file-filter'. It decides what a *directory*
holds and never what a person named: `sift lint notes.txt' reads the file it
was given, because naming a file is the most specific thing anyone can say."
(append-map
(lambda (path)
(cond
[(not (file-exists? path)) (list path)]
[(eq? (stat:type (stat path)) 'directory)
(directory-files* path patterns)]
[else (list path)]))
files))
Parse args and return state, the alist of what was said.
The operands are in it, in the order they were written. A ‘–’ stops option parsing, so a file whose name begins with a dash can still be named.
‘–stdin’ is checked here rather than in each command, because "at most one file may be named beside it" is a property of the flag and not of what the command does with the source: a second operand would be silently ignored, and a label that stands for nothing is exactly the kind of quiet lie the rest of this program refuses to tell.
(define* (parse-options args)
"Parse @var{args} and return @var{state}, the alist of what was said.
The operands are in it, in the order they were written. A `--' stops option
parsing, so a file whose name begins with a dash can still be named.
`--stdin' is checked here rather than in each command, because \"at most one
file may be named beside it\" is a property of the flag and not of what the
command does with the source: a second operand would be silently ignored, and
a label that stands for nothing is exactly the kind of quiet lie the rest of
this program refuses to tell."
(let* ((state (args-fold (normalise-long-options args)
option-specification
(lambda (opt name arg state)
(usage-error "unrecognized option `~a'" name)
state)
(lambda (operand state) (acons 'operand operand state))
'()))
(files (filter-map (lambda (entry)
(and (eq? (car entry) 'operand) (cdr entry)))
state)))
(when (and (assq 'stdin state) (> (length files) 1))
(usage-error "--stdin reads one source; at most one file may be named, as a label"))
state))
Run sift with args and return the exit status.
The status is the contract: 0 clean, 1 findings or differences, 2 usage error, unreadable file, or a file that cannot be parsed. A run with ‘–watch’ does not return one, because it does not return: it repeats until the process is interrupted, and Ctrl-C is how an editor-style watch is meant to end.
(define* (sift-main args)
"Run sift with @var{args} and return the exit status.
The status is the contract: 0 clean, 1 findings or differences, 2 usage
error, unreadable file, or a file that cannot be parsed. A run with `--watch'
does not return one, because it does not return: it repeats until the process
is interrupted, and Ctrl-C is how an editor-style watch is meant to end."
(catch 'sift-usage-error
(lambda () (dispatch-once-or-watch args))
(lambda (key message)
(format (current-error-port) "sift: ~a~%" message)
(format (current-error-port) "~a" usage-text)
2)))
"1.40.2"
The value is a string of 965 characters, too long to print here.
(define usage-text "Usage: sift format [OPTIONS] [FILE...] sift lint [OPTIONS] [FILE...] sift check [OPTIONS] [FILE...] sift fix [OPTIONS] [FILE...] # lint --fix sift ci [OPTIONS] [FILE-OR-DIR...] # format check + lint; exits 1 if either fails sift install-hooks [--force] # a pre-commit hook that runs `sift ci` sift doctor # what ran, what it read, what it decided sift lsp # a language server on stdin and stdout sift list-checkers [--dialect DIALECT] sift explain CHECKER-NAME sift config show|explain|trust ... sift version Options common to the commands: --dialect, --brackets, --blank-lines, --line-length, --style, --severity, --format, --color/--no-color, --file-filter/-p, --verbose, --config, --watch. `--watch' re-runs format, lint, check, fix or ci whenever the files the run read change, until the process is interrupted. Run `sift COMMAND --help' for the options of a command. ")
The reader in ‘(sift reader)’ is a reader, not a compiler: it knows the shape of a form and nothing about the names inside it. The implementation a project already uses knows a great deal more – an undefined variable, a call with the wrong number of arguments, a macro that is not known, a type that cannot hold the value – and it says so in a form a human has read for decades. This module asks it, once per file, and turns the answer into something a language server can publish.
The compilers are run on a *temporary* copy of the text, never on the file in the project: a server that compiled ‘foo.go’ or ‘foo.elc’ beside the source would be a server that writes into the tree it is judging. Each implementation is asked in its own words, its output on standard error is captured with standard output, and a small parser per implementation turns the lines it prints into diagnostics.
Nothing here is on the request path. A compile is a process, a process is slower than a keystroke, and the answer is published as a later report for the version it was computed from. A compiler that is not installed is not an error: the answer is an empty list, and the rest of the server answers exactly as it did before.
The limits are the ones a background job needs: the output is bounded, the temporary files are removed, and a compiler that hangs is left to the process table rather than to the editor. ‘shortcut: no hard timeout, a compiler that hangs holds a thread until the session ends; add a watchdog when a real implementation is found hanging.’
#t when dialect’s compiler is on PATH.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Return the diagnostics dialect’s compiler makes about text.
file is the name the text has in the project, when it has one; its directory and root are put on the compiler’s load path so that a project whose modules live under ~src/~ can be compiled from anywhere. The text is written to a temporary file and removed afterwards: nothing is written into the project, and an unsaved buffer is compiled as it is.
A compiler that is not installed, or that fails before printing anything, is an empty list of findings. The caller already has a smaller answer for that case.
(define* (compile-text text #:key (dialect 'scheme) (file #f) (root #f))
"Return the diagnostics @var{dialect}'s compiler makes about @var{text}.
@var{file} is the name the text has in the project, when it has one; its
directory and @var{root} are put on the compiler's load path so that a project
whose modules live under ~src/~ can be compiled from anywhere. The text is
written to a temporary file and removed afterwards: nothing is written into
the project, and an unsaved buffer is compiled as it is.
A compiler that is not installed, or that fails before printing anything, is
an empty list of findings. The caller already has a smaller answer for that
case."
(let ((program (assq-ref dialect-program dialect))
(extension (assq-ref dialect-extension dialect)))
(if (not (and program extension text))
'()
(let* ((source (temporary-path dialect))
(output (temporary-path dialect))
(load-paths (delete-duplicates
(filter (lambda (path)
(and path (not (string-null? path))
(file-exists? path)))
(append (if file (list (dirname file)) '())
(if root (list root) '())
(if root
(list (string-append root "/src"))
'())))
string=?)))
(dynamic-wind
(lambda ()
(false-if-exception
(call-with-output-file source (lambda (port) (display text port)))))
(lambda ()
(let ((command (compiler-command dialect source output load-paths)))
(if (not command)
'()
(let ((printed (run-program (car command) (cdr command))))
(case dialect
[(scheme) (parse-guile-diagnostics printed)]
[(elisp) (parse-emacs-diagnostics printed)]
[(cl) (parse-sbcl-diagnostics printed text)]
[else '()])))))
(lambda ()
(false-if-exception (delete-file source))
(false-if-exception (delete-file output))))))))
Return #t when dialect’s compiler is on PATH.
(define* (compiler-available? dialect)
"Return @code{#t} when @var{dialect}'s compiler is on @code{PATH}."
(let ((program (assq-ref dialect-program dialect)))
(and program
(let ((path (getenv "PATH")))
(and path
(any (lambda (directory)
(file-exists? (string-append directory "/" program)))
(string-split path #\:)))))))
Return the diagnostics output holds, in the order it printed them.
(define (parse-emacs-diagnostics output)
"Return the diagnostics @var{output} holds, in the order it printed them."
(filter-map emacs-diagnostic (string-split output #\newline)))
Return the diagnostics output holds, in the order it printed them.
(define (parse-guile-diagnostics output)
"Return the diagnostics @var{output} holds, in the order it printed them."
(filter-map guile-diagnostic (string-split output #\newline)))
Return the diagnostics output describes about text.
(define (parse-sbcl-diagnostics output text)
"Return the diagnostics @var{output} describes about @var{text}."
(let loop ((lines (string-split output #\newline))
(severity #f)
(message '())
(form #f)
(snippet '())
(found '()))
(define (finish found)
(if (not severity)
found
(let* ((line (if form (car form) 0))
(column (if form (cdr form) 0))
(position (if form
(cons line column)
(position-of-snippet text (string-join (reverse snippet) " ")))))
(cons (make-compiler-diagnostic 'sbcl severity
(string-join (reverse message) " ")
(car position) (cdr position)
(car position) (+ (cdr position) 1))
found))))
(cond
[(null? lines) (reverse (finish found))]
[else
(let ((line (car lines)))
(cond
[(regexp-exec sbcl-caught line)
(let* ((match (regexp-exec sbcl-caught line))
(found (finish found)))
(loop (cdr lines)
(sbcl-severity (match:substring match 1))
'() #f snippet found))]
[(and (not severity) (string-prefix? "; " line))
(loop (cdr lines) severity message form
(cons (string-trim (substring line 6)) snippet) found)]
[(regexp-exec sbcl-form-position line)
(let ((match (regexp-exec sbcl-form-position line)))
(loop (cdr lines) severity message
(cons (- (string->number (match:substring match 1)) 1)
(string->number (match:substring match 2)))
snippet found))]
[(string-prefix? "; " line)
(loop (cdr lines) severity
(cons (string-trim (substring line 4)) message)
form snippet found)]
[(or (string-prefix? "; compilation" line)
(string-prefix? "; wrote" line)
(string-prefix? "; compiling" line))
(loop (cdr lines) #f '() #f '() (finish found))]
[else (loop (cdr lines) severity message form snippet found)]))])))
Three numbers describe one definition, because each answers a different question and no single one is enough:
score cognitive complexity: every decision costs one, and a decision nested inside another costs one more. This is the number that says "this takes effort to read". cycles cyclomatic complexity: one plus the number of decisions. This is the number that says "how many paths a test would have to cover". lines the length of the definition. This is the number that says "how far the reader has to scroll to see the whole thing".
Plus the deepest nesting of decisions, which is what ‘nesting-depth’ in the linter reports one form at a time.
The measurement lives here rather than in any one of the callers because ‘maak complexity’ prints the ranking and two rules report a definition one at a time; a report and a rule that computed the numbers separately would disagree about the same function, and the reader would have no way to tell which one was right.
It reads the tree sift’s reader produced, so a comment, a string, a datum comment and a quoted datum are never mistaken for code – an ‘(if ...)’ in a docstring or in a pattern is not a branch.
#t when node is a form that defines a name.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Return #t when node is a form that defines a name.
(define (complexity-definition? node)
"Return @code{#t} when @var{node} is a form that defines a name."
(and (node-list? node) (definition-head? node) #t))
Return the measurement of node, a definition form.
A definition nested inside node – a closure returned from a factory, a local helper – is skipped rather than counted twice: it is its own unit of reading, and folding it into its parent would make a factory look as costly as the function it builds. A quoted datum is skipped for the same reason a string is: it is data the program carries, not a branch it takes.
(define (complexity-of node)
"Return the measurement of @var{node}, a definition form.
A definition nested inside @var{node} -- a closure returned from a factory,
a local helper -- is skipped rather than counted twice: it is its own unit
of reading, and folding it into its parent would make a factory look as
costly as the function it builds. A quoted datum is skipped for the same
reason a string is: it is data the program carries, not a branch it takes."
(let ((decisions 0)
(score 0)
(deepest 0)
(data 0))
(define (walk inner nesting)
(unless (or (node-trivia? inner) (node-commented-out? inner))
(set! data (+ data 1))
(let ((branching (and (decision? inner) #t))
(next (if (decision? inner) (+ nesting 1) nesting)))
(when branching
(set! decisions (+ decisions 1))
(set! score (+ score 1 nesting))
(set! deepest (max deepest (+ nesting 1))))
(cond
[(quoted-datum? inner) #f]
[(node-list? inner)
(for-each
(lambda (child)
(unless (definition-head? child) (walk child next)))
(node-elements inner))]
[(node-prefix? inner)
(let ((child (node-child inner)))
(when (and child (not (node-datum-comment? inner)))
(walk child next)))]
[(node-conditional? inner)
(for-each (lambda (part) (when part (walk part next)))
(list (node-feature inner) (node-guarded-form inner)))]))))
(walk node 0)
(make-complexity score
(+ decisions 1)
deepest
(+ 1 (- (source-location-line (node-end node))
(source-location-line (node-start node))))
data
(source-location-line (node-start node))
(definition-name node))))
Configuration is merged from four layers, and a layer further down the list always wins:
defaults < system ($(prefix)/etc/sift) < user ($XDG_CONFIG_HOME) < project (sift.yaml, sift.scm) < command line
Two formats load into the same <config> record. YAML is data: it is read, validated and can never run anything, which is why it is the format to check in. Scheme is code: it is evaluated, so it can register an indent rule for a project’s own macros and read an environment variable – and so it is only loaded when the user has said the file is trusted (see ‘trusted-config-file?’). Neither format is privileged: ‘config show’ renders the effective result in either.
Unknown keys are errors rather than warnings. A typo in ‘line-length’ that is silently ignored is a setting the user believes is in effect.
Every value remembers where it came from, which is what ‘config show –source’ prints.
#t for either kind of configuration error.
#t when sift may evaluate the Scheme file at path.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Return the effective settings in schema order, one entry per key.
(define (config->alist config)
"Return the effective settings in schema order, one entry per key."
(map (lambda (entry) (cons (car entry) (config-ref config (car entry))))
config-keys))
Return the default configuration as a <config>.
(define (config-defaults)
"Return the default configuration as a <config>."
(make-config (map (lambda (entry) (cons (car entry) (assq-ref (cdr entry) 'default)))
config-keys)
(map (lambda (entry) (cons (car entry) "default"))
config-keys)))
Render a configuration error as file:line:column: message.
A setting that did not come from a file – one the editor sent with ‘workspace/didChangeConfiguration’ – has no line and column to name, and its message is the whole of what can be said about it.
(define (config-error->string error)
"Render a configuration error as file:line:column: message.
A setting that did not come from a file -- one the editor sent with
`workspace/didChangeConfiguration' -- has no line and column to name, and its
message is the whole of what can be said about it."
(cond
[(yaml-error? error)
(format #f "~a:~a:~a: ~a"
(yaml-error-path error) (yaml-error-line error)
(yaml-error-column error) (yaml-error-message error))]
[(config-error-object? error)
(if (config-error-path error)
(format #f "~a:~a:~a: ~a"
(config-error-path error) (config-error-line error)
(config-error-column error) (config-error-message error))
(config-error-message error))]
[else (format #f "~a" error)]))
Return #t for either kind of configuration error.
A YAML file fails in the parser and a Scheme or merged file fails in the validator; the caller reports both the same way.
(define (config-error? thing)
"Return @code{#t} for either kind of configuration error.
A YAML file fails in the parser and a Scheme or merged file fails in the
validator; the caller reports both the same way."
(or (config-error-object? thing) (yaml-error? thing)))
Explain one configuration key: what it does, its default and its flag.
(define* (config-explain key #:key (port (current-output-port)))
"Explain one configuration key: what it does, its default and its flag."
(let ((key (if (symbol? key) key (string->symbol key)))
(doc (config-key-doc (if (symbol? key) key (string->symbol key)))))
(when doc
(begin
(format port "~a~%" key)
(format port " ~a~%" (assq-ref doc 'description))
(format port " type: ~a~%" (assq-ref doc 'type))
(format port " default: ~s~%" (assq-ref doc 'default))
(format port " flag: ~a~%"
(or (assq-ref doc 'flag) "none (config-only)"))
#t))))
Undocumented procedure.
(define (config-key-documented? key) (and (assq key config-keys) #t))
Return where each effective setting came from, in schema order.
(define* (config-provenance->alist config)
"Return where each effective setting came from, in schema order."
(map (lambda (entry)
(cons (car entry) (or (assq-ref (config-provenance config)
(car entry))
"default")))
config-keys))
Return the configured value of key, or default.
(define* (config-ref config key #:optional (default #f))
"Return the configured value of @var{key}, or @var{default}."
(let ((cell (assq key (config-values config))))
(if cell (cdr cell) default)))
Return config with key set to value.
The new value replaces any earlier one for the same key, so the alist holds one entry per key and ‘config-ref’ always answers with the winning layer.
(define (config-set config key value provenance)
"Return @var{config} with @var{key} set to @var{value}.
The new value replaces any earlier one for the same key, so the alist holds
one entry per key and `config-ref' always answers with the winning layer."
(make-config (acons key value
(filter (lambda (entry) (not (eq? (car entry) key)))
(config-values config)))
(acons key provenance
(filter (lambda (entry) (not (eq? (car entry) key)))
(config-provenance config)))))
Write the effective configuration in format, with provenance.
With source?, every value is followed by where it came from, which is the question a user actually has when a setting does not do what they expect.
(define* (config-show config #:key (output-format 'yaml) (source? #f)
(port (current-output-port)))
"Write the effective configuration in @var{format}, with provenance.
With @var{source?}, every value is followed by where it came from, which is
the question a user actually has when a setting does not do what they
expect."
(case output-format
[(scheme)
(display "(\n" port)
(for-each
(lambda (entry)
(let ((key (car entry)) (value (cdr entry)))
(format port " (~a . ~s)" key value)
(if source?
(format port " ; ~a~%"
(assq-ref (config-provenance->alist config) key))
(newline port))))
(config->alist config))
(display ")\n" port)]
[else
(for-each
(lambda (entry)
(let ((key (car entry)) (value (cdr entry)))
(format port "~a: " key)
(cond [(eq? value #t) (display "true" port)]
[(eq? value #f) (display "false" port)]
[(null? value) (display "[]" port)]
[(list? value)
(format port "[~a]" (string-join (map (lambda (item)
(format #f "~a" item))
value)
", "))]
[else (format port "~a" value)])
(when source?
(format port " # ~a"
(assq-ref (config-provenance->alist config) key)))
(newline port)))
(config->alist config))
(when source?
(newline port)
(format port "# provenance: defaults < system < user < project < command line~%"))]))
Return the configuration files in effect, lowest precedence first.
The project file is the nearest one walking up from cwd, and the walk stops at the repository root: a ‘sift.yaml’ in the parent of a checkout belongs to a different project and must not be applied to this one.
(define* (discover-config-files #:key (cwd (getcwd)))
"Return the configuration files in effect, lowest precedence first.
The project file is the nearest one walking up from @var{cwd}, and the walk
stops at the repository root: a `sift.yaml' in the parent of a checkout
belongs to a different project and must not be applied to this one."
(let* ((system (find (lambda (path) (file-exists? path))
'("/etc/sift/config.yaml" "/etc/sift/config.yml"
"/etc/sift/config.scm")))
(user (existing-config-in
(string-append (user-config-directory) "/sift")))
(root (repository-root cwd))
(project
(let loop ((directory (string-trim-right cwd #\/)))
(cond
[(not directory) #f]
[(string-null? directory) #f]
;; `=>' keeps the value the test produced without giving the
;; clause a body that would just be the test again
[(existing-config-in directory) => identity]
[(and root (string=? directory root)) #f]
[else (loop (parent-directory directory))]))))
(filter identity
(list (and system (cons 'system system))
(and user (cons 'user user))
(and project (cons 'project project))))))
Return the alist the checkers and the formatter read their knobs from.
(define* (effective-options config)
"Return the alist the checkers and the formatter read their knobs from."
(list (cons 'line-length (config-ref config 'line-length))
(cons 'indent (config-ref config 'indent))
(cons 'loop-keywords (config-ref config 'loop-keywords))
(cons 'indent-rules (config-ref config 'indent-rules))
(cons 'brackets (config-ref config 'brackets))
(cons 'blank-lines (config-ref config 'blank-lines))
(cons 'single-letter-names (config-ref config 'single-letter-names))
(cons 'field-macros (config-ref config 'field-macros))
(cons 'max-depth (config-ref config 'max-depth))
(cons 'max-elements (config-ref config 'max-elements))
(cons 'max-positional (config-ref config 'max-positional))
(cons 'max-definition-depth (config-ref config 'max-definition-depth))
(cons 'max-cognitive-complexity (config-ref config 'max-cognitive-complexity))
(cons 'max-cyclomatic-complexity (config-ref config 'max-cyclomatic-complexity))))
Return the effective <config>, and the layers it was built from.
cli is an alist of options given on the command line; those win over every file. A config-file named explicitly replaces discovery, which is what a caller who says ‘–config’ means.
(define* (load-config #:key (cwd (getcwd)) (cli '()) (config-file #f)
(trust #f))
"Return the effective <config>, and the layers it was built from.
@var{cli} is an alist of options given on the command line; those win over
every file. A @var{config-file} named explicitly replaces discovery, which
is what a caller who says `--config' means."
(let* ((layers (if config-file
(list (cons 'explicit config-file))
(discover-config-files #:cwd cwd)))
(config (config-defaults))
(loaded '()))
(for-each
(lambda (layer)
(let* ((kind (car layer))
(path (cdr layer))
(settings (load-config-file path
#:explicit (memq kind
'(explicit)))))
(set! loaded (append loaded (list (cons kind path))))
(for-each (lambda (setting)
(set! config
(config-set config (car setting) (cdr setting)
path)))
settings)))
layers)
(for-each (lambda (setting)
(set! config
(config-set config (car setting) (cdr setting)
(format #f "command line (~a)"
(or (assq-ref (config-key-doc (car setting)) 'flag)
"option")))))
cli)
(values config loaded)))
Load path, returning a list of (key . value) settings.
A path that does not exist is not an error here: discovery hands over only files that do.
(define* (load-config-file path #:key (explicit #f))
"Load @var{path}, returning a list of @code{(key . value)} settings.
A path that does not exist is not an error here: discovery hands over only
files that do."
(if (scheme-config? path)
(if (trusted-config-file? path #:explicit explicit)
(load-scheme-config path)
(raise-config-error path 1 1
(string-append
(format #f "~a is a Scheme config file, which runs code, " path)
(format #f "and it is not trusted; run `sift config trust ~a'"
path))))
(load-yaml-config path)))
Undocumented procedure.
(define (scheme-config? path) (string-suffix? ".scm" path))
Record path’s directory as trusted, so its Scheme config may run.
(define* (trust-config-file! path #:key (port (current-output-port)))
"Record @var{path}'s directory as trusted, so its Scheme config may run."
(let* ((absolute (if (string-prefix? "/" path)
path
(string-append (getcwd) "/" path)))
(directory (dirname absolute))
(known (trusted-projects)))
(unless (member directory known)
(let ((target (trust-file-path)))
(make-directories (dirname target))
(call-with-output-file target
(lambda (out)
(for-each (lambda (line) (display line out) (newline out))
(cons directory known))))))
(format port "trusted ~a~%" directory)))
Return #t when sift may evaluate the Scheme file at path.
Three things can make a Scheme configuration trusted, in order: the user
named the file with ‘–config’; the environment says so for this run
(SIFT_TRUST_CONFIG=1); or its directory is listed in
~/.config/sift/trusted-projects, which is what ‘sift config
trust’ writes. A YAML file is always trusted, because reading data runs
nothing.
(define* (trusted-config-file? path #:key (explicit #f))
"Return @code{#t} when sift may evaluate the Scheme file at @var{path}.
Three things can make a Scheme configuration trusted, in order: the user
named the file with `--config'; the environment says so for this run
(SIFT_TRUST_CONFIG=1); or its directory is listed in
@code{~/.config/sift/trusted-projects}, which is what `sift config trust'
writes. A YAML file is always trusted, because reading data runs nothing."
(or explicit
(equal? (getenv "SIFT_TRUST_CONFIG") "1")
(let ((directory (dirname (if (string-prefix? "/" path)
path
(string-append (getcwd) "/" path)))))
(member directory (trusted-projects)))))
Return value in its canonical form, or raise a configuration error.
(define* (validate-setting key value #:key path line column)
"Return @var{value} in its canonical form, or raise a configuration error."
(define (bad expected)
(raise-config-error path line column
(format #f "~a must be ~a, got ~s" key expected value)))
(unless (config-key-documented? key)
(raise-config-error path line column
(format #f "unknown configuration key `~a'" key)))
(let ((validator (assq-ref setting-validators
(assq-ref (config-key-doc key) 'type))))
(if validator (validator value bad) value)))
Run thunk, turning a configuration error into a message and #f.
The caller decides the exit status; a malformed configuration is a usage error, and every caller treats it as one.
(define* (with-config-error-handler thunk #:key (port (current-error-port)))
"Run @var{thunk}, turning a configuration error into a message and #f.
The caller decides the exit status; a malformed configuration is a usage
error, and every caller treats it as one."
(catch 'sift-config-error
thunk
(lambda (key object)
(format port "sift: ~a~%" (config-error->string object))
#f)))
This record type has 2 fields: values, provenance.
(define-record-type <config> (make-config values provenance) config? ;; An alist of settings, and an alist of the same keys to the place the ;; winning value came from. Keeping the provenance beside the values is ;; what makes `config show --source' honest: it cannot drift, because it is ;; recorded when the value is chosen, not reconstructed afterwards. (values config-values) (provenance config-provenance))
("sift.yaml" "sift.yml" ".sift.yaml" ".sift.yml" "sift.scm" ".sift.scm")
(define config-file-names
'("sift.yaml" "sift.yml" ".sift.yaml" ".sift.yml"
"sift.scm" ".sift.scm"))
((dialect (type . dialect) (default . #f) (flag . "--dialect") (description . "Dialect to read the file as: scheme, racket, elisp or cl.")) (style (type . style) (default . community) (flag . "--style") (description . "Formatting style: community or dangling.")) (line-length (type . integer) (default . #f) (flag . "--line-length") (description . "Soft line limit; #f means 96, or 80 for Emacs Lisp.")) (indent (type . integer) (default . 2) (flag . "--indent") (description . "Indentation width in columns.")) (indent-rules (type . rules) (default) (flag . #f) (description . "Indentation for a project's own macros: (symbol . columns) pairs.")) (brackets (type . brackets) (default . #f) (flag . "--brackets") (description . "Bracket style for clause lists: square, parens or preserve.")) (blank-lines (type . blank-lines) (default . preserve) (flag . "--blank-lines") (description . "Blank lines: preserve the author's, or one between top-level forms.")) (max-depth (type . integer) (default . 6) (flag . #f) (description . "Depth at which wrap-in-let suggests a binding. Config-only.")) (max-elements (type . integer) (default . 20) (flag . #f) (description . "Size at which wrap-in-let suggests a binding. Config-only.")) (max-definition-depth (type . integer) (default . 6) (flag . #f) (description . "Conditionals deep at which nesting-depth warns. Config-only.")) (max-cognitive-complexity (type . integer) (default . 15) (flag . #f) (description . "Cognitive complexity at which cognitive-complexity warns. Config-only.")) (max-cyclomatic-complexity (type . integer) (default . 10) (flag . #f) (description . "Paths at which cyclomatic-complexity warns. Config-only.")) (max-positional (type . integer) (default . 5) (flag . #f) (description . "Positional arguments before keyword-arguments suggests :key. Config-only.")) (single-letter-names (type . names) (default i j) (flag . #f) (description . "Single-letter names single-letter-name accepts, such as index variables.")) (field-macros (type . names) (default package operating-system) (flag . #f) (description . "Macros whose arguments are named fields rather than positional parameters, which keyword-arguments leaves alone. Config-only.")) (hover (type . boolean) (default . #t) (flag . #f) (description . "Answer the language server's hover with a rule or a definition. Config-only.")) (completion (type . boolean) (default . #t) (flag . #f) (description . "Offer the project's names in the language server's completion. Config-only.")) (inlay-hints (type . hints) (default parameters) (flag . #f) (description . "Inlay hints the server answers: `parameters' (a parameter's name beside each positional argument), `types' (the type a literal states outright), both as a list, or #f for none. Config-only.")) (stdlib (type . stdlib) (default . #t) (flag . #f) (description . "The standard library the language server reads for the names the project does not define: true for the one this machine has installed, including the third-party packages beside it, false for none, or a list of directories and source URLs to read instead. Config-only.")) (download-sources (type . boolean) (default . #f) (flag . #f) (description . "Fetch the source URLs named by `stdlib' into the cache and index them. False by default, because reaching the network is a decision a project file should not make on its own. Config-only.")) (compiler-diagnostics (type . boolean) (default . #t) (flag . #f) (description . "Ask the dialect's own compiler for warnings and errors when a buffer is opened or saved. The compiler runs in a thread on a temporary copy of the text; false turns the second opinion off. Config-only.")) (optimize-imports (type . boolean) (default . #t) (flag . #f) (description . "Remove unused imports when the language server or `sift fix' organizes them. Config-only.")) (sort-imports (type . boolean) (default . #t) (flag . #f) (description . "Sort the specifications of every import form alphabetically when the language server or `sift fix' organizes them. Config-only.")) (comment-align (type . boolean) (default . #f) (flag . "--comment-align") (description . "Align inline comments in contiguous runs.")) (file-filter (type . patterns) (default . #f) (flag . "--file-filter") (description . "Glob patterns a file must match to be read (`*' stops at a directory, `**' crosses one, a leading `!' excludes); #f means the built-in extensions.")) (checkers (type . names) (default . #f) (flag . "--checker") (description . "The checkers to run, or #f for every applicable one.")) (exclude-checkers (type . names) (default) (flag . "--exclude-checker") (description . "Checkers to skip.")) (severity (type . severity) (default . info) (flag . "--severity") (description . "Minimum severity to report: error, warning or info.")) (format (type . output-format) (default . human) (flag . "--format") (description . "Output format: human, json or null.")) (color (type . color) (default . auto) (flag . "--no-color") (description . "Colour output: auto (a terminal, without NO_COLOR), always or never.")) (quiet (type . boolean) (default . #f) (flag . "--quiet") (description . "Suppress the summary line.")) (verbose (type . boolean) (default . #f) (flag . "--verbose") (description . "Print per-file processing details.")) (force (type . boolean) (default . #f) (flag . "--force") (description . "Format a file that has parse errors, leaving the broken part verbatim.")) (loop-keywords (type . loop-style) (default . either) (flag . #f) (description . "LOOP keyword style: either, literal or symbolic. Config-only.")))
(#f when the key is config-only).
(define config-keys
'((dialect
(type . dialect)
(default . #f)
(flag . "--dialect")
(description . "Dialect to read the file as: scheme, racket, elisp or cl."))
(style
(type . style)
(default . community)
(flag . "--style")
(description . "Formatting style: community or dangling."))
(line-length
(type . integer)
(default . #f)
(flag . "--line-length")
(description . "Soft line limit; #f means 96, or 80 for Emacs Lisp."))
(indent
(type . integer)
(default . 2)
(flag . "--indent")
(description . "Indentation width in columns."))
(indent-rules
(type . rules)
(default . ())
(flag . #f)
(description . "Indentation for a project's own macros: (symbol . columns) pairs."))
(brackets
(type . brackets)
(default . #f)
(flag . "--brackets")
(description . "Bracket style for clause lists: square, parens or preserve."))
(blank-lines
(type . blank-lines)
(default . preserve)
(flag . "--blank-lines")
(description . "Blank lines: preserve the author's, or one between top-level forms."))
(max-depth
(type . integer)
(default . 6)
(flag . #f)
(description . "Depth at which wrap-in-let suggests a binding. Config-only."))
(max-elements
(type . integer)
(default . 20)
(flag . #f)
(description . "Size at which wrap-in-let suggests a binding. Config-only."))
(max-definition-depth
(type . integer)
(default . 6)
(flag . #f)
(description . "Conditionals deep at which nesting-depth warns. Config-only."))
(max-cognitive-complexity
(type . integer)
(default . 15)
(flag . #f)
(description . "Cognitive complexity at which cognitive-complexity warns. Config-only."))
(max-cyclomatic-complexity
(type . integer)
(default . 10)
(flag . #f)
(description . "Paths at which cyclomatic-complexity warns. Config-only."))
(max-positional
(type . integer)
(default . 5)
(flag . #f)
(description . "Positional arguments before keyword-arguments suggests :key. Config-only."))
(single-letter-names
(type . names)
(default . (i j))
(flag . #f)
(description . "Single-letter names single-letter-name accepts, such as index variables."))
(field-macros
(type . names)
(default . (package operating-system))
(flag . #f)
(description . "Macros whose arguments are named fields rather than positional parameters, which keyword-arguments leaves alone. Config-only."))
(hover
(type . boolean)
(default . #t)
(flag . #f)
(description . "Answer the language server's hover with a rule or a definition. Config-only."))
(completion
(type . boolean)
(default . #t)
(flag . #f)
(description . "Offer the project's names in the language server's completion. Config-only."))
(inlay-hints
(type . hints)
(default . (parameters))
(flag . #f)
(description . "Inlay hints the server answers: `parameters' (a parameter's name beside each positional argument), `types' (the type a literal states outright), both as a list, or #f for none. Config-only."))
(stdlib
(type . stdlib)
(default . #t)
(flag . #f)
(description . "The standard library the language server reads for the names the project does not define: true for the one this machine has installed, including the third-party packages beside it, false for none, or a list of directories and source URLs to read instead. Config-only."))
(download-sources
(type . boolean)
(default . #f)
(flag . #f)
(description . "Fetch the source URLs named by `stdlib' into the cache and index them. False by default, because reaching the network is a decision a project file should not make on its own. Config-only."))
(compiler-diagnostics
(type . boolean)
(default . #t)
(flag . #f)
(description . "Ask the dialect's own compiler for warnings and errors when a buffer is opened or saved. The compiler runs in a thread on a temporary copy of the text; false turns the second opinion off. Config-only."))
(optimize-imports
(type . boolean)
(default . #t)
(flag . #f)
(description . "Remove unused imports when the language server or `sift fix' organizes them. Config-only."))
(sort-imports
(type . boolean)
(default . #t)
(flag . #f)
(description . "Sort the specifications of every import form alphabetically when the language server or `sift fix' organizes them. Config-only."))
(comment-align
(type . boolean)
(default . #f)
(flag . "--comment-align")
(description . "Align inline comments in contiguous runs."))
(file-filter
(type . patterns)
(default . #f)
(flag . "--file-filter")
(description . "Glob patterns a file must match to be read (`*' stops at a directory, `**' crosses one, a leading `!' excludes); #f means the built-in extensions."))
(checkers
(type . names)
(default . #f)
(flag . "--checker")
(description . "The checkers to run, or #f for every applicable one."))
(exclude-checkers
(type . names)
(default . ())
(flag . "--exclude-checker")
(description . "Checkers to skip."))
(severity
(type . severity)
(default . info)
(flag . "--severity")
(description . "Minimum severity to report: error, warning or info."))
(format
(type . output-format)
(default . human)
(flag . "--format")
(description . "Output format: human, json or null."))
(color
(type . color)
(default . auto)
(flag . "--no-color")
(description . "Colour output: auto (a terminal, without NO_COLOR), always or never."))
(quiet
(type . boolean)
(default . #f)
(flag . "--quiet")
(description . "Suppress the summary line."))
(verbose
(type . boolean)
(default . #f)
(flag . "--verbose")
(description . "Print per-file processing details."))
(force
(type . boolean)
(default . #f)
(flag . "--force")
(description . "Format a file that has parse errors, leaving the broken part verbatim."))
(loop-keywords
(type . loop-style)
(default . either)
(flag . #f)
(description . "LOOP keyword style: either, literal or symbolic. Config-only."))))
Go to definition is the one question an editor asks that sift’s reader already knows most of the answer to: a definition is a form whose operator is in the table below, and its name is the atom the form puts in a particular place. What the reader does not have, and this module adds, is the two things that make the answer worth trusting.
The first is scope. ‘(define (f x) (let ((x 1)) x))’ has two ‘x’s, and the reference belongs to the nearest one; a server that answered with the first ‘x’ in the file would be wrong in every file that uses a name twice. So the bindings a form introduces are computed here – parameters, ‘let’ and ‘letrec’ bindings, an internal definition, a named ‘let’, a ‘dolist’ variable – next to the range each of them is visible in, and a reference is resolved by walking outwards from the form it sits in.
The second is what counts as a definition in each dialect. ‘defun’, ‘cl-defun’, ‘define’, ‘define-public’, ‘defmacro’, ‘cl-defgeneric’, ‘defstruct’, ‘defpackage’, ‘defalias’ and the rest of the table below are not one shape: ‘(define (f x) ...)’ keeps its name inside the argument list, ‘(defpackage #:foo ...)’ keeps it in a keyword, ‘(defalias ’f ...)’ behind a quote, and ‘(define-module (foo bar) ...)’ inside a list. Each shape is read here, once, so that the language server, the outline, the completion list and the rename all agree about what a name is and where it lives.
Nothing here expands a macro, resolves a module import or reads a package definition: a reference is matched by name, within one dialect. That is the same promise the rest of sift makes – it reads the text you have – and the limits it implies are written down in the manual’s table of what the language server answers.
#f.
'().
#f.
#f.
#f when it does not name anything.
#f.
#f.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Return the completion kind for kind.
(define (completion-kind kind)
"Return the completion kind for @var{kind}."
(case kind
[(function alias method macro) 3]
[(variable parameter) 6]
[(constant) 21]
[(class) 7]
[(struct) 22]
[(module package) 9]
[(type) 25]
[else 6]))
Return the docstring a definition carries, or #f.
The docstring of a function is the string after its argument list; the one of a variable is the string after its value; a ‘define’ of a value has no place to put one, which is why the case is written out here.
(define (definition-docstring definition)
"Return the docstring a definition carries, or @code{#f}.
The docstring of a function is the string after its argument list; the
one of a variable is the string after its value; a `define' of a value has
no place to put one, which is why the case is written out here."
(let* ((form (definition-form definition))
(operator (and form (head-name form)))
(args (and form (arguments-of form))))
(and args
(cond
[(memq operator '(define define* define-public define-inlinable))
(let ((first (nth-or args 0)))
(if (and first (node-list? first))
(docstring-at (nth-or args 1))
#f))]
[(memq operator '(define-macro))
(docstring-at (nth-or args 1))]
[(memq operator '(defun defmacro defsubst cl-defun cl-defmacro cl-defsubst
defmethod cl-defmethod defgeneric cl-defgeneric
define-minor-mode define-derived-mode
define-generic-mode define-syntax))
(docstring-at (nth-or args 2))]
[(memq operator '(defvar defvar-local defcustom defparameter defface))
(docstring-at (nth-or args 2))]
[else #f]))))
Return the definitions of name in ast, top level first.
(define (definitions-by-name ast name)
"Return the definitions of @var{name} in @var{ast}, top level first."
(filter (lambda (definition)
(string=? (definition-name definition) name))
(parse-definitions ast)))
Return the definitions of ast, as ‘parse-definitions’ does.
(define (definitions-in ast)
"Return the definitions of @var{ast}, as `parse-definitions' does."
(parse-definitions ast))
Return the definitions of ast nested the way the outline shows them.
A definition inside another one is a child of it, nearest first, which is what makes a ‘define’ inside a ‘let’ appear under the function that holds it rather than beside it.
(define (document-symbol-tree ast)
"Return the definitions of @var{ast} nested the way the outline shows them.
A definition inside another one is a child of it, nearest first, which is what
makes a `define' inside a `let' appear under the function that holds it rather
than beside it."
(let* ((definitions (parse-definitions ast))
(top (filter (lambda (definition) (not (definition-scope definition)))
definitions)))
(map (lambda (definition)
(cons definition
(map (lambda (child) (cons child '()))
(filter (lambda (child)
(eq? (definition-scope child)
(definition-form definition)))
definitions))))
top)))
Return the parameter atoms a function definition form lists, or
'().
‘(define (f a b) ...)’ keeps them inside the argument list; ‘(defun f (a b))’ keeps them in the second argument; ‘(defmethod f ((x t)) ...)’ likewise.
(define (form-parameters form)
"Return the parameter atoms a function definition form lists, or @code{'()}.
`(define (f a b) ...)' keeps them inside the argument list; `(defun f (a b))'
keeps them in the second argument; `(defmethod f ((x t)) ...)' likewise."
(let* ((operator (head-name form))
(args (arguments-of form))
(first (nth-or args 0)))
(cond
[(memq operator '(define define* define-public define-inlinable))
(if (and first (node-list? first))
(append-map parameter-atoms (cdr (elements first)))
'())]
[(memq operator '(defun defmacro defsubst cl-defun cl-defmacro cl-defsubst
defgeneric cl-defgeneric defmethod cl-defmethod
define-minor-mode define-derived-mode
define-generic-mode))
(parameter-atoms (nth-or args 1))]
[else '()])))
Return two values: the innermost node at index, and its ancestors.
(define (node-path-at ast index)
"Return two values: the innermost node at @var{index}, and its ancestors."
(define (descend node ancestors)
(let ((child (and (node-list? node) (child-at node index))))
(if child
(descend child (cons node ancestors))
(values node ancestors))))
(let loop ((nodes ast))
(cond
[(null? nodes) (values #f '())]
[(and (node-data? (car nodes)) (inside? (car nodes) index))
(descend (car nodes) '())]
[else (loop (cdr nodes))])))
Return every symbol atom in ast called name, in source order.
A quote is not entered, because ‘’(a b)’ is a list of data; a datum comment is not entered either, for the reason the reader was told not to read it.
(define (occurrences-of ast name)
"Return every symbol atom in @var{ast} called @var{name}, in source order.
A quote is not entered, because `'(a b)' is a list of data; a datum comment is
not entered either, for the reason the reader was told not to read it."
(let ((found '()))
(define (walk node)
(cond
[(node-datum-comment? node) #f]
[(node-prefix? node)
;; `'x' names the same symbol as `x', so a quote prefix passes
;; through to its child and nothing else.
(let ((child (node-child node)))
(when (and child (not (quoted? node))) (walk child)))]
[(node-atom? node)
(when (and (eq? (node-atom-type node) 'symbol)
(string=? (node-value node) name))
(set! found (cons node found)))]
[(node-list? node)
(for-each walk (node-children node))]
[(node-conditional? node)
(let ((feature (node-feature node))
(guarded (node-guarded-form node)))
(when feature (walk feature))
(when guarded (walk guarded)))]
[else #f]))
(for-each walk ast)
(sort (reverse found) (lambda (a b) (< (node-index a) (node-index b))))))
Return every definition in ast, outermost first, each with its scope.
The scope of a definition is the definition form it is written inside,
or #f when it is one of the file’s own top-level forms; that is
the parent the outline nests under.
(define (parse-definitions ast)
"Return every definition in @var{ast}, outermost first, each with its scope.
The scope of a definition is the definition form it is written inside, or
@code{#f} when it is one of the file's own top-level forms; that is the parent
the outline nests under."
(let ((found '()))
(walk-forms (lambda (node ancestors)
(let ((scope (find (lambda (ancestor)
(and (head-name ancestor)
(form-kind (head-name ancestor))))
ancestors)))
(let ((definition (definition-of-form node scope)))
(when definition
(set! found (cons definition found))))))
ast)
(sort-by-index (reverse found))))
Return the definition the symbol at index names, or #f.
The name itself first, then lexical scope, then the file’s own definitions: a parameter or a ‘let’ variable is nearer than a definition of the same name, and a reference to a function defined later in the file is still a reference to it.
(define (resolve-definition ast index)
"Return the definition the symbol at @var{index} names, or @code{#f}.
The name itself first, then lexical scope, then the file's own definitions: a
parameter or a `let' variable is nearer than a definition of the same name,
and a reference to a function defined later in the file is still a reference
to it."
(let ((node (symbol-node-at ast index)))
(and node
(let ((name (symbol-name node)))
(call-with-values (lambda () (node-path-at ast index))
(lambda (cursor ancestors)
(let ((self (self-binding ancestors node)))
(cond
[self (binding-definition (car self) (cdr self))]
[else (or (resolve-in-scope ancestors name index)
(top-level-definition ast name))]))))))))
Return the name the symbol at index has, or #f.
(define (resolve-name ast index)
"Return the name the symbol at @var{index} has, or @code{#f}."
(let ((node (symbol-node-at ast index)))
(and node (symbol-name node))))
Return the protocol’s number for kind.
(define (symbol-kind kind)
"Return the protocol's number for @var{kind}."
(case kind
[(function alias) 12]
[(method) 6]
[(macro) 12]
[(variable parameter) 13]
[(constant) 14]
[(class) 5]
[(struct) 23]
[(type) 26]
[(module) 2]
[(package) 4]
[else 13]))
Return the name of an atom, or #f when it does not name anything.
A keyword loses its #: or : prefix and a package marker
loses its qualifier, so that ‘#:run’, ‘app:run’ and ‘run’ compare the
same way – which is what a reference is.
(define (symbol-name node)
"Return the name of an atom, or @code{#f} when it does not name anything.
A keyword loses its @code{#:} or @code{:} prefix and a package marker loses
its qualifier, so that `#:run', `app:run' and `run' compare the same way --
which is what a reference is."
(and node
(node-atom? node)
(case [node-atom-type node]
[(symbol keyword)
(let* ((value (node-value node))
(marker (node-package-marker node))
(bare (cond
[(and marker (< (string-length marker) (string-length value)))
(substring value (string-length marker))]
[(string-prefix? "#:" value) (substring value 2)]
[(string-prefix? ":" value) (substring value 1)]
[else value])))
bare)]
[else #f])))
Return the symbol atom at index, or #f.
(define (symbol-node-at ast index)
"Return the symbol atom at @var{index}, or @code{#f}."
(call-with-values (lambda () (node-path-at ast index))
(lambda (node ancestors)
(and node (node-atom? node)
(eq? (node-atom-type node) 'symbol)
node))))
Return the file-level definition of name, or #f.
(define (top-level-definition ast name)
"Return the file-level definition of @var{name}, or @code{#f}."
(let ((all (filter (lambda (definition)
(and (not (definition-scope definition))
(string=? (definition-name definition) name)))
(parse-definitions ast))))
(and (pair? all) (car all))))
(let let* letrec letrec* do lambda lambda* cl-lambda dolist dotimes multiple-value-bind define-syntax let-syntax letrec-syntax syntax-rules syntax-case)
(let-syntax ((swap (syntax-rules ...))) ...)' is
;; a name a use site refers to, and an editor that answered "not here" would
;; be wrong about the one place the name is written. `define-syntax' is here
;; for its patterns rather than for the macro it defines: a pattern variable
;; is a binding, and the template that uses it is the clearest "go to
;; definition" a macro body has.
(define binding-forms
'(let let* letrec letrec* do lambda lambda* cl-lambda
dolist dotimes multiple-value-bind
define-syntax let-syntax letrec-syntax syntax-rules syntax-case))
((function define define* define-public define-inlinable defun defsubst define-minor-mode define-derived-mode define-generic-mode cl-defun cl-defsubst defgeneric cl-defgeneric) (macro define-syntax define-macro defmacro cl-defmacro) (method defmethod cl-defmethod) (variable defvar defvar-local defcustom defparameter defface) (constant defconst defconstant) (class defclass define-class) (struct defstruct cl-defstruct define-record-type struct) (type deftype define-condition) (package defpackage define-package) (module define-module) (alias defalias))
(define definition-forms
'((function . (define define* define-public define-inlinable
defun defsubst define-minor-mode define-derived-mode
define-generic-mode cl-defun cl-defsubst
defgeneric cl-defgeneric))
(macro . (define-syntax define-macro defmacro cl-defmacro))
(method . (defmethod cl-defmethod))
(variable . (defvar defvar-local defcustom defparameter defface))
(constant . (defconst defconstant))
(class . (defclass define-class))
(struct . (defstruct cl-defstruct define-record-type struct))
(type . (deftype define-condition))
(package . (defpackage define-package))
(module . (define-module))
(alias . (defalias))))
A tool that walks a directory has to answer one question before it reads anything: which of these files are mine? The answer is a list of extensions, and every project eventually has a file that is not on it – an R6RS program in ‘.sps’, a file generated with a different suffix – or a directory it does not want walked at all.
So the answer is a *filter*: patterns a file must match, with ‘*’ stopping at a directory and ‘**’ crossing one, and a leading ‘!’ for the files and directories to leave out. With no filter set, the extensions are the answer, which is what every project that has never thought about it wants.
Both halves of sift read this module – the command line when it walks the operands, and the language server when it indexes the workspace – so ‘sift ci .’ and ‘sift lsp’ cannot disagree about which files are Lisp files.
#t when path names a gzip file.
#t when path is a file sift should read.
#t when path matches the glob pattern.
#t when path ends in an extension sift reads.
#f when it is not a file to
read.
.gz suffix, when it has one.
Return #t when path names a gzip file.
(define (compressed-path? path)
"Return @code{#t} when @var{path} names a gzip file."
(and (string? path) (string-suffix? ".gz" path)))
Return #t when path is a file sift should read.
patterns is the project’s ‘file-filter’, or #f for none, in
which case the extension list decides. With patterns, a path is
included when it matches one of them – patterns are matched in the
order they are written, and the last one that matches wins, so
‘!src/generated/**’ can be put after the pattern that let the directory
in.
root is the directory the walk started from: a pattern that names a directory is written the way a person reads the project, ‘src/**’, not the way the file system spells it.
(define* (file-included? patterns path #:optional (root #f))
"Return @code{#t} when @var{path} is a file sift should read.
@var{patterns} is the project's `file-filter', or @code{#f} for none, in which
case the extension list decides. With patterns, a path is included when it
matches one of them -- patterns are matched in the order they are written, and
the last one that matches wins, so `!src/generated/**' can be put after the
pattern that let the directory in.
@var{root} is the directory the walk started from: a pattern that names a
directory is written the way a person reads the project, `src/**', not the way
the file system spells it."
(if (or (not patterns) (null? patterns))
(lisp-path? path)
(let ((subject (if root (relative-path root path) path)))
(let loop ((rest patterns) (verdict #f))
(cond
[(null? rest) (and verdict #t)]
[(glob-match? (positive-pattern (car rest)) subject)
(loop (cdr rest) (not (negated? (car rest))))]
[else (loop (cdr rest) verdict)])))))
Return #t when path matches the glob pattern.
A pattern with no separator in it is matched against the file’s own name, so ‘*.sps’ means "every .sps file, wherever it is" rather than "one in the workspace root" – which is what a person writing it means.
(define (glob-match? pattern path)
"Return @code{#t} when @var{path} matches the glob @var{pattern}.
A pattern with no separator in it is matched against the file's own name, so
`*.sps' means \"every .sps file, wherever it is\" rather than \"one in the
workspace root\" -- which is what a person writing it means."
(let* ((subject (if (string-contains pattern "/") path (basename-of path)))
(regexp (make-regexp (glob-pattern pattern))))
(and (regexp-exec regexp subject) #t)))
Return #t when path ends in an extension sift reads.
‘.sps’ is an R6RS program and ‘.sld’ an R7RS library: both are Scheme, and a project that keeps them apart from its ‘.scm’ files would otherwise have its libraries indexed by everything except the tool meant to read them.
(define (lisp-path? path)
"Return @code{#t} when @var{path} ends in an extension sift reads.
`.sps' is an R6RS program and `.sld' an R7RS library: both are Scheme, and a
project that keeps them apart from its `.scm' files would otherwise have its
libraries indexed by everything except the tool meant to read them."
(let ((dot (string-rindex path #\.)))
(and dot (member (string-downcase (substring path dot)) lisp-extensions) #t)))
Return patterns as one line, for a message.
(define (patterns->string patterns)
"Return @var{patterns} as one line, for a message."
(if (or (not patterns) (null? patterns))
"the built-in extensions"
(string-join patterns ", ")))
Return the text of path, or #f when it is not a file to
read.
A ‘.gz’ file is decompressed as it is read, so a library that ships compressed is read like the file beside it. A file larger than limit characters, or one that cannot be read, is not a file this can answer about.
(define* (read-file-text path #:optional (limit #f))
"Return the text of @var{path}, or @code{#f} when it is not a file to read.
A `.gz' file is decompressed as it is read, so a library that ships compressed
is read like the file beside it. A file larger than @var{limit} characters,
or one that cannot be read, is not a file this can answer about."
(let ((text (if (compressed-path? path)
(decompressed-text path limit)
(false-if-exception (call-with-input-file path get-string-all)))))
(and (string? text)
(or (not limit) (< (string-length text) limit))
text)))
Return path without the .gz suffix, when it has one.
(define (without-compression path)
"Return @var{path} without the @code{.gz} suffix, when it has one."
(if (compressed-path? path) (string-drop-right path 3) path))
(".scm" ".ss" ".sld" ".sls" ".sps" ".rkt" ".rktd" ".rktl" ".el" ".lisp" ".cl" ".asd" ".lsp" ".system")
(define lisp-extensions
'(".scm" ".ss" ".sld" ".sls" ".sps" ".rkt" ".rktd" ".rktl" ".el"
".lisp" ".cl" ".asd" ".lsp" ".system"))
(".git" ".hg" ".svn" ".darcs" "node_modules" "build" "dist" ".cache" "_build" "target" "vendor" ".venv" ".tox" ".mypy_cache" "__pycache__")
(define skipped-directories
'(".git" ".hg" ".svn" ".darcs" "node_modules" "build" "dist" ".cache"
"_build" "target" "vendor" ".venv" ".tox" ".mypy_cache" "__pycache__"))
sift is a *fuzzy* formatter: it adjusts indentation, spacing and the placement of delimiters, and it keeps the author’s line breaks wherever they carry structure. It never reflows a form, never re-spells a string escape, never moves a comment to another line, and never drops one.
The pipeline is:
1. normalise line endings to LF (the reader reads CRLF as one newline); 2. normalise intra-form spacing – one space between adjacent forms on a line, none after an opener or before a closer; 3. place closing delimiters (community: trailing; dangling: own line); 4. compute indentation from the dialect’s special-form table, with the generic rule as the fallback; 5. align inline comments, when asked; 6. preserve blank lines, collapsing runs that are longer than the style allows; 7. clamp reader prefixes to their datum; 8. leave line length to the linter, which warns rather than reflowing.
Formatting is deterministic and idempotent: given the same input and the same options it produces the same output, and formatting that output again changes nothing. Indentation is computed from structure and from the column of the opening delimiter, never from the whitespace that was there, which is exactly what makes the second pass a no-op.
#t when the elements of a head form are clauses.
#t when formatting source would change it.
Return #t when the elements of a head form are clauses.
The elements of such a form are neither arguments to count nor keywords
to weigh, so a check about a form’s *elements* – how many there are,
what they are called – has nothing to say about it. A loop is the one
form whose clauses sit flat in its own list instead of in a clause list
each, which is why it is here and not in clause-taking-forms:
that table also decides how a form’s children are indented, and a loop’s
clauses are read on one line.
(define (clause-headed? dialect head)
"Return @code{#t} when the elements of a @var{head} form are clauses.
The elements of such a form are neither arguments to count nor keywords to
weigh, so a check about a form's *elements* -- how many there are, what they
are called -- has nothing to say about it. A loop is the one form whose
clauses sit flat in its own list instead of in a clause list each, which is
why it is here and not in @code{clause-taking-forms}: that table also decides
how a form's children are indented, and a loop's clauses are read on one line."
(or (memq head (clause-taking-forms dialect))
(and (eq? head 'loop) (memq dialect '(elisp cl)))))
Return the bracket style dialect wants when none is given.
Guile’s own sources write a ‘cond’ clause as ‘[(= x 1) ...]’, and so does the Guix code base; a Scheme file therefore gets square brackets for its clause lists unless the caller says otherwise. Racket writes the clause of a ‘cond’, a ‘case’ and a ‘match’ the same way, and gets the same answer. Emacs Lisp and Common Lisp have no such convention, so they keep whatever the author wrote.
(define* (default-brackets dialect)
"Return the bracket style @var{dialect} wants when none is given.
Guile's own sources write a `cond' clause as `[(= x 1) ...]', and so does the
Guix code base; a Scheme file therefore gets square brackets for its clause
lists unless the caller says otherwise. Racket writes the clause of a `cond',
a `case' and a `match' the same way, and gets the same answer. Emacs Lisp and
Common Lisp have no such convention, so they keep whatever the author wrote."
(if (memq dialect '(scheme racket)) 'square 'preserve))
Return the indentation width sift uses by default: two, for every dialect.
(define* (default-indent dialect) "Return the indentation width sift uses by default: two, for every dialect." 2)
Return the soft line limit sift uses for dialect when none is given.
Emacs Lisp is held to 80 columns – the width the Emacs manual assumes for a docstring’s first line and for a source file read side by side – while Scheme, Racket and Common Lisp get 96.
(define* (default-line-length dialect)
"Return the soft line limit sift uses for @var{dialect} when none is given.
Emacs Lisp is held to 80 columns -- the width the Emacs manual assumes for a
docstring's first line and for a source file read side by side -- while Scheme,
Racket and Common Lisp get 96."
(if (eq? dialect 'elisp) 80 96))
Render ast as source text.
sort puts the file’s top-level definitions in alphabetical order first; it is off by default and the caller has to ask, because it changes text a reader did not point at.
The result is deterministic: nothing here depends on a hash table’s order or on any state outside the arguments.
(define* (format-ast ast #:key (dialect 'scheme) (style 'community)
(indent-width 2) (comment-align #f) (brackets #f)
(indent-rules '()) (blank-lines 'preserve) (sort #f))
"Render @var{ast} as source text.
@var{sort} puts the file's top-level definitions in alphabetical order first;
it is off by default and the caller has to ask, because it changes text a
reader did not point at.
The result is deterministic: nothing here depends on a hash table's order or
on any state outside the arguments."
(let* ((ast (if sort (sort-top-level ast) ast))
(base (make-ctx #:dialect dialect #:style style
#:indent-width indent-width #:brackets brackets
#:rules indent-rules #:blank-lines blank-lines)))
(if comment-align
(call-with-values
(lambda () (render-document ast base))
(lambda (text marks)
(let* ((table (compute-alignment marks))
(aligned (%make-ctx dialect style indent-width #t table
(cons '() '()) (ctx-brackets base)
(ctx-rules base) (ctx-blank-lines base))))
(call-with-values
(lambda () (render-document ast aligned))
(lambda (aligned-text ignored) aligned-text)))))
(call-with-values (lambda () (render-document ast base))
(lambda (text marks) text)))))
Return #t when formatting source would change it.
This is what ‘sift check’ asks: not "is the file ugly?" but "would running the formatter change a single byte?".
(define* (format-check source #:key (dialect 'scheme) (style 'community)
(indent 2) (comment-align #f) (brackets #f)
(blank-lines 'preserve))
"Return @code{#t} when formatting @var{source} would change it.
This is what `sift check' asks: not \"is the file ugly?\" but \"would running
the formatter change a single byte?\"."
(call-with-values
(lambda () (format-source source #:dialect dialect #:style style
#:indent indent #:comment-align comment-align
#:blank-lines blank-lines))
(lambda (formatted errors)
(not (string=? formatted source)))))
Format source, returning two values: the text and the parse errors.
No file is read from or written to here, and no error is swallowed: the
caller decides whether an error is fatal (see format/file).
(define* (format-source source #:key (dialect 'scheme) (file #f)
(style 'community) (indent #f) (comment-align #f)
(line-length #f) (force #f) (brackets #f)
(indent-rules '()) (blank-lines 'preserve) (sort #f))
"Format @var{source}, returning two values: the text and the parse errors.
No file is read from or written to here, and no error is swallowed: the
caller decides whether an error is fatal (see @code{format/file})."
(call-with-values
(lambda () (read-source #:source source #:dialect dialect #:file file))
(lambda (ast errors)
(values (format-ast ast #:dialect dialect #:style style
#:indent-width (or indent (default-indent dialect))
#:comment-align comment-align
#:brackets brackets
#:indent-rules indent-rules
#:blank-lines blank-lines
#:sort sort)
errors))))
Format source and return just the text.
(define* (format-string source #:key (dialect 'scheme) (style 'community)
(indent 2) (comment-align #f) (brackets #f)
(indent-rules '()) (blank-lines 'preserve) (sort #f))
"Format @var{source} and return just the text."
(call-with-values
(lambda () (read-source #:source source #:dialect dialect))
(lambda (ast errors)
(format-ast ast #:dialect dialect #:style style
#:indent-width indent #:comment-align comment-align
#:brackets brackets #:indent-rules indent-rules
#:blank-lines blank-lines #:sort sort))))
Format the file at path, returning the text and the parse errors.
The dialect is detected from path when dialect is #f.
(define* (format/file path #:key (dialect #f) (style 'community) (indent 2)
(comment-align #f) (force #f) (brackets #f)
(indent-rules '()) (blank-lines 'preserve) (sort #f))
"Format the file at @var{path}, returning the text and the parse errors.
The dialect is detected from @var{path} when @var{dialect} is @code{#f}."
(let* ((source (call-with-input-file path get-string-all))
(dialect* (or dialect
(detect-dialect #:file path #:source source)
'scheme)))
(format-source source #:dialect dialect* #:file path #:style style
#:indent indent #:comment-align comment-align
#:force force #:brackets brackets #:indent-rules indent-rules
#:blank-lines blank-lines #:sort sort)))
Return the indentation rule for operator in dialect.
#f means the form is not in the table and the generic rule
applies. The table is keyed by (dialect, symbol), so ‘defun’ can
mean one thing in Emacs Lisp and another in Common Lisp without either
guessing.
(define* (indent-rule dialect operator #:optional (indent-width 2))
"Return the indentation rule for @var{operator} in @var{dialect}.
@code{#f} means the form is not in the table and the generic rule applies.
The table is keyed by @code{(dialect, symbol)}, so `defun' can mean one thing
in Emacs Lisp and another in Common Lisp without either guessing."
(let ((entry (assq operator (indent-rules dialect))))
(and entry (cdr entry))))
Return the indentation table for dialect.
A dialect sift does not read is formatted by Scheme’s table, the same way the rest of the formatter treats syntax it does not recognise: every byte is kept and the shape is the one most likely to be right.
(define (indent-rules dialect)
"Return the indentation table for @var{dialect}.
A dialect sift does not read is formatted by Scheme's table, the same way the
rest of the formatter treats syntax it does not recognise: every byte is kept
and the shape is the one most likely to be right."
(let ((row (assq dialect dialect-indent-tables)))
(if row (cdr row) scheme-indent-rules)))
Undocumented procedure.
(define* (line-length-for dialect #:optional (override #f)) (or override (default-line-length dialect)))
Return the nodes of ast that are not whitespace and not a comment.
(define (significant-nodes ast)
"Return the nodes of @var{ast} that are not whitespace and not a comment."
(filter node-data? ast))
Undocumented procedure.
(define (string->blank-lines string)
(let ((style (string->symbol (string-downcase string))))
(and (memq style blank-lines-styles) style)))
Undocumented procedure.
(define (string->brackets string)
(let ((style (string->symbol (string-downcase string))))
(and (memq style brackets-styles) style)))
Undocumented procedure.
(define (string->style string)
(let ((s (string->symbol (string-downcase string))))
(and (memq s styles) s)))
Undocumented procedure.
(define (valid-blank-lines? style) (and (symbol? style) (memq style blank-lines-styles) #t))
Undocumented procedure.
(define (valid-brackets? style) (and (symbol? style) (memq style brackets-styles) #t))
Undocumented procedure.
(define (valid-style? style) (and (symbol? style) (memq style styles) #t))
(preserve one)
(define blank-lines-styles '(preserve one))
(square parens preserve)
(define brackets-styles '(square parens preserve))
preserve
(define default-blank-lines 'preserve)
((scheme (lambda . 2) (lambda* . 2) (case-lambda . 2) (define . 2) (define* . 2) (define-public . 2) (define-syntax . 2) (define-syntax-rule . 2) (define-record-type . 2) (define-values . 2) (define-module . 2) (define-class . 2) (define-generic . 2) (define-method . 2) (define-inlinable . 2) (define-constant . 2) (library . 2) (define-library . 2) (import . 2) (export . 2) (include . 2) (include-ci . 2) (include-library-declarations . 2) (eval-when . 2) (with-syntax . 2) (syntax-parameterize . 2) (define-syntax-parameter . 2) (identifier-syntax . 2) (quasisyntax . 2) (unsyntax . 2) (unsyntax-splicing . 2) (package . 2) (package/inherit . 2) (origin . 2) (gexp . 2) (ungexp . 2) (ungexp-splicing . 2) (modify-phases . 2) (add-before . 2) (add-after . 2) (replace . 2) (delete . 2) (substitute* . 2) (with-imported-modules . 2) (with-extensions . 2) (let . 2) (let* . 2) (letrec . 2) (letrec* . 2) (let-values . 2) (let*-values . 2) (let-syntax . 2) (letrec-syntax . 2) (let-optionals . 2) (let-keywords . 2) (cond . clauses) (case . 2) (cond-expand . 2) (when . 2) (unless . 2) (if . 2) (and . 2) (or . 2) (begin . 2) (do . 2) (delay . 2) (delay-force . 2) (force . 2) (parameterize . 2) (with-exception-handler . 2) (guard . 2) (dynamic-wind . 2) (call-with-values . 2) (call-with-current-continuation . 2) (call/cc . 2) (with-input-from-file . 2) (with-output-to-file . 2) (call-with-output-string . 2) (call-with-input-string . 2) (quasiquote . 2) (unquote . 2) (unquote-splicing . 2) (quote . 2) (syntax-rules . 2) (syntax-case . 2) (match-lambda . 2) (match . 2) (assert . 2) (test . 2) (test-assert . 2) (test-equal . 2) (test-error . 2) (test-group . 2) (assert-equal . 2) (assert-true . 2) (assert-false . 2) (assert-error . 2) (assert-no-error . 2) (assert-raises . 2) (assert-eq . 2) (assert-eqv . 2) (assert-contains . 2) (assert-matches . 2) (assert-empty . 2) (assert-in-range . 2) (assert-not-equal . 2) (assert-length . 2) (assert-one-of . 2) (suite . 2) (test-each . 2) (suite-each . 2) (scenario . 2) (given . 2) (when-step . 2) (then . 2) (and-step . 2) (but-step . 2) (while . 2) (benchmark . 2) (veritas-run . 2) (data-driven . 2)) (racket (define . 2) (define-values . 2) (define-syntax . 2) (define-syntax-rule . 2) (define-syntax-parser . 2) (define-for-syntax . 2) (define/contract . 2) (define/match . 2) (define-simple-macro . 2) (define-record-type . 2) (define-sequence-syntax . 2) (define-logger . 2) (struct . 2) (struct* . 2) (lambda . 2) (λ . 2) (case-lambda . 2) (let . 2) (let* . 2) (letrec . 2) (let-values . 2) (let*-values . 2) (letrec-values . 2) (let/cc . 2) (let/ec . 2) (let-syntax . 2) (letrec-syntax . 2) (parameterize . 2) (with-handlers . 2) (with-handlers* . 2) (with-syntax . 2) (with-syntax* . 2) (begin . 2) (begin0 . 2) (begin-for-syntax . 2) (module . 2) (module* . 2) (module+ . 2) (when . 2) (unless . 2) (and . 2) (or . 2) (do . 2) (delay . 2) (delay/name . 2) (delay/thread . 2) (dynamic-wind . 2) (call-with-values . 2) (guard . 2) (call-with-input-file . 2) (call-with-output-file . 2) (with-input-from-file . 2) (with-output-to-file . 2) (call-with-output-string . 2) (with-output-to-string . 2) (for . 2) (for/list . 2) (for*/list . 2) (for/vector . 2) (for*/vector . 2) (for/hash . 2) (for/hasheq . 2) (for/hasheqv . 2) (for/and . 2) (for/or . 2) (for/first . 2) (for/last . 2) (for/sum . 2) (for/product . 2) (for/set . 2) (for*/set . 2) (for/fold . 2) (for*/fold . 2) (for/foldr . 2) (for/lists . 2) (for*/lists . 2) (cond . clauses) (case . clauses) (match-lambda . clauses) (match-lambda* . clauses) (match . 2) (match* . 2) (syntax-case . 2) (syntax-parse . 2) (match-let . 2) (match-let* . 2) (match-letrec . 2) (match-define . 2) (syntax-rules . 2) (quote . 2) (quasiquote . 2) (unquote . 2) (unquote-splicing . 2) (syntax . 2) (quasisyntax . 2) (unsyntax . 2) (unsyntax-splicing . 2) (quote-syntax . 2) (test-case . 2)) (elisp (defun . 2) (defmacro . 2) (defsubst . 2) (defalias . 2) (cl-defun . 2) (cl-defmacro . 2) (cl-defsubst . 2) (cl-defgeneric . 2) (cl-defmethod . 2) (cl-defstruct . 2) (cl-labels . 2) (cl-flet . 2) (defvar . 2) (defconst . 2) (defcustom . 2) (defface . 2) (defgroup . 2) (define-minor-mode . 2) (define-derived-mode . 2) (define-globalized-minor-mode . 2) (defun* . 2) (defadvice . 2) (advice-add . 2) (let . 2) (let* . 2) (letrec . 2) (if . 2) (if-let . 2) (when-let . 2) (cond . clauses) (case . 2) (pcase . clauses) (pcase-let . 2) (pcase-let* . 2) (when . 2) (unless . 2) (while . 2) (progn . 2) (prog1 . 2) (prog2 . 2) (condition-case . 2) (condition-case-unless-debug . 2) (ignore-errors . 2) (unwind-protect . 2) (catch . 2) (throw . 2) (signal . 2) (dolist . 2) (dotimes . 2) (loop . clauses) (seq-let . 2) (seq-doseq . 2) (save-excursion . 2) (save-restriction . 2) (save-match-data . 2) (with-current-buffer . 2) (with-temp-buffer . 2) (with-temp-file . 2) (with-output-to-string . 2) (with-eval-after-load . 2) (with-silent-modifications . 2) (with-demoted-errors . 2) (lambda . 2) (quote . 2) (function . 2) (backquote . 2) (interactive . 2) (declare . 2) (require . 2) (provide . 2) (use-package . 2) (ert-deftest . 2) (should . 2) (should-error . 2) (should-not . 2) (cl-letf . 2) (dolist-with-progress-reporter . 2)) (cl (defun . 2) (defmacro . 2) (defmethod . 2) (defgeneric . 2) (defclass . 2) (defpackage . 2) (defstruct . 2) (define-condition . 2) (defparameter . 2) (defvar . 2) (defconstant . 2) (defsetf . 2) (define-symbol-macro . 2) (let . 2) (let* . 2) (flet . 2) (labels . 2) (macrolet . 2) (symbol-macrolet . 2) (multiple-value-bind . 2) (destructuring-bind . 2) (multiple-value-setq . 2) (multiple-value-prog1 . 2) (multiple-value-list . 2) (with-open-file . 2) (with-slots . 2) (with-accessors . 2) (with-output-to-string . 2) (with-input-from-string . 2) (with-package-iterator . 2) (with-standard-io-syntax . 2) (loop . clauses) (do . 2) (do* . 2) (dolist . 2) (dotimes . 2) (cond . clauses) (case . 2) (ecase . 2) (ccase . 2) (typecase . 2) (etypecase . 2) (ctypecase . 2) (progn . 2) (prog1 . 2) (prog2 . 2) (prog . 2) (prog* . 2) (block . 2) (return-from . 2) (tagbody . 2) (catch . 2) (throw . 2) (unwind-protect . 2) (handler-case . 2) (handler-bind . 2) (restart-case . 2) (restart-bind . 2) (ignore-errors . 2) (when . 2) (unless . 2) (if . 2) (and . 2) (or . 2) (lambda . 2) (function . 2) (quote . 2) (push . 2) (pushnew . 2) (incf . 2) (decf . 2) (assert . 2) (check-type . 2) (eval-when . 2) (locally . 2) (declaim . 2) (declare . 2) (in-package . 2) (use-package . 2) (import . 2) (export . 2)))
(dialect . table).
;;
;; A table rather than a `case' because it is one of the four things a new
;; dialect has to fill in, and `tests/dialects.scm' fails when a dialect in
;; `dialects' has no row here. A dialect whose forms indent like Scheme's says
;; so by pointing at Scheme's table -- that is a decision someone wrote down,
;; not a fallback that happened.
(define dialect-indent-tables
(list (cons 'scheme scheme-indent-rules)
(cons 'racket racket-indent-rules)
(cons 'elisp elisp-indent-rules)
(cons 'cl cl-indent-rules)))
(community dangling)
(define styles '(community dangling))
A Scheme program that says what it uses is a program a reader can read from the top: ‘(import (scheme base) (only (srfi 1) fold))’ names two libraries and, in the second, the one name it wants out of it. Two of sift’s rules are about that sentence – an import nothing uses, and a library no file declares – and both need the same three things: the import forms read as data, the library forms read as data, and the names a file actually mentions.
What is *not* here is as important as what is. sift does not expand a macro, does not resolve a library’s exports beyond the ‘(export ...)’ the library itself writes down, and does not model a library search path. The consequence is written into each rule rather than hidden: a name is called unused only when the file names it (an ‘only’ or ‘rename’ clause), and a library is called missing only when the project declares libraries at all and this one is not among them – a project with no ‘library’ form anywhere has nothing to compare an import against, and the rule says nothing.
Reading the neighbouring files is the one place sift looks outside the text it was handed, and it is deliberate: "does this library exist" is a question about the project, not about the file. The scan is bounded (a depth, a file count and a size per file), sorted, and cached per directory, so two files in one directory pay for it once and the answer does not depend on the order the files were linted in.
#f.
(import ...) forms of ast, in source order.
import form.
(old new) pairs a rename spec writes.
#t when site is a ‘define-module’ clause.
#f.
#f.
only spec names, or '().
#t when name is a library sift cannot be sure about.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Return the data elements of node: no whitespace, no comments.
(define (data-elements node)
"Return the data elements of @var{node}: no whitespace, no comments."
(if (node-list? node)
(filter node-data? (node-elements node))
'()))
Return the (keyword . datum) clauses of a declaration
form.
‘(define-module (foo) #:use-module (srfi srfi-1) #:export (a b))’ is a sequence of keyword clauses with whitespace and comments between them, and the datum a keyword introduces is what the clause is about. A ‘#:’-keyword is a symbol atom with a package marker, which is why this is not a keyword type test.
(define (declaration-clauses form)
"Return the @code{(keyword . datum)} clauses of a declaration @var{form}.
`(define-module (foo) #:use-module (srfi srfi-1) #:export (a b))' is a
sequence of keyword clauses with whitespace and comments between them, and the
datum a keyword introduces is what the clause is about. A `#:'-keyword is a
symbol atom with a package marker, which is why this is not a keyword type test.
"
(let loop ((rest (node-children form)) (out '()))
(cond
[(null? rest) (reverse out)]
[(keyword-node? (car rest))
(let ((argument (first-data (cdr rest))))
(if argument
(loop (memq argument rest) (cons (cons (car rest) argument) out))
(loop (cdr rest) out)))]
[else (loop (cdr rest) out)])))
Return the libraries ast declares, as (key . exports)
pairs.
(define (declared-libraries ast)
"Return the libraries @var{ast} declares, as @code{(key . exports)} pairs."
(map (lambda (form) (cons (library-key (library-name form))
(library-exports form)))
(library-forms ast)))
Return the (start . end) a fix deletes to remove node.
The whitespace *before* the element goes with it, which is what keeps ‘(only (scheme base) car cdr)’ reading as ‘(only (scheme base) cdr)’ when the first name is removed rather than as a form with a double space in it.
(define (deletion-range elements node)
"Return the @code{(start . end)} a fix deletes to remove @var{node}.
The whitespace *before* the element goes with it, which is what keeps
`(only (scheme base) car cdr)' reading as `(only (scheme base) cdr)' when the
first name is removed rather than as a form with a double space in it."
(and elements
(let loop ((rest elements) (previous #f))
(cond
[(null? rest) #f]
[(eq? (car rest) node)
;; the first element has nothing before it, so it takes the space
;; *after* it instead -- otherwise removing it leaves a double space
(if previous
(cons (source-location-index (node-end previous))
(source-location-index (node-end node)))
(cons (source-location-index (node-start node))
(if (pair? (cdr rest))
(source-location-index (node-start (cadr rest)))
(source-location-index (node-end node)))))]
[else (loop (cdr rest) (car rest))]))))
Return the names nodes exports.
‘(export a (rename internal external))’ exports ‘a’ and ‘external’: the name a user of the library writes is the one that counts, which is the second half of a ‘rename’.
(define (export-names-of-nodes nodes)
"Return the names @var{nodes} exports.
`(export a (rename internal external))' exports `a' and `external': the name a
user of the library writes is the one that counts, which is the second half of
a `rename'."
(append-map
(lambda (element)
(cond
[(node-atom? element) (let ((name (element-name element))) (if name (list name) '()))]
[(and (node-list? element) (eq? (node-head-name element) 'rename))
(let ((external (nth-or (data-elements element) 2)))
(let ((name (and external (element-name external))))
(if name (list name) '())))]
[else '()]))
nodes))
Return the ‘define-module’ form of ast, or #f.
(define (file-module ast)
"Return the `define-module' form of @var{ast}, or @code{#f}."
(find (lambda (node) (list-headed-by? node 'define-module))
(filter node-data? ast)))
Return the (import ...) forms of ast, in source order.
An import is written at the top of a program and, in R6RS, inside a
(library ...); both are declarations, and nothing else is: an
import inside a body is a call to somebody’s procedure, not a
claim about what the file uses.
(define (import-forms ast)
"Return the @code{(import ...)} forms of @var{ast}, in source order.
An import is written at the top of a program and, in R6RS, inside a
@code{(library ...)}; both are declarations, and nothing else is: an
@code{import} inside a body is a call to somebody's procedure, not a claim
about what the file uses."
(let* ((top (filter node-data? ast))
(library-imports
(append-map (lambda (form)
(filter (lambda (clause) (list-headed-by? clause 'import))
(form-arguments form)))
(filter (lambda (node)
(memq (and (node-list? node) (node-head-name node))
library-form-heads))
top))))
(append (filter (lambda (node) (list-headed-by? node 'import)) top)
library-imports)))
Return every place ast says what it imports, in source order.
An ‘(import ...)’ form, wherever it is written – at the top of a program or inside an R6RS ‘library’ – and a ‘#:use-module’ clause of a Guile module.
(define (import-sites ast)
"Return every place @var{ast} says what it imports, in source order.
An `(import ...)' form, wherever it is written -- at the top of a program or
inside an R6RS `library' -- and a `#:use-module' clause of a Guile module."
(append (map (lambda (form)
(make-import-site form #f (import-specs form)))
(import-forms ast))
(module-import-sites ast)))
Return the import specs of form, which is an import form.
(define (import-specs form)
"Return the import specs of @var{form}, which is an @code{import} form."
(if (list-headed-by? form 'import) (form-arguments form) '()))
Return the names form exports, as the library itself writes them.
R7RS and R6RS write an ‘(export ...)’ clause; Guile writes ‘#:export (a b)’ and ‘#:re-export (c d)’, which are clauses too, just not lists. A name a library re-exports is on its surface all the same: a file that imports the library can name it.
(define (library-exports form)
"Return the names @var{form} exports, as the library itself writes them.
R7RS and R6RS write an `(export ...)' clause; Guile writes `#:export (a b)'
and `#:re-export (c d)', which are clauses too, just not lists. A name a
library re-exports is on its surface all the same: a file that imports the
library can name it."
(if (list-headed-by? form 'define-module)
(module-exports form)
(append-map (lambda (clause)
(if (and (node-list? clause)
(memq (node-head-name clause) '(export re-export)))
(export-clause-names clause)
'()))
(form-arguments form))))
Return the library forms of ast: R7RS, R6RS and Guile alike.
(define (library-forms ast)
"Return the library forms of @var{ast}: R7RS, R6RS and Guile alike."
(filter (lambda (node)
(memq (and (node-list? node) (node-head-name node))
library-form-heads))
(filter node-data? ast)))
Return the key a library name is looked up by.
(define (library-key name)
"Return the key a library @var{name} is looked up by."
(string-join (map (lambda (part) (or part "")) name) " "))
Return the name a library form declares, as a list of names.
(define (library-name form)
"Return the name a library @var{form} declares, as a list of names."
(let ((spec (car (form-arguments form))))
(if (and spec (node-list? spec))
(map element-name (data-elements spec))
'())))
Return a hash from every symbol ast names to how many times it does.
The plainer cousin of ‘referenced-names‘, and the difference is the whole point of it: ‘referenced-names‘ asks what the *program* uses, so it skips a quote and skips the import forms. This asks whether a name appears at all, because the question it answers is whether a definition is dead – and a name under a quote is a mention a formatter cannot rule out as a use.
(define (mentions ast)
"Return a hash from every symbol @var{ast} names to how many times it does.
The plainer cousin of `referenced-names`, and the difference is the whole
point of it: `referenced-names` asks what the *program* uses, so it skips a
quote and skips the import forms. This asks whether a name appears at all,
because the question it answers is whether a definition is dead -- and a name
under a quote is a mention a formatter cannot rule out as a use."
(let ((counts (make-hash-table)))
(for-each-node
(lambda (node)
(when (and (node-atom? node) (eq? (node-atom-type node) 'symbol))
(let ((name (node-value node)))
(hash-set! counts name (+ 1 (or (hash-ref counts name) 0))))))
ast)
counts))
Return the names a ‘define-module’ form puts in its ‘#:export’ clause.
#f is not the same answer as the empty list: a module that says
‘#:export ()’ has declared that it exports nothing, and a module with no
‘#:export’ clause has not said what it exports at all – a script
exports nothing and is right to.
(define (module-export-clause-names form)
"Return the names a `define-module' @var{form} puts in its `#:export' clause.
@code{#f} is not the same answer as the empty list: a module that says
`#:export ()' has declared that it exports nothing, and a module with no
`#:export' clause has not said what it exports at all -- a script exports
nothing and is right to."
(let ((clause (find (lambda (pair) (eq? (atom-symbol (car pair)) 'export))
(declaration-clauses form))))
(and clause (export-names-of-nodes (data-elements (cdr clause))))))
Return the names a ‘define-module’ form exports, in order.
‘#:export’ and ‘#:re-export’ both put a name on the module’s public surface: the first because the module defines it here, the second because it hands on a name another module defined. Either way a file that imports the module can name it.
(define (module-exports form)
"Return the names a `define-module' @var{form} exports, in order.
`#:export' and `#:re-export' both put a name on the module's public surface:
the first because the module defines it here, the second because it hands on a
name another module defined. Either way a file that imports the module can
name it."
(append-map
(lambda (clause)
(if (memq (atom-symbol (car clause)) (quote (export re-export)))
(export-names-of-nodes (data-elements (cdr clause)))
(quote ())))
(declaration-clauses form)))
Return the libraries declared under directory, cached per directory.
The same directory is scanned once per process, because a lint run asks the same question about every file in it and the answer cannot change while the run is going on.
(define (project-libraries directory)
"Return the libraries declared under @var{directory}, cached per directory.
The same directory is scanned once per process, because a lint run asks the
same question about every file in it and the answer cannot change while the
run is going on."
(if (not directory)
'()
(or (hash-ref scan-cache directory)
(let ((found (libraries-under directory)))
(hash-set! scan-cache directory found)
found))))
Return a hash of every name ast mentions outside its imports.
An import form names the very names it imports, so counting there would call every import used; a quote is data rather than a mention, so it is not entered. A datum comment is code the reader was told not to read. A quasiquote *is* entered, because what it holds is a template and the forms inside it are what the template evaluates (see ‘quoted-node?’).
(define (referenced-names ast)
"Return a hash of every name @var{ast} mentions outside its imports.
An import form names the very names it imports, so counting there would call
every import used; a quote is data rather than a mention, so it is not entered.
A datum comment is code the reader was told not to read. A quasiquote *is*
entered, because what it holds is a template and the forms inside it are what
the template evaluates (see `quoted-node?')."
(let ((names (make-hash-table)))
(define (walk node)
(cond
[(node-datum-comment? node) #f]
[(quoted-node? node) #f]
[(list-headed-by? node 'import) #f]
[(node-atom? node)
(let ((name (element-name node)))
(when (and name (eq? (node-atom-type node) 'symbol))
(hash-set! names name #t)))]
;; a prefix is a parent like any other: what follows a quasiquote or an
;; unquote is where the code is, and a reader that stops at the mark
;; never reaches it
[(node-prefix? node) (let ((child (node-child node))) (when child (walk child)))]
[(node-list? node) (for-each walk (node-children node))]
[(node-conditional? node)
(let ((feature (node-feature node))
(guarded (node-guarded-form node)))
(when feature (walk feature))
(when guarded (walk guarded)))]))
(for-each (lambda (node) (when (node-data? node) (walk node))) ast)
names))
Return the (old new) pairs a rename spec writes.
(define (rename-pair-nodes spec)
"Return the @code{(old new)} pairs a @code{rename} spec writes."
(if (eq? (spec-kind spec) 'rename)
(filter node-list? (cddr (data-elements spec)))
'()))
Return #t when site is a ‘define-module’ clause.
(define (site-clause? site)
"Return @code{#t} when @var{site} is a `define-module' clause."
(and (import-site? site) (import-site-anchor site) #t))
Return what kind of import spec spec is: a wrapper or a library.
(define (spec-kind spec)
"Return what kind of import spec @var{spec} is: a wrapper or a library."
(let ((head (and (node-list? spec) (node-head-name spec))))
(cond
[(memq head import-wrappers) head]
[(and head (node-atom? (node-head spec))) 'library]
[else #f])))
Return the library spec imports, as a list of names, or #f.
(define (spec-library spec)
"Return the library @var{spec} imports, as a list of names, or @code{#f}."
(let ((node (spec-library-node spec)))
(and node (map element-name (data-elements node)))))
Return the node that names the library spec imports, or #f.
The four wrappers all take the library as their first argument, so the answer is the same four times: ‘(only (scheme base) car)’ imports ‘(scheme base)’.
(define (spec-library-node spec)
"Return the node that names the library @var{spec} imports, or @code{#f}.
The four wrappers all take the library as their first argument, so the answer
is the same four times: `(only (scheme base) car)' imports `(scheme base)'."
(case [spec-kind spec]
[(library) spec]
[(only except prefix rename) (car (form-arguments spec))]
[else #f]))
Return the atoms an only spec names, or '().
(define (spec-name-nodes spec)
"Return the atoms an @code{only} spec names, or @code{'()}."
(if (eq? (spec-kind spec) 'only)
(filter node-atom? (cddr (data-elements spec)))
'()))
Undocumented procedure.
(define (used? names name) (and name (hash-ref names name) #t))
Return #t when name is a library sift cannot be sure about.
(define (well-known-library? name)
"Return @code{#t} when @var{name} is a library sift cannot be sure about."
(and (pair? name)
(let ((first (car name)))
(or (member first well-known-namespaces)
;; `(scheme base)' names its namespace twice; a single-component name
;; such as `(srfi-1)' is a namespace too.
(any (lambda (part) (member part well-known-namespaces)) name)
(and (string-prefix? "srfi" first) #t)))))
A jump is a question asked of a project, and reading a project is work an editor cannot wait for. So the two are separated here: this module reads the tree, parses the files and publishes an index, and nothing that answers a request ever reads a directory or a file to do it.
What makes that safe is that an index is a value. A scan builds the next one beside the one in use and publishes it with a single atomic store, so a reader holds a complete index for as long as it needs it, a writer never mutates what a reader can see, and neither waits for the other. A file that is saved is one entry replaced and a name table rebuilt – not the project read again – and a keystroke never asks for either.
One thread per workspace owns all of it: the queue of one-file refreshes and the occasional full rescan go through the same thread in order, which is what keeps two scans from publishing over each other. The state a request can read without the queue is the same shape as the index – an atomic value – and it is the state an editor is told about: uninitialized, scanning the tree, indexing ‘done’ of ‘total’ files, ready.
The cache is what makes a second session cheap: a file whose size and modification time have not changed keeps the names it defined and is not read until a request needs its text. A cache that cannot be read is no cache at all, which is slower and never wrong.
#f.
Return the Lisp files under root, at most ‘index-file-limit’ of them.
Directories a build leaves behind are skipped rather than walked: ‘.git’ alone holds more files than most source trees, and reading it would make the first definition request slower than finding the file by hand.
(define* (files-under root #:optional (filter #f))
"Return the Lisp files under @var{root}, at most `index-file-limit' of them.
Directories a build leaves behind are skipped rather than walked: `.git'
alone holds more files than most source trees, and reading it would make the
first definition request slower than finding the file by hand."
(let loop ((pending (list root)) (found '()) (count 0))
(cond
[(or (null? pending) (>= count index-file-limit)) (reverse found)]
[else
(let* ((dir (car pending))
(entries (or (false-if-exception (scandir dir)) '()))
(subdirectories '())
(files '()))
(for-each
(lambda (name)
(unless (or (member name skipped-directories)
(string-prefix? "." name))
(let ((path (string-append dir "/" name)))
(cond
[(directory? path) (set! subdirectories (cons path subdirectories))]
[(indexable-file? filter path root)
(set! files (cons path files))]))))
entries)
(loop (append subdirectories (cdr pending))
(append files found)
(+ count (length files))))])))
Return path as a fully read ‘indexed-file’, or #f.
(define (index-file path)
"Return @var{path} as a fully read `indexed-file', or @code{#f}."
(let ((dialect (detect-dialect #:file path))
(text (read-file-text path index-byte-limit)))
(and dialect text
(let ((definitions (parse-file-text text dialect path)))
(make-indexed-file path text dialect definitions
(top-level-names definitions))))))
Drop the index and read the project again, for a changed configuration.
(define (index-forget! workspace) "Drop the index and read the project again, for a changed configuration." (publish-workspace-index! workspace empty-index 'scanning 0 0) (notify! workspace 'scanning 0 0) (index-rescan! workspace))
Ask for path to be read again, in the indexer’s own thread.
(define (index-refresh! workspace path)
"Ask for @var{path} to be read again, in the indexer's own thread."
(enqueue! (ensure-worker! workspace) (list 'refresh path)))
Ask for the project to be read again, once per request.
(define (index-rescan! workspace)
"Ask for the project to be read again, once per request."
(let ((worker (ensure-worker! workspace)))
(unless (atomic-box-ref (worker-scan-requested? worker))
(atomic-box-set! (worker-scan-requested? worker) #t)
(enqueue! worker '(scan)))))
Start workspace’s indexer and ask it to read the project.
The thread is started once and then lives as long as the session; every
later request for an index is one job on its queue. notify is
called with (status done total) whenever the state changes.
(define* (index-start! workspace #:key (notify #f))
"Start @var{workspace}'s indexer and ask it to read the project.
The thread is started once and then lives as long as the session; every later
request for an index is one job on its queue. @var{notify} is called with
@code{(status done total)} whenever the state changes."
(let ((worker (ensure-worker! workspace)))
(when notify
(atomic-box-set! (worker-notify worker) notify))
(unless (worker-thread worker)
(set-worker-thread! worker
(call-with-new-thread
(lambda () (indexer-loop workspace)))))
(index-rescan! workspace)
*unspecified*))
Stop the indexer and wait for it, so an exit does not lose a write.
(define (index-stop! workspace)
"Stop the indexer and wait for it, so an exit does not lose a write."
(let ((worker (workspace-worker workspace)))
(when (and worker (worker-thread worker))
(atomic-box-set! (worker-stop? worker) #t)
(enqueue! worker '(stop))
(catch #t
(lambda () (join-thread (worker-thread worker)))
(lambda (key . arguments) #f))
(set-worker-thread! worker #f)))
*unspecified*)
The JSON a language server speaks, read and written here rather than borrowed: sift depends on Guile and nothing else, and ‘(json)’ is another package to install before a formatter will start.
The two shapes that a Lisp does not have are the two that matter:
an object is ‘(object ("key" . value) ...)‘, in the order written an array is a vector, so ‘(vector)‘ is the empty one
A pair whose car is ‘object’ cannot be confused with an array, an empty object cannot be confused with an empty array, and the order of a JSON object survives the round trip – which is what a caller comparing two documents needs, since a hash table promises nothing about order.
‘null’, ‘true’ and ‘false’ are the symbols ‘null’, ‘true’ and ‘false’, so that ‘#f’ means what it means in Scheme and a JSON ‘false’ is not the absence of a value.
#t when value is a JSON array.
#t when value is a JSON object.
#f.
Return #t when value is a JSON array.
(define (json-array? value)
"Return @code{#t} when @var{value} is a JSON array."
(vector? value))
Return the (name . value) pairs of a JSON object, in order.
(define (json-fields value)
"Return the @code{(name . value)} pairs of a JSON object, in order."
(and (json-object? value) (cdr value)))
Return the member name of object, or the optional default.
This is ‘json-ref’ with the argument order a fold or a ‘map’ wants.
(define (json-get name object . rest)
"Return the member @var{name} of @var{object}, or the optional default.
This is `json-ref' with the argument order a fold or a `map' wants."
(apply json-ref object name rest))
Undocumented procedure.
(define (json-null? value) (eq? value json-null))
Return number the way JSON wants to read it back.
An exact integer is written as itself, and anything else through ‘~f’ with enough digits to be read back as the same number.
(define (json-number->string number)
"Return @var{number} the way JSON wants to read it back.
An exact integer is written as itself, and anything else through `~f' with
enough digits to be read back as the same number."
(cond
[(exact-integer? number) (number->string number)]
[(and (real? number)
(let ((as-float (exact->inexact number)))
(or (not (= as-float as-float)) ; NaN
(= (abs as-float) (/ 1.0 0.0))))) ; infinity
"null"]
[else
(let ((text (format #f "~f" number)))
(if (string-find text ".")
(string-trim-right (string-trim-right text #\0) #\.)
text))]))
Return a JSON object of fields, (name . value) pairs.
(define (json-object . fields)
"Return a JSON object of @var{fields}, @code{(name . value)} pairs."
(cons json-object-tag fields))
Return #t when value is a JSON object.
(define (json-object? value)
"Return @code{#t} when @var{value} is a JSON object."
(and (pair? value) (eq? (car value) json-object-tag)))
Return the value text holds.
A syntax error is raised as (throw 'sift-json-error (path line
column message)), the same shape the configuration reader uses for its
own errors, so that the caller can say where the bad message came from.
(define* (json-read text #:key (path "json"))
"Return the value @var{text} holds.
A syntax error is raised as @code{(throw 'sift-json-error (path line column
message))}, the same shape the configuration reader uses for its own errors,
so that the caller can say where the bad message came from."
(let ((in (%make-input text 0)))
(let ((value (read-value in)))
(skip-space! in)
(unless (>= (input-index in) (string-length text))
(fail! in path "trailing text after the value"))
value)))
Return the member name of object, or the optional default.
The name is a string, the way JSON writes it; a symbol is accepted too, because a caller writing a request by hand has no reason to type quotes.
(define (json-ref object name . rest)
"Return the member @var{name} of @var{object}, or the optional default.
The name is a string, the way JSON writes it; a symbol is accepted too,
because a caller writing a request by hand has no reason to type quotes."
(let ((key (if (symbol? name) (symbol->string name) name))
(default (if (pair? rest) (car rest) #f)))
(let ((entry (and (json-object? object)
(assoc key (cdr object)))))
(if entry (cdr entry) default))))
Return the member at names, a path of keys, or #f.
(define (json-ref-path object . names)
"Return the member at @var{names}, a path of keys, or @code{#f}."
(fold (lambda (name value) (json-ref value name)) object names))
Return value as a JSON document, without a trailing newline.
(define (json-write value)
"Return @var{value} as a JSON document, without a trailing newline."
(let ((out (open-output-string)))
(write-value value out)
(get-output-string out)))
The driver reads a file once, runs the applicable checkers over the AST, folds in what the reader found, applies the suppression comments, sorts the result and – only when asked – applies the fixes.
Two rules from the manual are enforced here rather than trusted to each checker. Nothing is reported about a datum comment or inside a form the reader marked opaque, because the walk the checkers use does not enter them. And no fix is applied unless the source still reads afterwards: a fix that introduces a parse error is discarded, along with every other fix of the same run, and the original warnings are reported unfixed.
The pipeline, from one file’s text to the warnings a caller is given:
Mermaid diagram, as source:
flowchart TD
subgraph read ["read and check"]
direction LR
source(["> source text"]) --> reader["read-source · AST"]
reader --> applicable["checkers for the dialect"]
applicable --> warnings["warnings"]
reader -.->|parse errors| warnings
end
subgraph report ["report and fix"]
direction LR
filtered["suppress · threshold · sort"]
filtered --> fix["apply-fixes, on request"]
fix --> reread{"still reads?"}
reread -->|yes| fixed["fixed source"]
reread -->|no| unfixed["original warnings"]
end
read --> report
%% dokgen-mermaid
Code:
#f.
lint-source.
#t when severity is at or above minimum.
#t when warning is silenced by a directive comment.
Return every checker sift ships, sorted by name.
The order is sorted rather than written down, so ‘list-checkers’ and any other report over the whole set cannot drift from the set itself.
(define (all-checkers)
"Return every checker sift ships, sorted by name.
The order is sorted rather than written down, so `list-checkers' and any
other report over the whole set cannot drift from the set itself."
(sort (append whitespace-checkers
comments-checkers
parens-checkers
bodies-checkers
scheme-checkers
elisp-checkers
cl-checkers
ergonomics-checkers
naming-checkers
simplify-checkers
sxml-checkers
practices-checkers
guix-checkers
inference-checkers)
(lambda (a b)
(string<? (symbol->string (lint-checker-name a))
(symbol->string (lint-checker-name b))))))
Return source with every fix applied, or source unchanged.
Fixes are applied from the highest offset down, so that a fix does not move the text a later one was measured against. After applying them the source is read again: a fix that introduces a parse error the file did not have before is not worth the change, so all of them are discarded together and the caller reports the original warnings.
(define* (apply-fixes source warnings)
"Return @var{source} with every fix applied, or @var{source} unchanged.
Fixes are applied from the highest offset down, so that a fix does not move
the text a later one was measured against. After applying them the source
is read again: a fix that introduces a parse error the file did not have
before is not worth the change, so all of them are discarded together and
the caller reports the original warnings."
(let* ((fixes (sort (fixable-warnings warnings)
(lambda (a b)
(> (car (lint-warning-range a))
(car (lint-warning-range b))))))
(fixed
(fold (lambda (warning text)
(let* ((range (lint-warning-range warning))
(start (car range))
(end (cdr range))
(replacement ((lint-warning-fix warning)
source start end)))
(string-append (substring text 0 start)
replacement
(substring text end))))
source
fixes)))
(if (and (not (string=? fixed source))
(fix-introduces-error? source fixed))
source
fixed)))
Return the checkers to run for dialect.
include, when given, is the list of names to run; exclude is a list of names to skip. Selecting a checker that does not apply to the dialect is not an error – it simply runs nothing for that dialect.
(define* (checkers-applicable? dialect #:key (include #f) (exclude '()))
"Return the checkers to run for @var{dialect}.
@var{include}, when given, is the list of names to run; @var{exclude} is a
list of names to skip. Selecting a checker that does not apply to the
dialect is not an error -- it simply runs nothing for that dialect."
(let* ((available (checkers-for-dialect dialect))
(selected (if include
;; a name that does not apply to the dialect selects
;; nothing, which is what the docstring promises
(filter (lambda (checker)
(and (memq (lint-checker-name checker) include)
(lint-checker-for-dialect? checker dialect)))
(all-checkers))
available))
(excluded (map normalise-checker-name (or exclude '()))))
(remove (lambda (checker)
(memq (lint-checker-name checker) excluded))
selected)))
Return the checkers named by names; unknown names are dropped.
(define* (checkers-by-name names)
"Return the checkers named by @var{names}; unknown names are dropped."
(filter-map find-checker names))
Return the checkers that apply to dialect.
(define (checkers-for-dialect dialect)
"Return the checkers that apply to @var{dialect}."
(filter (lambda (checker) (lint-checker-for-dialect? checker dialect))
(all-checkers)))
Return the checker named name, or #f.
(define* (find-checker name)
"Return the checker named @var{name}, or @code{#f}."
(let ((wanted (normalise-checker-name name)))
(find (lambda (checker) (eq? (lint-checker-name checker) wanted))
(all-checkers))))
Lint the file at path and return the warnings, sorted.
(define* (lint-file path #:key (dialect #f) (checkers #f)
(exclude-checkers '()) (severity 'info) (options '()))
"Lint the file at @var{path} and return the warnings, sorted."
(let* ((source (call-with-input-file path get-string-all))
(dialect* (or dialect
(detect-dialect #:file path #:source source)
'scheme)))
(lint-source source #:dialect dialect* #:file path
#:checkers checkers #:exclude-checkers exclude-checkers
#:severity severity #:options options)))
Lint every file in paths, returning one list of warnings.
The warnings of the whole run are sorted together, so the report reads in file order and a pipeline can compare runs line by line.
The files are linted in parallel, because nothing one file says is anything another file reads, and the answer is sorted anyway – which is what lets the whole thing be spread over the processors without changing a byte of it.
(define* (lint-files paths #:key (dialect #f) (checkers #f)
(exclude-checkers '()) (severity 'info) (options '()))
"Lint every file in @var{paths}, returning one list of warnings.
The warnings of the whole run are sorted together, so the report reads in
file order and a pipeline can compare runs line by line.
The files are linted in parallel, because nothing one file says is anything
another file reads, and the answer is sorted anyway -- which is what lets the
whole thing be spread over the processors without changing a byte of it."
(sort (apply append
(map-ordered
(lambda (path)
(lint-file path #:dialect dialect
#:checkers checkers
#:exclude-checkers exclude-checkers
#:severity severity #:options options))
paths))
lint-warning<?))
Lint source and return the warnings, sorted.
checkers selects the checkers to run; exclude-checkers
removes some; severity is the minimum severity to report.
options is the alist a checker sees through option – the
line limit, the indentation width, the LOOP keyword style.
(define* (lint-source source #:key (dialect 'scheme) (file #f)
(checkers #f) (exclude-checkers '()) (severity 'info)
(options '()))
"Lint @var{source} and return the warnings, sorted.
@var{checkers} selects the checkers to run; @var{exclude-checkers} removes
some; @var{severity} is the minimum severity to report. @var{options} is
the alist a checker sees through @code{option} -- the line limit, the
indentation width, the LOOP keyword style."
(call-with-values
(lambda () (read-source #:source source #:dialect dialect #:file file))
(lambda (ast parse-errors)
(let* ((selected (checkers-applicable? dialect
#:include checkers
#:exclude exclude-checkers))
(produced
(append
(filter (lambda (warning) (not (reader-warning-covered? warning)))
parse-errors)
(append-map
(lambda (checker)
(with-check-options
options
(lambda ()
((lint-checker-proc checker) ast source dialect))))
selected)))
(with-file
(map (lambda (warning)
(let ((location (lint-warning-location warning)))
(if (or (not file) (source-location-file location))
warning
(make-lint-warning
(lint-warning-checker warning)
(lint-warning-severity warning)
(lint-warning-message warning)
(make-source-location file
(source-location-line location)
(source-location-column location)
(source-location-offset location)
(source-location-index location))
(lint-warning-fix warning)
(lint-warning-range warning)))))
produced)))
(call-with-values (lambda () (suppression-intervals ast))
(lambda (intervals next-lines)
(sort (filter (lambda (warning)
(and (severity-at-least? (lint-warning-severity warning)
severity)
(not (suppressed? warning
#:intervals intervals
#:next-lines next-lines))))
with-file)
lint-warning<?)))))))
Lint source as text; a convenience over lint-source.
(define* (lint-string source #:key (dialect 'scheme)
(checkers #f) (exclude-checkers '())
(severity 'info) (options '())
#:allow-other-keys)
"Lint @var{source} as text; a convenience over @code{lint-source}."
(lint-source source #:dialect dialect #:checkers checkers
#:exclude-checkers exclude-checkers #:severity severity
#:options options))
Return name as a symbol, whatever way it was spelled on the command line.
(define (normalise-checker-name name)
"Return @var{name} as a symbol, whatever way it was spelled on the command line."
(cond [(symbol? name) name]
[(string? name) (string->symbol name)]
[else (string->symbol (format #f "~a" name))]))
Return #t when severity is at or above minimum.
(define (severity-at-least? severity minimum)
"Return @code{#t} when @var{severity} is at or above @var{minimum}."
(>= (severity-rank severity) (severity-rank minimum)))
Return #t when warning is silenced by a directive comment.
(define* (suppressed? warning #:key intervals next-lines)
"Return @code{#t} when @var{warning} is silenced by a directive comment."
(let* ((location (lint-warning-location warning))
(checker (lint-warning-checker warning))
(line (source-location-line location))
(index (source-location-index location)))
(or (any (lambda (entry)
(and (checkers-match? (second entry) checker)
(>= index (second entry))
(<= index (third entry))))
intervals)
(any (lambda (entry)
(and (= line (first entry))
(checkers-match? (second entry) checker)))
next-lines))))
Return the suppression directives in ast, in document order.
Each directive is a list of the kind, the checker names it names (empty for all of them) and the line it sits on.
(define (suppression-directives ast)
"Return the suppression directives in @var{ast}, in document order.
Each directive is a list of the kind, the checker names it names (empty for
all of them) and the line it sits on."
(let ((directives '()))
(define (walk node)
(cond
[(node-list? node) (for-each walk (node-children node))]
[(node-prefix? node) (let ((child (node-child node)))
(when child (walk child)))]
[(node-comment? node)
(let ((directive (parse-directive (node-value node))))
(when directive
(set! directives
(cons (list (car directive)
(cdr directive)
(source-location-line (node-start node))
(source-location-index (node-start node)))
directives))))]))
(for-each walk ast)
(reverse directives)))
A language server that speaks JSON-RPC on standard input and output, which is what makes one integration possible instead of four: Eglot in Emacs, ‘vim.lsp’ in Neovim and any LSP client in VS Code all speak this, so the findings and the fixes are written once, here, and each editor only has to start the process.
What it does is what sift already does, moved to where an editor can reach it:
textDocument/didOpen, didChange lint the buffer, publish the findings textDocument/didSave re-read the project, check it all again workspace/didChangeWatchedFiles the same, for a file nobody has open workspace/didChangeConfiguration read the settings again, check again workspace/willRenameFiles rename the module a file names, and its imports workspace/didRenameFiles re-read the renamed file textDocument/codeAction each finding’s fix, fix-all, format this definition textDocument/formatting format the buffer textDocument/hover a symbol’s definition, or the rule under it textDocument/definition the definition a symbol names textDocument/references every mention of it in the project textDocument/documentHighlight the mentions in this buffer textDocument/documentSymbol the outline of the buffer workspace/symbol search those outlines textDocument/completion the names the project defines textDocument/inlayHint a parameter’s name beside its argument textDocument/prepareRename whether a symbol can be renamed here textDocument/rename rename it, by name, in the project
The navigation requests are answered from the same tree the linter reads, with ‘(sift definitions)’ resolving what is in scope at the cursor: a parameter, a ‘let’ variable, an internal definition, and then the file and the rest of the workspace, in that order. A name is matched as a name, per dialect – no macro is expanded, no module import is followed – which is the same promise the linter makes, and the manual says so where it lists what the server answers.
What it does not do is as deliberate: no signature help, no type hierarchy, no hover that guesses at a type. A server that answered every request an editor can make would be a server that lies about half of them.
Everything the server answers is configurable, in the same place as the rest of sift: ‘inlay-hints’ (which kinds of hint, or none), ‘hover’ and ‘completion’ are settings like ‘line-length’ is, so a project can set them in its ‘sift.yaml’. They can also be set by the editor itself – ‘initializationOptions’ when the session starts, and ‘eglot-workspace-configuration’ or a ‘settings.json’ through ‘workspace/didChangeConfiguration’ – and those settings are read by the same validator and layered over the files, because what the editor says is the most specific thing anyone can say about this session.
Documents are kept whole and replaced whole (‘change: 1’ in the sync options). An incremental edit would mean patching a string by character offsets that the editor computed in UTF-16, and the formatter’s promise – read everything, write everything back – is only kept if the text it reads is the text the editor has.
A finding is a function of the text *and of the project*, and most of what this server does is arranged around that: a save and a watched file refresh the index that jumps and references read, a changed configuration is read again and every open buffer is re-checked against it, and the findings of every open buffer – not only the one that changed – go out again, because a finding can name a definition in a file nobody is looking at. What the server asks of the client is the half of that it cannot do alone: ‘openClose’, a full ‘change’, and ‘save’, which is the news that the file on disk is the buffer.
It also says what it is doing, over ‘window/logMessage’: the root it serves, the dialect each buffer is read as, the findings each report carries, and every re-read it was asked for. Eglot shows those lines in the *EGLOT events* buffer, and without them "nothing to report" and "not running" look exactly alike.
(values edits refusal) for formatting text.
Return the code actions that apply to start..end of text.
The answers, in the order an editor should show them: the fixes for the findings under the cursor, the extractions sift can make without being told what to call anything, the one rewrite it can make, and the source actions – fix everything, the two import operations, and organize imports. only is the request’s ‘context.only’, so a client that asked for ‘source’ gets the source actions and nothing else.
(define* (lsp-code-actions config text start end #:key (dialect 'scheme)
(uri #f) (version #f) (only '()))
"Return the code actions that apply to @var{start}..@var{end} of @var{text}.
The answers, in the order an editor should show them: the fixes for the
findings under the cursor, the extractions sift can make without being told
what to call anything, the one rewrite it can make, and the source actions --
fix everything, the two import operations, and organize imports. @var{only}
is the request's `context.only', so a client that asked for `source' gets the
source actions and nothing else."
(let* ((warnings (warnings-for config text #:dialect dialect #:uri uri))
(quickfixes
(filter-map
(lambda (warning)
(and (lint-warning-fix warning)
(lint-warning-range warning)
(code-action-of warning text (or uri "") version)))
(select-warnings warnings start end text)))
(extractions
(and (only-accepts? only "refactor.extract")
(extract-actions text dialect start end
#:uri (or uri "") #:version version)))
(inlines
(and (only-accepts? only "refactor.inline")
(inline-actions text dialect start end
#:uri (or uri "") #:version version)))
(rewrite
(and (only-accepts? only "refactor.rewrite")
(format-form-action config text (ast-of-text text dialect) start
#:dialect dialect #:uri uri #:version version)))
(fix-all
(and (only-accepts? only "source.fixAll")
(fix-all-action config text #:dialect dialect #:uri uri
#:version version)))
(optimize
(and (only-accepts? only "source.optimizeImports.sift")
(optimize-imports-action config text #:dialect dialect #:uri uri
#:version version)))
(sort
(and (only-accepts? only "source.sortImports.sift")
(sort-imports-action config text #:dialect dialect #:uri uri
#:version version)))
(organize
;; The standard "organize imports" is the answer to a request that
;; named it, or to a client that asked for the `source' family. A
;; request with no preference gets the two actions a reader can tell
;; apart, not that pair again under a third name.
(and (pair? only)
(only-accepts? only "source.organizeImports")
(organize-imports-action config text #:dialect dialect #:uri uri
#:version version))))
(list->vector
(append
(if (only-accepts? only "quickfix") quickfixes '())
(or extractions '())
(or inlines '())
(if rewrite (list rewrite) '())
(if optimize (list optimize) '())
(if sort (list sort) '())
(if organize (list organize) '())
(if fix-all (list fix-all) '())))))
Return the locations the symbol at index is defined at, as an array.
Return the diagnostics for text, as the array an editor expects.
(define* (lsp-diagnostics config text #:key (dialect 'scheme) (uri #f))
"Return the diagnostics for @var{text}, as the array an editor expects."
(list->vector
(map (lambda (warning) (diagnostic-of warning text))
(warnings-for config text #:dialect dialect #:uri uri))))
Return the outline of text: every definition, nested.
Return (values edits refusal) for formatting text.
edits is the array an editor applies, empty when the text is already formatted. refusal is a sentence when sift could not format at all – a buffer with a parse error is left alone, because the formatter never guesses where a delimiter goes – and the server shows it, so that a Format Document which did nothing has a reason attached.
Every other answer here is computed from a buffer sift can read the *whole* of or not at all; a half-written form is the normal state of a buffer being typed, and the findings for the part that could be read are still reported.
(define* (lsp-formatting config text #:key (dialect 'scheme) (uri #f))
"Return @code{(values edits refusal)} for formatting @var{text}.
@var{edits} is the array an editor applies, empty when the text is already
formatted. @var{refusal} is a sentence when sift could not format at all --
a buffer with a parse error is left alone, because the formatter never guesses
where a delimiter goes -- and the server shows it, so that a Format Document
which did nothing has a reason attached.
Every other answer here is computed from a buffer sift can read the *whole* of
or not at all; a half-written form is the normal state of a buffer being
typed, and the findings for the part that could be read are still reported."
(call-with-values (lambda () (format-text config text #:dialect dialect
#:uri uri))
(lambda (formatted errors)
(cond
[(pair? errors)
(values (vector)
(format #f "sift cannot format this buffer: ~a"
(lint-warning-message (car errors))))]
[(string=? formatted text) (values (vector) #f)]
[else
(values
(vector
(json-object
(field "range"
(json-range text (car (document-range text))
(cdr (document-range text))))
(field "newText" formatted)))
#f)]))))
Return every location in the project that mentions the symbol at index.
A name bound by a form is not a name the project has: ‘(let ((x 1)) x)’ makes an ‘x’ that has nothing to do with the ‘x’ of the file next door, and answering with every ‘x’ in the project would be answering a question nobody asked. So a mention of a binding is looked for inside the form that binds it, and a mention of anything else is looked for in the project, which is where a definition lives.
Serve one editor until it says ‘exit’.
in and out are the binary ports of the conversation, standard input and standard output by default.
reload is a thunk that returns the configuration as the project’s
files now describe it, or #f when they cannot be read. It is
called when the editor says the settings changed and when a watched
configuration file is saved; a server started without one keeps the
configuration it was given and says so rather than pretending to have
re-read it.
The return value is the status the protocol asks for: 0 when the editor said ‘exit‘ after a ‘shutdown‘, 1 when it said ‘exit‘ without one, and 0 when the input simply ended, because a closed pipe is an editor that closed the file rather than a server that failed.
What it never does is stop on a bad message. A frame that is not JSON is answered with -32700 and the loop continues, and a handler that raises is answered with -32603 and the loop continues: a server that dies on one request makes the next one impossible, and the editor shows a dead server where it should show a finding.
(define* (lsp-serve config #:key (in #f) (out #f) (reload #f))
"Serve one editor until it says `exit'.
@var{in} and @var{out} are the binary ports of the conversation, standard
input and standard output by default.
@var{reload} is a thunk that returns the configuration as the project's files
now describe it, or @code{#f} when they cannot be read. It is called when the
editor says the settings changed and when a watched configuration file is
saved; a server started without one keeps the configuration it was given and
says so rather than pretending to have re-read it.
The return value is the status the protocol asks for: 0 when the editor said
`exit` after a `shutdown`, 1 when it said `exit` without one, and 0 when the
input simply ended, because a closed pipe is an editor that closed the file
rather than a server that failed.
What it never does is stop on a bad message. A frame that is not JSON is
answered with -32700 and the loop continues, and a handler that raises is
answered with -32603 and the loop continues: a server that dies on one request
makes the next one impossible, and the editor shows a dead server where it
should show a finding."
(let ((port-in (or in (current-input-port)))
(port-out (or out (current-output-port)))
(documents (make-hash-table))
;; The workspace is given the globs the project configured; `(sift
;; index)' fills it in a thread of its own once a root is known, and a
;; workspace with no root answers about the open buffers alone.
(workspace (new-workspace (and config (config-ref config 'file-filter))))
(session (new-session #:config config #:reload reload)))
;; The one thread that checks buffers, so the loop that reads messages is
;; never the loop that computes a finding.
(set-lint-queue-thread!
(session-queue session)
(call-with-new-thread
(lambda () (lint-loop session workspace port-out documents))))
(let loop ((status 0))
(flush-deep-results! port-out documents)
(let ((frame (read-message port-in)))
(cond
[(not frame) (finish! port-out status documents session workspace)]
[(eq? (car frame) 'malformed)
;; The id of a message that could not be parsed is not known, and
;; the protocol says to answer with null.
(reply-error! port-out json-null -32700 (cdr frame))
(loop status)]
[else
(let ((outcome (serve-one session workspace documents
(cdr frame) port-out)))
(if (eq? outcome 'exit)
(finish! port-out (if (session-shutdown? session) 0 1)
documents session workspace)
(loop status)))])))))
Return text with every import form’s specs sorted.
Both shapes a Scheme file uses are read: a top-level (import ...)
form – wherever it is written, including inside a ‘library’ body – and
the #:use-module clauses of a define-module. The
specifications are permuted in place, so a form written on one line
stays on one line and a form written one spec per line keeps its
indentation.
(define (organize-imports-text text dialect)
"Return @var{text} with every import form's specs sorted.
Both shapes a Scheme file uses are read: a top-level @code{(import ...)} form
-- wherever it is written, including inside a `library' body -- and the
@code{#:use-module} clauses of a @code{define-module}. The specifications are
permuted in place, so a form written on one line stays on one line and a form
written one spec per line keeps its indentation."
(let* ((ast (ast-of-text text dialect))
(top (filter node-data? ast))
(forms (filter (lambda (form) (memq form top)) (import-forms ast)))
(modules (filter (lambda (form)
(eq? (node-head-name form) 'define-module))
top))
(edits
(append
(append-map
(lambda (form)
(let ((specs (form-arguments form)))
(if (null? specs)
;; an import left with nothing in it is removed rather than
;; written as `(import)', which no Scheme reads
(list (list (form-start form)
(import-line-end text (form-end form))
""))
(list (list (form-start form) (form-end form)
(organize-import-form text form specs))))))
forms)
(append-map (lambda (form) (module-import-edits text form))
modules))))
(replace-spans text edits)))
A run over a project is a run over one file at a time, and the files do not know about each other: nothing a checker reads in one file is anything it reads in another. That is exactly the shape ‘map-ordered’ takes.
Two things are promised here and are what make it safe to use:
* the answers come back in the order the work was given, so a parallel run prints the same bytes as a sequential one, and * an error is re-raised in the caller’s thread, in that order, so a caller’s ‘catch’ reads the same either way.
Guile’s threads are real threads in Guile 3, and the garbage collector stops them all – so a lint that allocates less also parallelises better, which is the other reason the allocation numbers in the benchmarks are worth keeping an eye on.
Call proc on every item of items, in parallel, discarding answers.
(define* (for-each-in-order proc items #:key (count #f))
"Call @var{proc} on every item of @var{items}, in parallel, discarding answers."
(map-ordered proc items #:count count)
*unspecified*)
Apply proc to every item of items, answering in order.
The items are handed out one at a time from a shared counter, so a list of one large file and twenty small ones takes as long as the workers can make it rather than as long as the slowest bucket would have; and the answers are collected by index, so the order is the order they were given in.
With one item, one processor, or count of one, the work is done in the calling thread: a thread that exists to be joined is a promise to be kept for nothing.
(define* (map-ordered proc items #:key (count #f))
"Apply @var{proc} to every item of @var{items}, answering in order.
The items are handed out one at a time from a shared counter, so a list of one
large file and twenty small ones takes as long as the workers can make it
rather than as long as the slowest bucket would have; and the answers are
collected by index, so the order is the order they were given in.
With one item, one processor, or @var{count} of one, the work is done in the
calling thread: a thread that exists to be joined is a promise to be kept for
nothing."
(let* ((items (list->vector items))
(total (vector-length items))
(count (or count (worker-count total))))
(cond
[(or (<= count 1) (<= total 1))
(let loop ((i 0) (out '()))
(if (>= i total)
(reverse! out)
(loop (+ i 1) (cons (proc (vector-ref items i)) out))))]
[else
(let* ((count (min count total))
(results (make-vector total #f))
(next (vector 0))
(lock (make-mutex))
(take!
(lambda ()
"Return the next unclaimed index, or @code{#f} when there is none."
(lock-mutex lock)
(let ((i (vector-ref next 0)))
(if (>= i total)
(begin (unlock-mutex lock) #f)
(begin (vector-set! next 0 (+ i 1))
(unlock-mutex lock)
i)))))
(run
(lambda ()
(let loop ()
(let ((i (take!)))
(when i
(vector-set! results i
(catch #t
(lambda ()
(cons 'answered
(proc (vector-ref items i))))
(lambda (key . args)
(cons 'raised (cons key args)))))
(loop))))))
(threads (map (lambda (ignored) (call-with-new-thread run))
(iota count))))
(for-each join-thread threads)
(let loop ((i 0) (out '()))
(if (>= i total)
(reverse! out)
(let ((result (vector-ref results i)))
(unless result
(error "sift: an item was never taken by a worker" i))
(case [car result]
[(answered) (loop (+ i 1) (cons (cdr result) out))]
[else (apply throw (cdr result))])))))])))
Return how many processors this run may use, at least one.
(define (processor-count) "Return how many processors this run may use, at least one." (max 1 (or (current-processor-count) 1)))
Return how many threads to use for total items.
‘SIFT_JOBS’ overrides the count, which is what makes a parallel run comparable with a sequential one: ‘SIFT_JOBS=1 sift ci .’ does the same work in the same order on one thread, so a difference in the output is a bug and not a guess.
More workers than items is a thread that takes no work and still has to be joined, and a machine with more processors than a run has files does not need all of them: the work here is a few hundred milliseconds, and the point is to stop waiting, not to saturate a machine.
The variable is read with ‘get-environment-variable’ rather than Guile’s
‘getenv’, because one of the two is R7RS and therefore available
wherever sift is built, and a build with no environment at all answers
#f to it – which is the same answer as "unset", and the right
one.
(define (worker-count total)
"Return how many threads to use for @var{total} items.
`SIFT_JOBS' overrides the count, which is what makes a parallel run
comparable with a sequential one: `SIFT_JOBS=1 sift ci .' does the same work in
the same order on one thread, so a difference in the output is a bug and not a
guess.
More workers than items is a thread that takes no work and still has to be
joined, and a machine with more processors than a run has files does not need
all of them: the work here is a few hundred milliseconds, and the point is to
stop waiting, not to saturate a machine.
The variable is read with `get-environment-variable' rather than Guile's
`getenv', because one of the two is R7RS and therefore available wherever sift
is built, and a build with no environment at all answers @code{#f} to it --
which is the same answer as \"unset\", and the right one."
(or (and (get-environment-variable "SIFT_JOBS")
(let ((n (string->number (get-environment-variable "SIFT_JOBS"))))
(and n (exact? n) (> n 0) (inexact->exact n))))
(max 1 (min total (processor-count)))))
A hand-written, dialect-aware, location-preserving reader.
Guile’s ‘read’ is not used anywhere in sift, and cannot be: it drops comments, keeps no locations, and has no way to represent a block comment, a datum comment or a reader prefix as a node of its own. Everything the formatter must put back – every comment, every blank line, every "’" – is therefore read here into a node that carries its source span.
The reader is permissive. A malformed file produces nodes for the part it could read plus a list of parse errors; it never aborts a file because one form in it is broken, and it never guesses at a missing delimiter.
Whitespace is read as nodes too, and split in two: a run of spaces and tabs becomes one whitespace node, and a run of newlines becomes another one carrying the count. That split is what lets the formatter preserve blank lines and decide which comments are inline.
#f.
#f.
read-source for tests.
Render ast back to source text, byte for byte.
The reader and this function are inverses: every comment, every blank line and every reader prefix in the input is in the output, in the same place.
(define (ast->text ast)
"Render @var{ast} back to source text, byte for byte.
The reader and this function are inverses: every comment, every blank line
and every reader prefix in the input is in the output, in the same place."
(call-with-output-string
(lambda (out)
(for-each (lambda (node) (display (node->string node) out)) ast))))
Work out which dialect a file is written in.
The order is the one the manual documents: the extension first, because
it is what the user chose; then the shebang, because it says which
interpreter runs the file; then a marker inside the file; and nothing
else. A caller that gets #f must ask for ‘–dialect’ rather than
guess.
(define* (detect-dialect #:key file source)
"Work out which dialect a file is written in.
The order is the one the manual documents: the extension first, because it
is what the user chose; then the shebang, because it says which interpreter
runs the file; then a marker inside the file; and nothing else. A caller
that gets @code{#f} must ask for `--dialect' rather than guess."
(or (and file (extension-dialect file))
(and source (shebang-dialect source))
(and source (dialect-marker source))
#f))
Return the dialect named by a marker inside source, or #f.
The first 200 lines are searched, because a library’s ‘define-module’ or ‘in-package’ appears before any code it describes, and a file that names its dialect that early has already told us what it is. Only a directive counts, and only where one can be written – at the start of a line, not in a comment and not inside a string. A ‘#lang’ line is a header rather than a marker: it is the first thing in the file, and nothing else writes one.
(define (dialect-marker source)
"Return the dialect named by a marker inside @var{source}, or @code{#f}.
The first 200 lines are searched, because a library's `define-module' or
`in-package' appears before any code it describes, and a file that names its
dialect that early has already told us what it is. Only a directive counts,
and only where one can be written -- at the start of a line, not in a comment
and not inside a string. A `#lang' line is a header rather than a marker: it
is the first thing in the file, and nothing else writes one."
(let ((lines (marker-lines source)))
(cond
[(let loop ((rest lines))
(cond
[(null? rest) #f]
[(string-null? (string-trim-both (car rest))) (loop (cdr rest))]
[(string-prefix? "#!" (string-trim-both (car rest))) (loop (cdr rest))]
[else (string-prefix? "#lang " (string-trim-both (car rest)))]))
'racket]
[(any (lambda (line)
(string-contains line "lexical-binding: t"))
(take lines (min 2 (length lines))))
'elisp]
[(any (lambda (line)
(or (directive-line? line "(in-package")
(directive-line? line "(defpackage")))
lines)
'cl]
[(any (lambda (line)
(or (directive-line? line "(define-module")
(directive-line? line "(use-modules")))
lines)
'scheme]
[else #f])))
Return the dialect file’s extension claims, or #f.
(define (extension-dialect file)
"Return the dialect @var{file}'s extension claims, or @code{#f}."
(let ((ext (extension-of file)))
(and ext
(let ((row (find (lambda (entry) (member ext (cdr entry)))
dialect-extensions)))
(and row (car row))))))
Return the number of lines in source; a file of one line returns 1.
(define (line-count source)
"Return the number of lines in @var{source}; a file of one line returns 1."
(let ((n (string-length source)))
(if (= n 0)
1
(let loop ((i 0) (count 1))
(if (>= i n)
count
(let ((c (string-ref source i)))
(cond
[(char=? c #\newline) (loop (+ i 1) (+ count 1))]
[(and (char=? c #\return)
(or (>= (+ i 1) n)
(not (char=? (string-ref source (+ i 1))
#\newline))))
(loop (+ i 1) (+ count 1))]
[else (loop (+ i 1) count)])))))))
Return the 1-based line number of index in source.
(define (line-of source index)
"Return the 1-based line number of @var{index} in @var{source}."
(let* ((starts (compute-line-starts source))
(limit index))
(let loop ((i 0))
(cond
[(>= (+ i 1) (vector-length starts)) (+ i 1)]
[(<= (vector-ref starts (+ i 1)) limit) (loop (+ i 1))]
[else (+ i 1)]))))
Render node back to source text, verbatim.
This is the structural inverse of the reader and is what the round-trip fixtures compare: no formatting decisions are made here at all.
Read source (or all of port) and return the AST and the errors.
Two values come back: a list of top-level nodes, each carrying its location, and a list of <lint-warning> records whose checker is ‘reader’. A file with errors still has an AST: the reader returns everything it could read, and never abandons the rest of the file because one form is broken.
‘port’ defaults to #f and the current input port is taken in the
body rather than in the argument list, because a default that calls a
procedure is evaluated on every call – including the calls that pass
source and have no port to give – and taking a port that will not
be read is work, and can be a side effect, for nothing.
(define* (read-source #:key (dialect 'scheme) (file #f) (port #f) (source #f))
"Read @var{source} (or all of @var{port}) and return the AST and the errors.
Two values come back: a list of top-level nodes, each carrying its
location, and a list of <lint-warning> records whose checker is `reader'.
A file with errors still has an AST: the reader returns everything it could
read, and never abandons the rest of the file because one form is broken.
`port' defaults to @code{#f} and the current input port is taken in the body
rather than in the argument list, because a default that calls a procedure is
evaluated on every call -- including the calls that pass @var{source} and have
no port to give -- and taking a port that will not be read is work, and can be
a side effect, for nothing."
(let* ((text (if source
source
(read-port-text (or port (current-input-port)))))
(r (make-reader text #:file file #:dialect dialect)))
(let loop ((nodes '()))
(let ((node (read-node r)))
(if (eq? node '*eof*)
(values (reverse nodes) (reverse (reader-errors r)))
(loop (cons node nodes)))))))
Read string; a convenience over read-source for tests.
(define* (read-source-string string #:key (dialect 'scheme) (file #f))
"Read @var{string}; a convenience over @code{read-source} for tests."
(read-source #:source string #:dialect dialect #:file file))
Read the file at path.
(define* (read-source/file path #:key (dialect 'scheme))
"Read the file at @var{path}."
(read-source #:source (call-with-input-file path get-string-all)
#:dialect dialect
#:file path))
Return line line (1-based) of source, without its break.
(define (source-line source line)
"Return line @var{line} (1-based) of @var{source}, without its break."
(let ((lines (source-lines source)))
(and (>= line 1) (<= line (length lines))
(list-ref lines (- line 1)))))
Return source split into lines, without their line breaks.
(define (source-lines source)
"Return @var{source} split into lines, without their line breaks."
(let* ((text (if (string-index source #\return)
(normalise-newlines source)
source))
(n (string-length text)))
(if (= n 0)
(list "")
(let loop ((start 0) (i 0) (out '()))
(cond
[(>= i n)
(reverse (cons (substring text start i) out))]
[(char=? (string-ref text i) #\newline)
(loop (+ i 1) (+ i 1) (cons (substring text start i) out))]
[else (loop start (+ i 1) out)])))))
Read string and return only its data nodes, trivia dropped.
This is the structural view a test wants when it asks "what did the reader see?": ‘(string->ast-list "(a b)")’ gives one node, the list.
(define (string->ast-list string)
"Read @var{string} and return only its data nodes, trivia dropped.
This is the structural view a test wants when it asks \"what did the reader
see?\": `(string->ast-list \"(a b)\")' gives one node, the list."
(call-with-values
(lambda () (read-source-string string))
(lambda (ast errors)
(filter node-data? ast))))
((scheme ".scm" ".ss" ".sld" ".sls" ".sps") (racket ".rkt" ".rktd" ".rktl") (elisp ".el") (cl ".lisp" ".cl" ".asd" ".lsp" ".system"))
(dialect . extensions).
;;
;; A table rather than a `cond' because it is the first thing a new dialect
;; needs: a file nothing recognises is a file a reader has to pass `--dialect'
;; for, and `tests/dialects.scm' fails when a dialect in `dialects' has no row
;; here.
;;
;; - `.sld' and `.sls' are R7RS and R6RS libraries, `.sps' an R6RS program: all
;; three are Scheme, and a project that keeps them apart from its `.scm' files
;; would otherwise have to pass `--dialect' for every one of them.
;; - `.rktd' is a Racket data module and `.rktl' a library the test runner
;; loads. `.scrbl' is Scribble, which has an at-expression reader of its own
;; -- `@verbatim{a b}' keeps its spacing, and this reader would collapse it
;; -- so it is not claimed as Racket.
(define dialect-extensions
'((scheme . (".scm" ".ss" ".sld" ".sls" ".sps"))
(racket . (".rkt" ".rktd" ".rktl"))
(elisp . (".el"))
(cl . (".lisp" ".cl" ".asd" ".lsp" ".system"))))
This module holds every data type the rest of sift shares: source locations, lint warnings, lint checkers and – as documented at length below – the uniform AST node used by the reader, the formatter and the checkers.
Nothing in this module does any work: it is a vocabulary, and every other module imports it so that a node built by the reader is the same shape the formatter renders and the checkers inspect.
list-checkers table.
#t when checker applies to dialect.
#t for a bytevector, in either of its two spellings.
#f.
#f.
#t when node sits inside a "#;" datum comment.
#t for a node that carries a datum, trivia aside.
#+/#- conditional.
#+/#- conditional.
#f.
#f.
#t when node is a comment that follows code on its
line.
#t for a node that is not a datum: whitespace or a
comment.
#t for a vector literal.
#t when the formatter must copy node without
touching it.
#f.
#f.
#f.
#t when thing names a dialect sift reads.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented procedure.
(define (dialect->string dialect) (symbol->string dialect))
Render checker as one line of the list-checkers table.
(define (lint-checker->string checker)
"Render @var{checker} as one line of the @code{list-checkers} table."
(format #f "~a ~a ~a ~a"
(pad-right (symbol->string (lint-checker-name checker)) 24)
(pad-right (format #f "~a" (lint-checker-dialects checker)) 15)
(pad-right (symbol->string (lint-checker-severity checker)) 10)
(lint-checker-description checker)))
Return #t when checker applies to dialect.
(define (lint-checker-for-dialect? checker dialect)
"Return @code{#t} when @var{checker} applies to @var{dialect}."
(let ((applies (lint-checker-dialects checker)))
(or (eq? applies 'all) (memq dialect applies) #f)))
Render warning as one line in the Guix lint style.
The path, line and column come first so that an editor can jump to the finding; the checker is bracketed so that a filter can find it; the message is a complete sentence, lowercase after the bracket and without a trailing period, so that several findings read as a list.
(define (lint-warning->string warning)
"Render @var{warning} as one line in the Guix lint style.
The path, line and column come first so that an editor can jump to the
finding; the checker is bracketed so that a filter can find it; the message
is a complete sentence, lowercase after the bracket and without a trailing
period, so that several findings read as a list."
(format #f "~a: ~a: [~a] ~a"
(source-location->string (lint-warning-location warning))
(severity->string (lint-warning-severity warning))
(lint-warning-checker warning)
(lint-warning-message warning)))
Order two warnings by file, line, column and checker name.
The order has to be total and independent of hash iteration order, because the formatter and the linter promise the same output on every run.
(define (lint-warning<? a b)
"Order two warnings by file, line, column and checker name.
The order has to be total and independent of hash iteration order, because
the formatter and the linter promise the same output on every run."
(let ((loc-a (lint-warning-location a))
(loc-b (lint-warning-location b)))
(cond
[(and (source-location-file loc-a) (source-location-file loc-b)
(not (string=? (source-location-file loc-a)
(source-location-file loc-b))))
(string<? (source-location-file loc-a) (source-location-file loc-b))]
[(not (eqv? (source-location-line loc-a) (source-location-line loc-b)))
(< (source-location-line loc-a) (source-location-line loc-b))]
[(not (eqv? (source-location-column loc-a) (source-location-column loc-b)))
(< (source-location-column loc-a) (source-location-column loc-b))]
[else
(string<? (symbol->string (lint-warning-checker a))
(symbol->string (lint-warning-checker b)))])))
Return a checker record, with its rule code.
A checker’s *name* is what a person types; its *code* is what an editor
attaches to a diagnostic so that a key press can jump to the rule’s
documentation. The code is derived from the name through
rule-codes when it is not given, so a checker cannot be written
without one and a code cannot move when the list is re-sorted.
(define* (make-lint-checker name description dialects proc severity example
#:optional (code #f))
"Return a checker record, with its rule code.
A checker's *name* is what a person types; its *code* is what an editor
attaches to a diagnostic so that a key press can jump to the rule's
documentation. The code is derived from the name through @code{rule-codes}
when it is not given, so a checker cannot be written without one and a code
cannot move when the list is re-sorted."
(%make-lint-checker name (or code (rule-code name)) description dialects
proc severity example))
Return a warning about checker at location.
fix, when given, is a procedure of three arguments – the whole source string, the start character offset and the end character offset – that returns the replacement text for that range. The procedure is only called when range is also known (either passed here or derived from location), because a fix that does not know what it replaces cannot be applied safely.
(start . end) character offsets
(define* (make-lint-warning checker severity message location
#:optional (fix #f) (range #f))
"Return a warning about @var{checker} at @var{location}.
@var{fix}, when given, is a procedure of three arguments -- the whole source
string, the start character offset and the end character offset -- that
returns the replacement text for that range. The procedure is only called
when @var{range} is also known (either passed here or derived from
@var{location}), because a fix that does not know what it replaces cannot be
applied safely."
(%make-lint-warning checker severity message location fix range))
Return a warning whose fix, when applied, replaces the range START..END.
(define* (make-lint-warning/range checker severity message location
start end
#:optional (fix #f))
"Return a warning whose fix, when applied, replaces the range START..END."
(%make-lint-warning checker severity message location fix (cons start end)))
Return a node of kind holding value, spanning start..end.
(marking a datum comment's children
;;; commented out) builds a new node, which starts with no cache.
(define* (make-node kind value start end #:optional (fields '()))
"Return a node of @var{kind} holding @var{value}, spanning @var{start}..@var{end}."
(%make-node kind value start end fields #f))
Return a location, defaulting the character index to the byte OFFSET.
Both numbers are kept because a file of ASCII is the common case in which they agree, and code that only cares about a position should not have to pass both.
(define* (make-source-location file line column offset #:optional (index offset)) "Return a location, defaulting the character index to the byte OFFSET. Both numbers are kept because a file of ASCII is the common case in which they agree, and code that only cares about a position should not have to pass both." (%make-source-location file line column offset index))
Return a location carrying both the byte OFFSET and the character INDEX.
(define* (make-source-location* file line column offset index) "Return a location carrying both the byte OFFSET and the character INDEX." (%make-source-location file line column offset index))
Render node back to source text, verbatim.
This is the structural inverse of the reader and is what the round-trip fixtures compare: no formatting decisions are made here at all.
(define (node->string node)
"Render @var{node} back to source text, verbatim.
This is the structural inverse of the reader and is what the round-trip
fixtures compare: no formatting decisions are made here at all."
(define (emit node out)
(cond
[(node-list? node)
(display (node-open node) out)
(for-each (lambda (child) (emit child out)) (node-children node))
(when (node-close node) (display (node-close node) out))]
[(node-prefix? node)
(display (node-token node) out)
(let ((gap (node-field node 'gap ""))
(child (node-child node)))
(display gap out)
(when child (emit child out)))]
[(node-conditional? node)
(display (node-token node) out)
(display (node-field node 'gap "") out)
(emit (node-feature node) out)
(display (node-field node 'gap2 " ") out)
(when (node-guarded-form node) (emit (node-guarded-form node) out))]
[else (display (node-value node) out)]))
(let ((out (open-output-string)))
(emit node out)
(get-output-string out)))
Return the classification of an atom: symbol, keyword, number, string ...
(define (node-atom-type node) "Return the classification of an atom: symbol, keyword, number, string ..." (and (node-atom? node) (node-field node 'atom-type 'symbol)))
Undocumented procedure.
(define (node-atom? node) (node-kind? node 'atom))
Undocumented procedure.
(define (node-block-comment? node) (node-kind? node 'block-comment))
Return #t for a bytevector, in either of its two spellings.
‘#u8(...)’ is the one Guile and R7RS write and ‘#vu8(...)’ the one R6RS writes; both name the same datum, so a checker asks this rather than comparing the opener itself.
(define (node-bytevector? node)
"Return @code{#t} for a bytevector, in either of its two spellings.
`#u8(...)' is the one Guile and R7RS write and `#vu8(...)' the one R6RS writes;
both name the same datum, so a checker asks this rather than comparing the
opener itself."
(and (node-list? node)
(let ((open (node-open node)))
(or (equal? open "#u8(") (equal? open "#vu8(")))))
Return the datum a prefix node applies to, or #f.
(define (node-child node)
"Return the datum a prefix node applies to, or @code{#f}."
(and (node-prefix? node) (node-field node 'child #f)))
Return every child of a list node, trivia included.
(define (node-children node) "Return every child of a list node, trivia included." (if (node-list? node) (node-value node) '()))
Return the closing token a list node was closed with, or #f.
(define (node-close node)
"Return the closing token a list node was closed with, or @code{#f}."
(and (node-list? node) (node-field node 'close ")")))
Undocumented procedure.
(define (node-comment? node) (node-kind? node 'comment))
Return #t when node sits inside a "#;" datum comment.
(define (node-commented-out? node)
"Return @code{#t} when @var{node} sits inside a \"#;\" datum comment."
(node-field node 'commented-out #f))
Undocumented procedure.
(define (node-conditional? node) (node-kind? node 'conditional))
Return #t for a node that carries a datum, trivia aside.
A datum comment ("#;form") is trivia: the form it holds is preserved but is not part of the program, and neither the formatter nor the linter may treat it as code.
(define (node-data? node)
"Return @code{#t} for a node that carries a datum, trivia aside.
A datum comment (\"#;form\") is trivia: the form it holds is preserved but
is not part of the program, and neither the formatter nor the linter may
treat it as code."
(not (or (node-trivia? node) (node-datum-comment? node))))
Undocumented procedure.
(define (node-datum-comment? node) (and (node-prefix? node) (equal? (node-token node) "#;")))
Return the children of node that carry a datum, trivia aside.
Comments and whitespace are dropped, and so is a datum comment, so the result is the form as a program sees it. The list is shared with every other caller – a node is immutable, so sharing it is free.
(define (node-elements node)
"Return the children of @var{node} that carry a datum, trivia aside.
Comments and whitespace are dropped, and so is a datum comment, so the
result is the form as a program sees it. The list is shared with every other
caller -- a node is immutable, so sharing it is free."
(if (node-list? node)
(vector-ref (node-list-cache node) 0)
'()))
Return the feature expression of a #+/#- conditional.
(define (node-feature node)
"Return the feature expression of a @code{#+}/@code{#-} conditional."
(and (node-conditional? node) (node-field node 'feature #f)))
Return the property key of node, or default.
(define* (node-field node key #:optional (default #f))
"Return the property @var{key} of @var{node}, or @var{default}."
(let ((cell (assq key (node-fields node))))
(if cell (cdr cell) default)))
Return the property key of node, or default.
This is the argument order a fold wants, so a whole tree can be summarised without writing a lambda around every accessor.
(define (node-field/node default key node)
"Return the property @var{key} of @var{node}, or @var{default}.
This is the argument order a fold wants, so a whole tree can be summarised
without writing a lambda around every accessor."
(node-field node key default))
Return the form guarded by a #+/#- conditional.
(define (node-guarded-form node)
"Return the form guarded by a @code{#+}/@code{#-} conditional."
(and (node-conditional? node) (node-field node 'guarded-form #f)))
Return the first datum of a list node, or #f.
(define (node-head node)
"Return the first datum of a list node, or @code{#f}."
(and (node-list? node)
(let ((elements (vector-ref (node-list-cache node) 0)))
(and (pair? elements) (car elements)))))
Return the head of a list node as a symbol, or #f.
Only an unquoted, unprefixed atom names an operator: ('foo x) and
(#'foo x) have no operator, which is what the indentation table
keys on.
A vector has no operator either. #(progn a) is a literal that
holds two symbols; reading the first of them as an operator is how a
linter ends up offering to replace a vector with its contents, and a
formatter ends up indenting a literal like a call.
The answer is computed once and kept on the node: every checker asks it about every node, and interning the same name again for each of them is the largest single cost a lint has.
(define (node-head-name node)
"Return the head of a list node as a symbol, or @code{#f}.
Only an unquoted, unprefixed atom names an operator: @code{('foo x)} and
@code{(#'foo x)} have no operator, which is what the indentation table keys
on.
A vector has no operator either. @code{#(progn a)} is a literal that holds
two symbols; reading the first of them as an operator is how a linter ends up
offering to replace a vector with its contents, and a formatter ends up
indenting a literal like a call.
The answer is computed once and kept on the node: every checker asks it about
every node, and interning the same name again for each of them is the largest
single cost a lint has."
(and (node-list? node)
(vector-ref (node-list-cache node) 1)))
Return #t when node is a comment that follows code on its
line.
(define (node-inline? node)
"Return @code{#t} when @var{node} is a comment that follows code on its line."
(and (node-comment? node) (node-field node 'inline #f)))
Undocumented procedure.
(define (node-language? node) (node-kind? node 'language))
Undocumented procedure.
(define (node-list? node) (node-kind? node 'list))
Return the number of newline characters in a whitespace node.
(define (node-newlines node) "Return the number of newline characters in a whitespace node." (and (node-whitespace? node) (node-field node 'newlines 0)))
Undocumented procedure.
(define (node-opaque? node) (node-kind? node 'opaque))
Return the opening token of a list node: "(", "[", "#(" ...
(define (node-open node)
"Return the opening token of a list node: \"(\", \"[\", \"#(\" ..."
(and (node-list? node) (node-field node 'open "(")))
Return the package marker of a Common Lisp symbol: "cl:", "cl::", ...
(define (node-package-marker node) "Return the package marker of a Common Lisp symbol: \"cl:\", \"cl::\", ..." (and (node-atom? node) (node-field node 'package-marker #f)))
Undocumented procedure.
(define (node-prefix? node) (node-kind? node 'prefix))
Return the original source text of node, when it was recorded.
(define (node-raw node)
"Return the original source text of @var{node}, when it was recorded."
(node-field node 'raw #f))
Undocumented procedure.
(define (node-shebang? node) (node-kind? node 'shebang))
Undocumented procedure.
(define (node-stray-delimiter? node) (and (node-atom? node) (eq? (node-atom-type node) 'stray-delimiter)))
Undocumented procedure.
(define (node-string? node) (and (node-atom? node) (eq? (node-atom-type node) 'string)))
Return the token of a prefix or conditional node: "’", "#;", "#+" ...
(define (node-token node)
"Return the token of a prefix or conditional node: \"'\", \"#;\", \"#+\" ..."
(and (memq (node-kind node) '(prefix conditional))
(node-value node)))
Return #t for a node that is not a datum: whitespace or a
comment.
(define (node-trivia? node)
"Return @code{#t} for a node that is not a datum: whitespace or a comment."
(memq (node-kind node) '(whitespace comment block-comment shebang)))
Return #t for a vector literal.
A vector is ‘#(1 2)’ in every dialect sift reads, and ‘[1 2]’ in Emacs Lisp, where a square bracket *is* the vector syntax. In Scheme and Common Lisp a square bracket is a list written with brackets – a ‘cond’ clause, most of the time – and is not a vector at all.
The reader settles the question when it reads the opener, because that is where the dialect is known, and records the answer on the node; this asks the node.
(define (node-vector? node)
"Return @code{#t} for a vector literal.
A vector is `#(1 2)' in every dialect sift reads, and `[1 2]' in Emacs Lisp,
where a square bracket *is* the vector syntax. In Scheme and Common Lisp a
square bracket is a list written with brackets -- a `cond' clause, most of the
time -- and is not a vector at all.
The reader settles the question when it reads the opener, because that is
where the dialect is known, and records the answer on the node; this asks the
node."
(and (node-list? node) (node-field node 'vector #f)))
Return #t when the formatter must copy node without
touching it.
(define (node-verbatim? node)
"Return @code{#t} when the formatter must copy @var{node} without touching it."
(or (node-field node 'verbatim #f)
(node-opaque? node)
(node-datum-comment? node)))
Undocumented procedure.
(define (node-whitespace? node) (node-kind? node 'whitespace))
Return the code of the rule named name, or #f.
(define (rule-code name)
"Return the code of the rule named @var{name}, or @code{#f}."
(assq-ref rule-codes name))
Return the name of severity as it is printed.
(define (severity->string severity)
"Return the name of @var{severity} as it is printed."
(symbol->string severity))
Return how loud severity is: errors 3, warnings 2, info 1.
(define (severity-rank severity)
"Return how loud @var{severity} is: errors 3, warnings 2, info 1."
(case severity
[(error) 3]
[(warning) 2]
[(info) 1]
[else 0]))
Format location the way a compiler does: file:line:column.
(define (source-location->string location)
"Format @var{location} the way a compiler does: file:line:column."
(format #f "~a:~a:~a"
(or (source-location-file location) "<stdin>")
(source-location-line location)
(source-location-column location)))
Order two locations by file, then line, then column.
A missing file sorts first, so a diagnostic about stdin is reported before one about a named file in the same run.
(define (source-location<? a b)
"Order two locations by file, then line, then column.
A missing file sorts first, so a diagnostic about stdin is reported before
one about a named file in the same run."
(let ((fa (source-location-file a))
(fb (source-location-file b)))
(cond
[(and fa fb (not (string=? fa fb))) (string<? fa fb)]
[(and (not fa) fb) #t]
[(and fa (not fb)) #f]
[(not (= (source-location-line a) (source-location-line b)))
(< (source-location-line a) (source-location-line b))]
[else (< (source-location-column a) (source-location-column b))])))
Return the dialect named by string, or #f.
Both the editor-facing names and the everyday ones are accepted, so
elisp and emacs-lisp name the same dialect, and rkt
is the name an editor gives a Racket buffer beside the language’s own.
(define (string->dialect string)
"Return the dialect named by @var{string}, or @code{#f}.
Both the editor-facing names and the everyday ones are accepted, so
@code{elisp} and @code{emacs-lisp} name the same dialect, and @code{rkt} is
the name an editor gives a Racket buffer beside the language's own."
(case [string->symbol (string-downcase string)]
[(scheme) 'scheme]
[(racket rkt) 'racket]
[(elisp emacs-lisp emacs) 'elisp]
[(cl common-lisp lisp) 'cl]
[else #f]))
Return the severity named by string, or #f.
(define (string->severity string)
"Return the severity named by @var{string}, or @code{#f}."
(case [string->symbol (string-downcase string)]
[(error) 'error]
[(warning warn) 'warning]
[(info) 'info]
[else #f]))
Return #t when thing names a dialect sift reads.
(define (valid-dialect? thing)
"Return @code{#t} when @var{thing} names a dialect sift reads."
(and (symbol? thing) (memq thing dialects) #t))
This record type has 7 fields: name, code,
description, dialects, proc, severity,
example.
(define-record-type <lint-checker> (%make-lint-checker name code description dialects proc severity example) lint-checker? (name lint-checker-name) ; symbol (code lint-checker-code) ; "SIFT012": the stable name of the rule (description lint-checker-description) ; string, one sentence (dialects lint-checker-dialects) ; '(scheme racket elisp cl), '(...), or 'all (proc lint-checker-proc) ; (lambda (ast source dialect) warnings) (severity lint-checker-severity) ; default severity of its findings (example lint-checker-example))
This record type has 6 fields: checker, severity,
message, location, fix, range.
(define-record-type <lint-warning> (%make-lint-warning checker severity message location fix range) lint-warning? (checker lint-warning-checker) ; symbol (severity lint-warning-severity) ; 'error | 'warning | 'info (message lint-warning-message) ; string (location lint-warning-location) ; <source-location> (fix lint-warning-fix) ; #f or (lambda (source start end) string) (range lint-warning-range))
This record type has 6 fields: kind, value, start,
end, fields, cache.
(" and a bytevector one
;;; whose `open' is "#u8(" or "#vu8("; both close with ")". This keeps the
;;; renderer's one rule -- "a list is its opener, its children, its closer" --
;;; true for every bracketed datum. The `vector' field says whether the node
;;; is a vector literal, which the reader decides because it is the only pass
;;; that knows the dialect: `[' is a vector in Emacs Lisp and a clause in
;;; Scheme.
;;;
;;; A symbol written in the extended syntax Guile reads, `#{foo bar}#', is an
;;; atom like any other: its value is the text between the two markers, its
;;; type is `symbol', and the formatter copies it back unchanged. Nothing
;;; parses what is inside it, because what is inside it is a name.
;;;
;;; Every node carries its start and end location, so that a diagnostic can
;;; point at it, a fix can replace exactly it, and a verbatim node can have
;;; its original text cut back out of the source.
(define-record-type <node>
(%make-node kind value start end fields cache)
node?
(kind node-kind) ; symbol
(value node-value) ; depends on the kind
(start node-start) ; <source-location>
(end node-end) ; <source-location>
(fields node-fields) ; alist of extra properties
(cache node-cache set-node-cache!))
This record type has 5 fields: file, line, column,
offset, index.
(define-record-type <source-location> (%make-source-location file line column offset index) source-location? (file source-location-file) ; string, or #f for stdin (line source-location-line) ; 1-based integer (column source-location-column) ; 1-based integer, in characters (offset source-location-offset) ; 0-based byte offset (index source-location-index))
(scheme racket elisp cl)
(define dialects '(scheme racket elisp cl))
This is a record of the type <source-location>, with 5 fields:
file, line, column, offset, index.
(define null-source-location (make-source-location #f 1 1 0 0))
((trailing-whitespace . "SIFT001") (tabs . "SIFT002") (line-length . "SIFT003") (unmatched-parens . "SIFT004") (empty-body . "SIFT005") (redundant-progn . "SIFT006") (reader-prefix-break . "SIFT007") (empty-form . "SIFT008") (duplicate-keyword . "SIFT009") (trailing-blank-lines . "SIFT010") (internal-define . "SIFT011") (if-without-else . "SIFT012") (when-without-body . "SIFT013") (unless-without-body . "SIFT014") (letrec-single-binding . "SIFT015") (quasiquote-unquote-constant . "SIFT016") (docstring-missing . "SIFT017") (docstring-first-line . "SIFT018") (docstring-indent . "SIFT019") (lexical-binding-missing . "SIFT020") (interactive-without-docstring . "SIFT021") (checkdoc-style-verb . "SIFT022") (provide-missing . "SIFT023") (declare-indent . "SIFT024") (package-prefix . "SIFT025") (double-colon . "SIFT026") (dangling-paren . "SIFT027") (defun-no-docstring . "SIFT028") (loop-keyword-style . "SIFT029") (redundant-identity . "SIFT030") (wrap-in-let . "SIFT031") (keyword-arguments . "SIFT032") (negated-if . "SIFT033") (docstring-arguments . "SIFT034") (docstring-texinfo . "SIFT035") (clause-brackets . "SIFT036") (duplicate-binding . "SIFT037") (docstring-before-interactive . "SIFT038") (unused-binding . "SIFT039") (naming-convention . "SIFT040") (predicate-name . "SIFT041") (special-variable-name . "SIFT042") (unused-argument . "SIFT043") (nesting-depth . "SIFT044") (eta-reduction . "SIFT045") (beta-reduction . "SIFT046") (composition . "SIFT047") (let-simplification . "SIFT048") (sxml-attributes . "SIFT049") (sxml-child . "SIFT050") (comment-semicolons . "SIFT051") (blank-line-in-body . "SIFT052") (single-letter-name . "SIFT053") (quote-of-constant . "SIFT054") (eq-on-literal . "SIFT055") (cond-else-not-last . "SIFT056") (duplicate-case-datum . "SIFT057") (too-many-arguments . "SIFT058") (defcustom-without-type . "SIFT059") (unused-import . "SIFT060") (library-not-found . "SIFT061") (unused-definition . "SIFT062") (sxml-empty-element . "SIFT063") (apply-of-list . "SIFT064") (let-sibling . "SIFT065") (needless-let* . "SIFT066") (eq-nil . "SIFT067") (append-nothing . "SIFT068") (case-literal-datum . "SIFT069") (letrec-init-reference . "SIFT070") (defpackage-use . "SIFT071") (ecase-otherwise . "SIFT072") (mixed-lambda-list . "SIFT073") (require-cl . "SIFT074") (save-excursion-set-buffer . "SIFT075") (interactive-without-arguments . "SIFT076") (gexp-quoted . "SIFT077") (ungexp-outside-gexp . "SIFT078") (gexp-output-script . "SIFT079") (assoc-ref-outputs . "SIFT080") (string-append-file-append . "SIFT081") (phase-name-quoting . "SIFT082") (use-modules-in-gexp . "SIFT083") (package-synopsis . "SIFT084") (package-description-literal . "SIFT085") (sha256-base32 . "SIFT086") (inputs-label-alist . "SIFT087") (call-arity . "SIFT088") (string-literal-argument . "SIFT089") (number-literal-argument . "SIFT090") (unused-import-from . "SIFT091") (eq-non-symbol . "SIFT092") (quasiquote-dotted-unquote . "SIFT093") (cognitive-complexity . "SIFT094") (cyclomatic-complexity . "SIFT095"))
(define rule-codes
'((trailing-whitespace . "SIFT001")
(tabs . "SIFT002")
(line-length . "SIFT003")
(unmatched-parens . "SIFT004")
(empty-body . "SIFT005")
(redundant-progn . "SIFT006")
(reader-prefix-break . "SIFT007")
(empty-form . "SIFT008")
(duplicate-keyword . "SIFT009")
(trailing-blank-lines . "SIFT010")
(internal-define . "SIFT011")
(if-without-else . "SIFT012")
(when-without-body . "SIFT013")
(unless-without-body . "SIFT014")
(letrec-single-binding . "SIFT015")
(quasiquote-unquote-constant . "SIFT016")
(docstring-missing . "SIFT017")
(docstring-first-line . "SIFT018")
(docstring-indent . "SIFT019")
(lexical-binding-missing . "SIFT020")
(interactive-without-docstring . "SIFT021")
(checkdoc-style-verb . "SIFT022")
(provide-missing . "SIFT023")
(declare-indent . "SIFT024")
(package-prefix . "SIFT025")
(double-colon . "SIFT026")
(dangling-paren . "SIFT027")
(defun-no-docstring . "SIFT028")
(loop-keyword-style . "SIFT029")
(redundant-identity . "SIFT030")
;; the rules added with the editor integration
(wrap-in-let . "SIFT031")
(keyword-arguments . "SIFT032")
(negated-if . "SIFT033")
(docstring-arguments . "SIFT034")
(docstring-texinfo . "SIFT035")
(clause-brackets . "SIFT036")
(duplicate-binding . "SIFT037")
(docstring-before-interactive . "SIFT038")
(unused-binding . "SIFT039")
(naming-convention . "SIFT040")
(predicate-name . "SIFT041")
(special-variable-name . "SIFT042")
(unused-argument . "SIFT043")
(nesting-depth . "SIFT044")
;; the rules about a form that says more than it does
(eta-reduction . "SIFT045")
(beta-reduction . "SIFT046")
(composition . "SIFT047")
(let-simplification . "SIFT048")
;; the shape of an SXML document
(sxml-attributes . "SIFT049")
(sxml-child . "SIFT050")
;; the layout rules of Riastradh's style guide
(comment-semicolons . "SIFT051")
(blank-line-in-body . "SIFT052")
(single-letter-name . "SIFT053")
;; the rules about a form that reads as safe and is not quite
(quote-of-constant . "SIFT054")
(eq-on-literal . "SIFT055")
(cond-else-not-last . "SIFT056")
(duplicate-case-datum . "SIFT057")
(too-many-arguments . "SIFT058")
(defcustom-without-type . "SIFT059")
;; the rules about what a file claims to use
(unused-import . "SIFT060")
(library-not-found . "SIFT061")
(unused-definition . "SIFT062")
;; the rules added after the first release of the editor integration
(sxml-empty-element . "SIFT063")
;; the rules a survey of the three style guides asked for
(apply-of-list . "SIFT064")
(let-sibling . "SIFT065")
(needless-let* . "SIFT066")
(eq-nil . "SIFT067")
(append-nothing . "SIFT068")
(case-literal-datum . "SIFT069")
(letrec-init-reference . "SIFT070")
(defpackage-use . "SIFT071")
(ecase-otherwise . "SIFT072")
(mixed-lambda-list . "SIFT073")
(require-cl . "SIFT074")
(save-excursion-set-buffer . "SIFT075")
(interactive-without-arguments . "SIFT076")
(gexp-quoted . "SIFT077")
(ungexp-outside-gexp . "SIFT078")
(gexp-output-script . "SIFT079")
(assoc-ref-outputs . "SIFT080")
(string-append-file-append . "SIFT081")
(phase-name-quoting . "SIFT082")
(use-modules-in-gexp . "SIFT083")
(package-synopsis . "SIFT084")
(package-description-literal . "SIFT085")
(sha256-base32 . "SIFT086")
(inputs-label-alist . "SIFT087")
(call-arity . "SIFT088")
(string-literal-argument . "SIFT089")
(number-literal-argument . "SIFT090")
(unused-import-from . "SIFT091")
(eq-non-symbol . "SIFT092")
(quasiquote-dotted-unquote . "SIFT093")
;; the rules about how much a definition asks of a reader
(cognitive-complexity . "SIFT094")
(cyclomatic-complexity . "SIFT095")))
"1.40.2"
(define sift-version "1.40.2")
Everything that turns a warning into something a human or a program reads: the one-line report in the style of Guix lint, the JSON array, the table ‘list-checkers’ prints, the page ‘explain’ prints, and the unified diff ‘check’ prints for a file that would change.
Colour is used only when the output is a terminal and NO_COLOR is unset, so a pipeline never has to strip escape sequences it did not ask for.
#t when colour should be written to port.
Return #t when colour should be written to port.
Three things can say no, and any one of them is enough: ‘–no-color’, the NO_COLOR environment variable, and an output that is not a terminal.
(define* (color-enabled? #:key (no-color #f) (port (current-output-port)))
"Return @code{#t} when colour should be written to @var{port}.
Three things can say no, and any one of them is enough: `--no-color', the
NO_COLOR environment variable, and an output that is not a terminal."
(and (not no-color)
(not (getenv "NO_COLOR"))
(isatty? port)))
Write everything sift knows about checker.
(define* (explain-checker checker #:key (port (current-output-port)))
"Write everything sift knows about @var{checker}."
(let ((example (lint-checker-example checker)))
(format port "CODE~%~a~%~%" (or (lint-checker-code checker) ""))
(format port "NAME~%~a~%~%" (lint-checker-name checker))
(format port "DESCRIPTION~%~a~%~%" (lint-checker-description checker))
(format port "DIALECTS~%~a~%~%"
(let ((dialects (lint-checker-dialects checker)))
(if (eq? dialects 'all)
(format #f "all dialects: ~a"
(string-join (checker-dialect-names checker) ", "))
(string-join (map symbol->string dialects) ", "))))
(format port "SEVERITY~%~a~%~%" (lint-checker-severity checker))
(when (and example (assq 'input example))
(format port "FAILING EXAMPLE~%~a~%~%" (assq-ref example 'input)))
(when (and example (assq 'fix example))
(format port "EXPECTED FIX~%~a~%" (assq-ref example 'fix)))))
Return string as a JSON string body, quotes and all.
(define (json-escape string)
"Return @var{string} as a JSON string body, quotes and all."
(let ((out (open-output-string)))
(display "\"" out)
(string-for-each
(lambda (c)
(case c
[(#\") (display "\\\"" out)]
[(#\\) (display "\\\\" out)]
[(#\newline) (display "\\n" out)]
[(#\return) (display "\\r" out)]
[(#\tab) (display "\\t" out)]
[else
(if (char<? c #\space)
(format out "\\u~4,'0x" (char->integer c))
(display c out))]))
string)
(display "\"" out)
(get-output-string out)))
Write the table ‘list-checkers’ prints.
The columns are as wide as their contents need, with the widths the manual shows as a minimum: a checker whose name is cut in half is a checker nobody can select, because the name printed is the name ‘–checker’ takes.
(define* (list-checkers-table checkers #:key (port (current-output-port)))
"Write the table `list-checkers' prints.
The columns are as wide as their contents need, with the widths the manual
shows as a minimum: a checker whose name is cut in half is a checker nobody
can select, because the name printed is the name `--checker' takes."
(let* ((name-width
(max 24
(+ 2
(apply max
0
(map (lambda (checker)
(string-length (symbol->string
(lint-checker-name checker))))
checkers)))))
(dialect-width
(max 15
(+ 2
(apply max
0
(map (lambda (checker)
(string-length (dialects->string checker)))
checkers)))))
(severity-width 10)
(code-width 9))
(format port "~a ~a ~a ~a ~a~%"
(string-pad-right "NAME" name-width)
(string-pad-right "CODE" code-width)
(string-pad-right "DIALECTS" dialect-width)
(string-pad-right "SEVERITY" severity-width)
"DESCRIPTION")
(for-each
(lambda (checker)
(format port "~a ~a ~a ~a ~a~%"
(string-pad-right (symbol->string (lint-checker-name checker))
name-width)
(string-pad-right (or (lint-checker-code checker) "") code-width)
(string-pad-right (dialects->string checker) dialect-width)
(string-pad-right (symbol->string (lint-checker-severity checker))
severity-width)
(lint-checker-description checker)))
checkers)))
Wrap text in the ANSI code when enabled.
(define* (paint text code #:key enabled)
"Wrap @var{text} in the ANSI @var{code} when @var{enabled}."
(if enabled
(string-append "\x1b[" (cdr (assq code ansi-codes)) "m" text "\x1b[0m")
text))
Write the ‘N files checked, N warnings, N errors‘ line.
(define* (render-summary files warnings errors infos
#:key (color? #f) (port (current-output-port)))
"Write the `N files checked, N warnings, N errors` line."
(let ((line (format #f "~a ~a, ~a, ~a"
files
(if (= files 1) "file checked" "files checked")
(format #f "~a ~a" warnings
(if (= warnings 1) "warning" "warnings"))
(format #f "~a ~a" errors
(if (= errors 1) "error" "errors")))))
(display (paint line (if (> errors 0) 'error
(if (> warnings 0) 'warning 'ok))
#:enabled color?)
port)
(newline port)))
Render one warning as the line ‘file:line:column: severity: [checker] msg’.
The order is the one an editor’s compile-mode parses: position first, then severity, then the bracketed checker, then a message that is a lowercase sentence with no trailing period.
(define* (render-warning warning #:key (color? #f) (port #f))
"Render one warning as the line `file:line:column: severity: [checker] msg'.
The order is the one an editor's compile-mode parses: position first, then
severity, then the bracketed checker, then a message that is a lowercase
sentence with no trailing period."
(let* ((location (lint-warning-location warning))
(path (or (source-location-file location) "<stdin>"))
(sev (lint-warning-severity warning))
(line (format #f "~a:~a:~a: ~a: [~a] ~a"
(paint (format #f "~a" path) 'bold #:enabled color?)
(source-location-line location)
(source-location-column location)
(paint (severity->string sev) sev #:enabled color?)
(lint-warning-checker warning)
(lint-warning-message warning))))
(if port (display line port) line)))
Write warnings to port in format.
json writes one array for the whole run, which is what a
streaming consumer wants; null writes nothing at all and exists
so that a script can ask for the exit status alone.
(define* (render-warnings warnings #:key (format 'human) (color? #f)
(port (current-output-port)) (quiet #f))
"Write @var{warnings} to @var{port} in @var{format}.
@code{json} writes one array for the whole run, which is what a streaming
consumer wants; @code{null} writes nothing at all and exists so that a
script can ask for the exit status alone."
(case format
[(json) (display (warnings->json warnings) port) (newline port)]
[(github)
(for-each (lambda (warning)
(display (warning->github warning) port)
(newline port))
warnings)]
[(sarif) (display (warnings->sarif warnings) port) (newline port)]
[(null) *unspecified*]
[else
(for-each (lambda (warning)
(display (render-warning warning #:color? color?) port)
(newline port))
warnings)]))
Return the URL of the rule catalogue.
(define (sift-rules-page) "Return the URL of the rule catalogue." (string-append sift-home-page "/blob/trunk/doc/rules.org"))
Return a unified diff between old-text and new-text.
The diff is not the shortest one possible – it trims the common prefix and suffix and reports the rest as one hunk – because sift’s job is to say "this file would change", which is what the reader of a ‘check’ run needs, not to minimise a patch.
(define* (unified-diff old-text new-text #:key (path "file") (context 3)
(color? #f) (labels #f))
"Return a unified diff between @var{old-text} and @var{new-text}.
The diff is not the shortest one possible -- it trims the common prefix and
suffix and reports the rest as one hunk -- because sift's job is to say
\"this file would change\", which is what the reader of a `check' run needs,
not to minimise a patch."
(let* ((old (source-line-list old-text))
(new (source-line-list new-text))
(prefix (common-prefix old new))
(suffix (common-suffix (drop old prefix) (drop new prefix)))
(old-changed (drop-right (drop old prefix) suffix))
(new-changed (drop-right (drop new prefix) suffix)))
(if (and (null? old-changed) (null? new-changed))
""
(let* ((window-start (max 0 (- prefix context)))
(old-end (min (length old)
(+ (- (length old) suffix) context)))
(new-end (min (length new)
(+ (- (length new) suffix) context)))
(old-count (- old-end window-start))
(new-count (- new-end window-start))
(out (open-output-string))
;; A single file is labelled by its own name, which is what
;; `patch' and `git apply' both accept; when two labels are
;; given they are used as they are.
(old-label (if labels (car labels) path))
(new-label (if labels (cdr labels) path)))
(format out "--- ~a~%" old-label)
(format out "+++ ~a~%" new-label)
(format out "@@ -~a,~a +~a,~a @@~%"
(+ window-start 1) old-count (+ window-start 1) new-count)
(for-each (lambda (line)
(display (string-append " " line) out)
(newline out))
(take (drop old window-start) (- prefix window-start)))
(for-each (lambda (line)
(display (paint (string-append "-" line) 'error
#:enabled color?) out)
(newline out))
old-changed)
(for-each (lambda (line)
(display (paint (string-append "+" line) 'ok
#:enabled color?) out)
(newline out))
new-changed)
(let* ((tail-start (- (length old) suffix))
(tail (take (drop old tail-start)
(max 0 (- old-end tail-start)))))
(for-each (lambda (line)
(display (string-append " " line) out)
(newline out))
tail))
(get-output-string out)))))
Return one warning as a JSON object, its keys in a fixed order.
The order matters: a diff of two runs of sift should only show what changed, and a hash table would not promise that.
(define* (warning->json warning)
"Return one warning as a JSON object, its keys in a fixed order.
The order matters: a diff of two runs of sift should only show what
changed, and a hash table would not promise that."
(let* ((location (lint-warning-location warning))
(checker (lint-warning-checker warning)))
(string-append
"{"
"\"file\":" (json-escape (or (source-location-file location) "<stdin>")) ","
"\"line\":" (number->string (source-location-line location)) ","
"\"column\":" (number->string (source-location-column location)) ","
"\"checker\":" (json-escape (symbol->string checker)) ","
;; the rule code is what an editor attaches to a diagnostic, so that a
;; key press can open the documentation of the rule that fired; a
;; finding that is not a rule -- a file that would be reformatted, one
;; that could not be read -- is named by its checker instead, because
;; an empty code is a code no editor can look up
"\"code\":" (json-escape (or (rule-code checker)
(symbol->string checker))) ","
"\"severity\":" (json-escape (severity->string
(lint-warning-severity warning))) ","
"\"message\":" (json-escape (lint-warning-message warning))
"}")))
Return warnings as a JSON array; an empty run is ‘[]’, not blank.
(define (warnings->json warnings)
"Return @var{warnings} as a JSON array; an empty run is `[]', not blank."
(string-append "["
(string-join (map warning->json warnings) ",")
"]"))
A standard library that is installed is read where it lives; a source tree that is not installed can be fetched, and that is what this module does. A URL is downloaded with ‘curl’ into the cache, checked before it is unpacked, and unpacked with ‘tar’ into a directory of its own. The directory is then just another root for ‘(sift stdlib)’ to index, which is the whole of the integration: downloading and indexing are two jobs, and the second one already knows how to read a directory.
Three rules make a download safe enough to be worth having. Only ‘http’, ‘https’ and ‘file’ URLs are accepted; the archive is listed before it is extracted, and an entry that is absolute, climbs out with ‘..’ or is a symbolic link is refused; and the download is bounded by a timeout, a connection timeout and a size. A bad archive is a failed source, never a tree written over the cache or over the home directory.
‘curl’ and ‘tar’ are the platform’s tools rather than libraries sift links against: both ship with Linux and macOS, and a machine without one reports that the source was not fetched rather than claiming it was. A source that is already in the cache is not downloaded again; deleting the cache directory is always safe.
#t when it arrived.
#f.
#t when name stays inside the directory it is in.
#t when path ends in an archive suffix tar can read.
#t when text is a source URL this module will fetch.
#t on success.
Return the source directories in cache-directory, newest name first.
(define (cached-sources cache-directory)
"Return the source directories in @var{cache-directory}, newest name first."
(if (not (and cache-directory (file-exists? cache-directory)))
'()
(filter-map
(lambda (name)
(let ((tree (string-append cache-directory "/" name "/tree")))
(and (directory-nonempty? tree) tree)))
(sort (or (false-if-exception (scandir cache-directory)) '()) string<?))))
Download url to target, returning #t when it arrived.
A partial file is written beside the target and renamed into place, so a download that ends in the middle leaves the archive it had rather than half of the one it was making. The limits are the ones a background fetch needs: a timeout, a connection timeout and a maximum size.
(define* (download-source url target #:key (report #f))
"Download @var{url} to @var{target}, returning @code{#t} when it arrived.
A partial file is written beside the target and renamed into place, so a
download that ends in the middle leaves the archive it had rather than half
of the one it was making. The limits are the ones a background fetch needs:
a timeout, a connection timeout and a maximum size."
(cond
[(not (program-exists? "curl"))
(when report (report "sources: curl is not installed; cannot download"))
#f]
[else
(let ((partial (string-append target ".partial")))
(when report (report (format #f "sources: downloading ~a" url)))
(let ((result (run-program
"curl"
(list "--fail" "--location" "--silent" "--show-error"
"--max-time" download-timeout
"--connect-timeout" connect-timeout
"--max-filesize" download-limit
"--output" partial url))))
(if (successful? result)
(let ((attributes (false-if-exception (stat partial))))
(if (and attributes (> (stat:size attributes) download-limit-bytes))
(begin
(false-if-exception (delete-file partial))
(when report
(report (format #f "sources: download too large: ~a" url)))
#f)
(begin
(false-if-exception (rename-file partial target))
(when report
(report (format #f "sources: downloaded ~a (~a bytes)"
url (if attributes (stat:size attributes) 0))))
#t)))
(begin
(false-if-exception (delete-file partial))
(when report
(report (format #f "sources: download failed: ~a"
(string-trim-both (cdr result)))))
#f))))]))
Undocumented procedure.
(define (program-exists? program)
(let ((path (getenv "PATH")))
(and path
(any (lambda (directory)
(file-exists? (string-append directory "/" program)))
(string-split path #\:)))))
Return the directory url was unpacked into, or #f.
A directory that is already there is the answer without a network request; refresh asks for the archive again, and is what a reader who wants a newer source tree uses. A failed download or a refused archive leaves no directory, so a later attempt is a later attempt.
(define* (resolve-source url cache-directory #:key (report #f) (refresh #f))
"Return the directory @var{url} was unpacked into, or @code{#f}.
A directory that is already there is the answer without a network request;
@var{refresh} asks for the archive again, and is what a reader who wants a
newer source tree uses. A failed download or a refused archive leaves no
directory, so a later attempt is a later attempt."
(if (not (source-url? url))
(begin
(when report (report (format #f "sources: not a source URL: ~a" url)))
#f)
(let* ((directory (source-directory cache-directory url))
(tree (string-append directory "/tree"))
(archive (string-append directory "/archive")))
(cond
[(and (not refresh) (directory-nonempty? tree))
(when report (report (format #f "sources: using cached ~a" url)))
tree]
[(not (source-archive? url))
(when report (report (format #f "sources: not an archive URL: ~a" url)))
#f]
[else
(make-directories directory)
(and (download-source url archive #:report report)
(unpack-source archive tree #:report report)
(begin
(when report (report (format #f "sources: ready ~a" url)))
tree))]))))
Return #t when name stays inside the directory it is in.
An absolute path, a component that is ‘..’, or an empty name is refused. The check is on the member’s spelling, which is what tar writes and what tar will follow; a name that passes is a name under the extraction directory.
(define (safe-archive-member? name)
"Return @code{#t} when @var{name} stays inside the directory it is in.
An absolute path, a component that is `..', or an empty name is refused. The
check is on the member's spelling, which is what tar writes and what tar will
follow; a name that passes is a name under the extraction directory."
(and (string? name)
(not (string-null? name))
(not (char=? (string-ref name 0) #\/))
(not (any (lambda (part) (string=? part ".."))
(string-split name #\/)))))
Return #t when path ends in an archive suffix tar can read.
(define (source-archive? path)
"Return @code{#t} when @var{path} ends in an archive suffix tar can read."
(and (string? path)
(any (lambda (suffix) (string-suffix? suffix path)) archive-suffixes)))
Undocumented procedure.
(define (source-cache-key url) (url-hash url))
Return the directory url is cached in under cache-directory.
(define (source-directory cache-directory url)
"Return the directory @var{url} is cached in under @var{cache-directory}."
(string-append cache-directory "/" (source-cache-key url)))
Return #t when text is a source URL this module will fetch.
(define (source-url? text)
"Return @code{#t} when @var{text} is a source URL this module will fetch."
(and (string? text)
(or (string-prefix? "https://" text)
(string-prefix? "http://" text)
(string-prefix? "file://" text))))
Unpack archive into tree, returning #t on success.
(define* (unpack-source archive tree #:key (report #f))
"Unpack @var{archive} into @var{tree}, returning @code{#t} on success."
(cond
[(not (program-exists? "tar"))
(when report (report "sources: tar is not installed; cannot unpack"))
#f]
[(not (safe-archive? archive))
(when report (report (format #f "sources: refusing an unsafe archive: ~a"
archive)))
#f]
[else
(make-directories tree)
(when report (report (format #f "sources: unpacking ~a" archive)))
(let ((result (run-program
"tar"
(list "-xf" archive "-C" tree "--no-same-owner"))))
(if (successful? result)
#t
(begin
(when report
(report (format #f "sources: unpack failed: ~a"
(string-trim-both (cdr result)))))
#f)))]))
A jump to ‘car’ has nowhere to land inside the project, and a server that answered "not here" would be answering about one in every three names a reader asks about. So the library a dialect ships with itself is indexed too, from two places, because a standard library comes in two shapes.
The first is *source*: Guile’s ‘ice-9’, ‘srfi’ and ‘scheme’ modules, the Emacs Lisp files an installation keeps beside its binary, the systems in a Common Lisp source registry, and the package trees those implementations install third-party code into. Those are files, and they are indexed the way a project’s files are – read, parsed, and asked the same question – so ‘(ice-9 format)’s ‘format’ lands on the ‘define’ that defines it, an Emacs package lands on the source it installed, and the hover is the hover of any other definition. A source that is compressed – the ‘.el.gz’ most Emacs installations ship – is decompressed as it is read.
The second is what an implementation *knows about itself*: ‘car’ is compiled into libguile and no file in the installation says where. Each implementation is asked once, in one process, to write down every name it documents, and the answer becomes a source file in that dialect – a ‘define’ with a docstring for a procedure, a ‘define-macro’ for a macro, a ‘define’ documented by the comment above it for a value. So a jump to ‘car’ lands in code that reads like the dialect rather than in a list of prose, and the index over the file is the same index a project’s files get.
Racket is the one dialect that has the first and not the second: it ships ‘collects’ and ‘pkgs’ as source, so its library is read like a project, and a name that only the compiled ‘#%kernel’ defines is the one it cannot answer. Not shipping a Racket program to describe it is a decision and not an omission – the files are already there.
Nothing here downloads anything. A standard library that is not installed is a standard library sift cannot read, and the answer is a smaller answer rather than a wrong one; ‘stdlib:’ in ‘sift.yaml’ is how a reader who unpacked a source tree somewhere hands it over.
Two costs are worth naming. Asking an implementation costs one process per dialect and indexing a standard library costs one read of it; both happen once per installation and are cached under the user’s cache directory. The cache is keyed on the implementation’s own binary, so an upgraded Guile is read again rather than answered about from an index of the old one.
#f when it has
none.
(uri text definition) for every place library
defines name.
#f when it
holds nothing.
Undocumented macro.
Undocumented macro.
Return the directory sift keeps its caches in, or #f when it has
none.
‘XDG_CACHE_HOME’ wins because it is the user saying where; macOS gets its own ‘Library/Caches’ because that is where a Mac application’s cache belongs, and ‘LOCALAPPDATA’ is the same answer for a Windows shell.
(define (cache-home)
"Return the directory sift keeps its caches in, or @code{#f} when it has none.
`XDG_CACHE_HOME' wins because it is the user saying where; macOS gets its own
`Library/Caches' because that is where a Mac application's cache belongs, and
`LOCALAPPDATA' is the same answer for a Windows shell."
(let ((xdg (getenv "XDG_CACHE_HOME"))
(home (getenv "HOME"))
(local (getenv "LOCALAPPDATA")))
(cond
[(and xdg (not (string-null? xdg))) (string-append xdg "/sift")]
[(and home (not (string-null? home)) (darwin?))
(string-append home "/Library/Caches/sift")]
[(and home (not (string-null? home))) (string-append home "/.cache/sift")]
[(and local (not (string-null? local))) (string-append local "/sift")]
[else #f])))
Return the standard library roots and builtins-path describe.
Nothing is discovered, nothing is written and no implementation is asked: this is the shape both the discovery and a test fill in, which is what lets the reading of a library be tested without one. builtins-path is the file the implementation described itself in, if it wrote one; it is read with the same reader as roots, and with a limit that fits a file holding every name an implementation documents.
(define* (index-standard-library #:key dialect roots (builtins-path #f)
(implementation "unknown"))
"Return the standard library @var{roots} and @var{builtins-path} describe.
Nothing is discovered, nothing is written and no implementation is asked: this
is the shape both the discovery and a test fill in, which is what lets the
reading of a library be tested without one. @var{builtins-path} is the file
the implementation described itself in, if it wrote one; it is read with the
same reader as @var{roots}, and with a limit that fits a file holding every
name an implementation documents."
(let* ((roots (without-nested-roots (existing-directories roots)))
;; the generated file may sit inside a root the reader named, and it
;; is read once, with the limit it was written under
(names (index-files dialect
(remove (lambda (path) (equal? path builtins-path))
(files-under-roots
roots (dialect-extensions dialect))))))
(when (and builtins-path (file-exists? builtins-path))
(let ((text (read-file-text builtins-path generated-byte-limit)))
(when text (record-file! names dialect builtins-path text))))
(make-standard-library dialect implementation roots names builtins-path
(make-hash-table) (make-hash-table) #f)))
Return the ‘;; sift: key value’ lines of a generated index, as an alist.
(define (metadata-of text)
"Return the `;; sift: key value' lines of a generated index, as an alist."
(let loop ((lines (string-split text #\newline)) (metadata '()))
(cond
[(null? lines) (reverse metadata)]
[(string-prefix? ";; sift: " (car lines))
(let* ((body (substring (car lines) 9))
(space (string-index body #\space)))
(loop (cdr lines)
(if space
(cons (cons (substring body 0 space)
(string-trim-both (substring body (+ space 1))))
metadata)
metadata)))]
[else (loop (cdr lines) metadata)])))
Resolve the URL entries of the ‘stdlib’ setting, and answer the directories.
A URL is downloaded and unpacked only when ‘download-sources’ is true; a directory is itself. The resolved list becomes the roots ‘read-library’ indexes, so a failure is one source missing rather than a library that cannot be read.
(define* (resolve-configured-roots! #:key (report #f))
"Resolve the URL entries of the `stdlib' setting, and answer the directories.
A URL is downloaded and unpacked only when `download-sources' is true; a
directory is itself. The resolved list becomes the roots `read-library'
indexes, so a failure is one source missing rather than a library that cannot
be read."
(if (not (and stdlib-enabled? configured-sources))
'()
(let* ((local (filter (lambda (entry) (not (source-url? entry)))
configured-sources))
(urls (filter source-url? configured-sources))
(cache (source-cache-directory))
(downloaded
(cond
[(null? urls) '()]
[(not download-sources?)
(when report
(report "sources: URLs in stdlib need download-sources: true"))
'()]
[(not cache)
(when report (report "sources: no cache directory"))
'()]
[else
(filter-map (lambda (url)
(resolve-source url cache #:report report))
urls)])))
(set! configured-roots (append local downloaded))
downloaded)))
Return the directory downloaded source archives and trees live in.
(define (source-cache-directory)
"Return the directory downloaded source archives and trees live in."
(let ((home (cache-home)))
(and home (string-append home "/sources"))))
Return (uri text definition) for every place library
defines name.
Every place, ordered by what a reader asking the question would rather be shown: a definition that writes its parameters, then a definition whose value is something else, then the file the implementation described itself in. The order is stable, so the files stay in the order the walk found them.
(define (stdlib-definitions library name)
"Return @code{(uri text definition)} for every place @var{library} defines @var{name}.
Every place, ordered by what a reader asking the question would rather be shown:
a definition that writes its parameters, then a definition whose value is
something else, then the file the implementation described itself in. The
order is stable, so the files stay in the order the walk found them."
(if (standard-library? library)
(let ((parts (name-parts name)))
(ordered-sites
(append-map
(lambda (entry)
(let ((path (car entry)))
(let ((text (library-text library path))
(definitions (library-definitions library path)))
(if text
(map (lambda (definition)
(list (path->uri path) text definition))
(filter (lambda (definition)
(and (not (definition-scope definition))
(member (definition-name definition) parts)))
(or definitions '())))
'()))))
(append-map (lambda (part)
(or (hash-ref (standard-library-names library) part) '()))
parts))
(standard-library-builtins-path library)))
'()))
Return dialect’s standard library, reading it on first use.
An index that is already written down is read here and now: one file, sooner than a request can be handed to another thread. An index that has to be built is built by one thread, and a request that arrives meanwhile is answered without it – with the smaller answer the caller already handles – rather than made to wait for a library it may not even be asking about.
(define (stdlib-for dialect)
"Return @var{dialect}'s standard library, reading it on first use.
An index that is already written down is read here and now: one file, sooner
than a request can be handed to another thread. An index that has to be built
is built by one thread, and a request that arrives meanwhile is answered
without it -- with the smaller answer the caller already handles -- rather than
made to wait for a library it may not even be asking about."
(or (with-mutex *library-lock* (hash-ref *libraries* dialect))
(cond
[(index-on-disk? dialect)
(let ((library (read-library dialect)))
(when library
(with-mutex *library-lock* (hash-set! *libraries* dialect library)))
library)]
[(with-mutex *library-lock*
(unless (hash-ref *reading* dialect)
(hash-set! *reading* dialect #t)
#t))
(let ((library (read-library dialect)))
(with-mutex *library-lock*
(when library (hash-set! *libraries* dialect library))
(hash-remove! *reading* dialect))
library)]
[else #f])))
Forget what this session knows about dialect, and its index with it.
(define (stdlib-forget! dialect)
"Forget what this session knows about @var{dialect}, and its index with it."
(hash-remove! *libraries* dialect)
(let ((index (index-file dialect))
(generated (builtins-file dialect)))
(when index (false-if-exception (delete-file index)))
(when generated (false-if-exception (delete-file generated))))
#t)
Answer the analysis’s questions about the standard library from here on.
setting is the configuration’s ‘stdlib’: #t to discover
what this machine has installed, a list of directories or source URLs to
read instead, or #f to answer nothing about a library at all.
download? is the ‘download-sources’ setting: a URL is fetched only
when it is true, so a project file cannot make sift reach the network on
its own.
(define* (stdlib-install! setting #:key (download? #f))
"Answer the analysis's questions about the standard library from here on.
@var{setting} is the configuration's `stdlib': @code{#t} to discover what this
machine has installed, a list of directories or source URLs to read instead,
or @code{#f} to answer nothing about a library at all. @var{download?} is the
`download-sources' setting: a URL is fetched only when it is true, so a project
file cannot make sift reach the network on its own."
(set! configured-sources (and (list? setting) setting))
(set! download-sources? download?)
(set! stdlib-enabled? (and setting #t))
(set! configured-roots
(and (list? setting)
(filter (lambda (entry) (not (source-url? entry))) setting)))
(hash-clear! *libraries*)
(if setting
(begin
(current-stdlib stdlib-definitions-for)
(current-stdlib-names stdlib-completions))
(begin
(current-stdlib (lambda (dialect name) '()))
(current-stdlib-names (lambda (dialect prefix) '())))))
Return (name . kind) for every name library knows.
A name is offered with the kind its definition has, which is the kind the editor colours it with; the generated file states one the same way a project’s file does.
(define (stdlib-names library)
"Return @code{(name . kind)} for every name @var{library} knows.
A name is offered with the kind its definition has, which is the kind the
editor colours it with; the generated file states one the same way a project's
file does."
(if (standard-library? library)
(or (standard-library-offered library)
(let ((names '()))
(hash-for-each
(lambda (name entries)
(set! names (cons (cons name (cdr (car entries))) names)))
(standard-library-names library))
(let ((offered (reverse names)))
(set-standard-library-offered! library offered)
offered)))
'()))
Return one line saying what library holds, or #f when it
holds nothing.
(define (stdlib-summary library)
"Return one line saying what @var{library} holds, or @code{#f} when it holds nothing."
(and (standard-library? library)
(format #f "~a: ~a, ~a names"
(standard-library-dialect library)
(standard-library-implementation library)
(hash-fold (lambda (name entries count) (+ count 1)) 0
(standard-library-names library)))))
Read every dialect’s library, and return a line about each that was read.
Called in a thread of its own by the server, so that the first jump a reader makes into a standard library is a jump and not a wait. report is called with a line as each source is resolved and each library is read, which is what lets an editor show that the work is happening rather than that sift is idle.
(define* (stdlib-warm! #:key (report #f))
"Read every dialect's library, and return a line about each that was read.
Called in a thread of its own by the server, so that the first jump a reader
makes into a standard library is a jump and not a wait. @var{report} is called
with a line as each source is resolved and each library is read, which is what
lets an editor show that the work is happening rather than that sift is idle."
(if (not stdlib-enabled?)
'()
(begin
(resolve-configured-roots! #:report report)
(filter-map (lambda (dialect)
(when report
(report (format #f "indexing the ~a library" dialect)))
(let ((library (stdlib-for dialect)))
(and library (pair? (stdlib-names library))
(let ((summary (stdlib-summary library)))
(when report (report summary))
summary))))
(map car dialects)))))
Return paths without the ones another of paths already holds.
A ‘%load-path’ names a directory and its parent – ‘/share/guile/3.0’ and ‘/share/guile’ – and walking both would read every file twice and answer with two places for one definition, so the parent is kept and the child is dropped.
(define (without-nested-roots paths)
"Return @var{paths} without the ones another of @var{paths} already holds.
A `%load-path' names a directory and its parent -- `/share/guile/3.0' and
`/share/guile' -- and walking both would read every file twice and answer with
two places for one definition, so the parent is kept and the child is dropped."
(filter (lambda (path)
(not (any (lambda (other)
(and (< (string-length other) (string-length path))
(string-prefix? other path)
(char=? #\/ (string-ref path (string-length other)))))
paths)))
paths))
Three procedures that every Scheme programmer reaches for and that R7RS does not have: find a substring, ask a question of every character, widen a field. They are SRFI-13’s, spelled ‘string-contains’, ‘string-every’ and ‘string-pad-right’ there, and SRFI-13 is a large library that Guile carries in full – but not every platform sift is built for does.
So they are written here against ‘string-ref’, ‘char=?’ and ‘string-append’, and they are spelled with names of sift’s own. That is the part worth saying out loud: reusing the SRFI-13 names would work, and would make every module that wants one of them carry an import clause saying "not that one" – which is exactly the kind of instruction that gets dropped by the next person to add an import. A name nobody else claims costs one word at the call site and asks nothing of the reader.
The optional arguments are SRFI-13’s, in SRFI-13’s order, so that a caller who knows the SRFI already knows these.
#t for no
characters.
#f.
Return the last value predicate returned, or #t for no
characters.
A character may be given in place of a predicate and stands for the
predicate that asks whether a character is that one, which is the
SRFI-13 shorthand. A predicate that answers #f once ends the
walk, so a caller asking whether a name is all punctuation does not read
the rest of the name.
(define (every-char predicate string . rest)
"Return the last value @var{predicate} returned, or @code{#t} for no characters.
A character may be given in place of a predicate and stands for the predicate
that asks whether a character is that one, which is the SRFI-13 shorthand.
A predicate that answers @code{#f} once ends the walk, so a caller asking
whether a name is all punctuation does not read the rest of the name."
(let* ((arguments (range-arguments rest 2))
(start (argument arguments 0 0))
(end (checked-end string 'every-char start (argument arguments 1 #f)))
(test (if (char? predicate)
(lambda (char) (char=? char predicate))
predicate)))
(let loop ((index start) (answer #t))
(if (>= index end)
answer
(let ((result (test (string-ref string index))))
(and result (loop (+ index 1) result)))))))
Return string padded on the right with char to width.
The table ‘list-checkers’ prints is laid out with this. A field wider than its column is not truncated: it is the author’s text and not the table’s, and a formatter that cut a description to fit a column would be lying about it.
(define (pad-right string width . rest)
"Return @var{string} padded on the right with @var{char} to @var{width}.
The table `list-checkers' prints is laid out with this. A field wider than
its column is not truncated: it is the author's text and not the table's, and
a formatter that cut a description to fit a column would be lying about it."
(let* ((arguments (range-arguments rest 3))
(char (argument arguments 0 #\space))
(start (argument arguments 1 0))
(end (checked-end string 'pad-right start (argument arguments 2 #f)))
(text (substring string start end))
(missing (- width (string-length text))))
(if (> missing 0)
(string-append text (make-string missing char))
text)))
Return the index of the first needle in string, or
#f.
The optional arguments are ranges: the part of string to search, then the part of needle to look for. An empty needle is found at the start of the range, so that ‘(string-find text "")’ is a question about the range and not a special case.
The answer is an index, and 0 is a true value, so a caller asking only whether a string occurs can use it as a predicate – which is what most of sift does.
(define (string-find string needle . rest)
"Return the index of the first @var{needle} in @var{string}, or @code{#f}.
The optional arguments are ranges: the part of @var{string} to search, then
the part of @var{needle} to look for. An empty @var{needle} is found at the
start of the range, so that `(string-find text \"\")' is a question about the
range and not a special case.
The answer is an index, and 0 is a true value, so a caller asking only whether
a string occurs can use it as a predicate -- which is what most of sift does."
(let* ((arguments (range-arguments rest 4))
(start (argument arguments 0 0))
(end (checked-end string 'string-find start (argument arguments 1 #f)))
(needle-start (argument arguments 2 0))
(needle-end (checked-end needle 'string-find needle-start
(argument arguments 3 #f)))
(needle-length (- needle-end needle-start)))
(let loop ((index start))
(cond
[(> (+ index needle-length) end) #f]
[(let inner ((offset 0))
(cond
[(>= offset needle-length) #t]
[(char=? (string-ref string (+ index offset))
(string-ref needle (+ needle-start offset)))
(inner (+ offset 1))]
[else #f]))
index]
[else (loop (+ index 1))]))))
Return the runs of word characters in text, in the order written.
‘(string-words "Add two numbers.")’ is ("Add" "two" "numbers").
(define (string-words text)
"Return the runs of word characters in @var{text}, in the order written.
`(string-words \"Add two numbers.\")' is @code{(\"Add\" \"two\" \"numbers\")}."
(let loop ((chars (string->list text)) (current '()) (words '()))
(define (finish words)
(if (null? current)
words
(cons (list->string (reverse current)) words)))
(cond
[(null? chars) (reverse (finish words))]
[(word-character? (car chars))
(loop (cdr chars) (cons (car chars) current) words)]
[else (loop (cdr chars) '() (finish words))])))
There is no inotify here and no dependency to carry: the watcher asks the file system a question every half second instead of subscribing to it. That is the right trade for this program – the alternative is a C library, a probe for three operating systems, and a fallback for the two that have neither – and the cost is one ‘stat’ per file per look, which is what a directory listing already costs.
What it asks is the cheapest question that catches a save: the modification time and the size. A time alone is not enough, because a file saved twice inside one tick of the clock has the same time twice; a size alone is not enough, because an edit that swaps one character for another is the same size. Together they miss exactly one case – two saves inside one tick that do not change the length – and a tick is a second on the filesystems that round and a nanosecond on the ones that do not.
The list that is polled is the list the last run *read*, not the operands it was given: ‘sift ci .’ is given a directory, and what changed may be a file three levels down. So the caller re-answers "what would this command read now" on every look, which is also how a new file is noticed.
'gone.
Return the paths whose stamp differs between before and after.
A path that appeared and a path that vanished are both changes: a run that starts reading a file it did not read before has something new to say about it, and one that stops reading a file has something to stop saying.
(define (changed-paths before after)
"Return the paths whose stamp differs between @var{before} and @var{after}.
A path that appeared and a path that vanished are both changes: a run that
starts reading a file it did not read before has something new to say about it,
and one that stops reading a file has something to stop saying."
(let ((paths (delete-duplicates
(append (map car before) (map car after))
string=?)))
(filter (lambda (path)
(let ((was (stamp-of before path))
(is (stamp-of after path)))
(not (equal? was is))))
paths)))
Return a sentence naming paths, limit of them at most.
(define* (describe-paths paths #:optional (limit 3))
"Return a sentence naming @var{paths}, @var{limit} of them at most."
(let ((shown (take paths (min limit (length paths))))
(rest (- (length paths) (min limit (length paths)))))
(if (null? shown)
"nothing"
(string-append (string-join shown ", ")
(if (> rest 0)
(format #f " and ~a more" rest)
"")))))
Return path’s modification time and size, or 'gone.
A file that cannot be read – deleted between the listing and the stat, or behind a permission the run will report on its own – is ‘gone’ rather than an error: the watcher’s job is to say that something changed, and a file that has vanished has certainly changed.
(define (file-stamp path)
"Return @var{path}'s modification time and size, or @code{'gone}.
A file that cannot be read -- deleted between the listing and the stat, or
behind a permission the run will report on its own -- is `gone' rather than an
error: the watcher's job is to say that something changed, and a file that has
vanished has certainly changed."
(catch #t
(lambda ()
(let ((info (stat path)))
(cons (stat:mtime info) (stat:size info))))
(lambda arguments 'gone)))
Return what paths looked like, as an alist of (path .
stamp).
(define (snapshot paths)
"Return what @var{paths} looked like, as an alist of @code{(path . stamp)}."
(map (lambda (path) (cons path (file-stamp path))) paths))
Watch files, calling run whenever they change.
files answers the paths the next run would read, and run is the run itself: the loop is written this way so that what is watched is the command’s own idea of its files – the project’s ‘file-filter’, the dialect an extension chose, a directory walked again – and not a second implementation of it here.
The caller has already run the command by the time this is called: its output is on the screen, and the first thing a watch says is what it is watching. A finding is a thing to look at rather than a reason to stop, so nothing about a run’s status is used, and Ctrl-C is how the loop ends.
(define* (watch-loop #:key run files (interval watch-interval)
(out (current-error-port)))
"Watch @var{files}, calling @var{run} whenever they change.
@var{files} answers the paths the next run would read, and @var{run} is the run
itself: the loop is written this way so that what is watched is the command's
own idea of its files -- the project's `file-filter', the dialect an extension
chose, a directory walked again -- and not a second implementation of it here.
The caller has already run the command by the time this is called: its output
is on the screen, and the first thing a watch says is what it is watching. A
finding is a thing to look at rather than a reason to stop, so nothing about a
run's status is used, and Ctrl-C is how the loop ends."
(let loop ((before (snapshot (files))))
(format out "sift: ~a file~a watched; waiting for a change (Ctrl-C to stop)~%"
(length before) (if (= 1 (length before)) "" "s"))
(force-output out)
(let* ((after (wait-for-change before files interval))
(changed (changed-paths before after)))
(format out "sift: ~a changed; running again~%"
(describe-paths changed))
(force-output out)
(run)
(loop (snapshot (files))))))
A small, data-only YAML reader and writer, sized to what a ‘sift.yaml’ configuration file needs: block mappings, block sequences, quoted and plain scalars, inline ‘[a, b]’ lists, comments, and nesting by indentation.
It is deliberately not a general YAML implementation. Anything it does not understand – anchors, tags, block scalars, flow mappings spanning lines – is reported as an error with a line and a column rather than guessed at, because a configuration file that quietly means something other than what it says is worse than one that refuses to load.
The reader keeps positions, so a wrong key or a wrong value can be reported as ‘sift.yaml:12:5: message’ instead of just a line number.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Undocumented macro.
Write datum as YAML, one block at a time.
Only the shapes a configuration holds are written: an alist is a mapping, a list is a sequence, everything else is a scalar.
(define* (scm->yaml datum #:key (port (current-output-port)) (indent 0))
"Write @var{datum} as YAML, one block at a time.
Only the shapes a configuration holds are written: an alist is a mapping, a
list is a sequence, everything else is a scalar."
(let ((pad (make-string indent #\space)))
(cond
[(and (list? datum) (every pair? datum))
(for-each
(lambda (entry)
(let ((key (car entry)) (value (cdr entry)))
(cond
[(and (list? value) (pair? value) (every pair? value))
(format port "~a~a:~%" pad key)
(scm->yaml value #:port port #:indent (+ indent 2))]
[(and (list? value) (pair? value) (not (pair? (car value))))
(format port "~a~a:~%" pad key)
(for-each (lambda (item)
(format port "~a- " pad)
(write-scalar item port)
(newline port))
value)]
[(and (list? value) (null? value))
(format port "~a~a: []~%" pad key)]
[else
(format port "~a~a: " pad key)
(write-scalar value port)
(newline port)])))
datum)
*unspecified*]
[(and (list? datum) (null? datum))
(format port "~a[]~%" pad)]
[else (format port "~a" pad) (write-scalar datum port) (newline port)])))
Parse source and return its node tree, positions included.
(define* (yaml->nodes source #:key (path "<yaml>"))
"Parse @var{source} and return its node tree, positions included."
(let ((lines (yaml-lines source path)))
(if (null? lines)
(mapping-node '() 1 1)
(call-with-values
(lambda () (parse-block lines path (first-of (car lines))))
(lambda (node remaining)
node)))))
Parse source and return plain data: alists, lists and scalars.
Keys come back as strings, because a YAML key is text; the caller decides what a key means.
(define* (yaml->scm source #:key (path "<yaml>"))
"Parse @var{source} and return plain data: alists, lists and scalars.
Keys come back as strings, because a YAML key is text; the caller decides
what a key means."
(node->scm (yaml->nodes source #:path path)))