Files
sex/types.scm
alex-eg c123120d22 read every trailing array bound as a dimension
[m 1 2] lost its second index, and [int 2 3] came out int 2 x[3]. Each
index now subscripts what the one before it gave, and [int 2 3] declares
what it indexes, int[2][3]. An inline struct's fields, once more than
one bound was looked for, were taken for one; their shape tells them apart.
2026-10-20 13:40:26 +03:00

553 lines
20 KiB
Scheme
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
;;; The type database.
;;;
;;; Every named aggregate, typedef and define the semantic engine
;;; walks past is recorded here, so that macros (or other forms) can
;;; ask what a type is made of. That is what lets a macro generate
;;; code from a struct's fields given nothing but its name.
;;;
;;; Entries are filled in as toplevel forms are processed, in order, so
;;; a type has to be declared before the macro that asks about it.
(import
scheme
(scheme base)
(chicken base)
(chicken module)
srfi-1
srfi-69)
(export
add-struct
add-union
add-enum
add-typedef
add-define
type-match
type-pattern-matches?
map-fields
add-sum!
get-sum
add-constructor!
get-constructor
variant-fields
reset-declarations!
add-spec!
get-spec
spec-parameter
spec-methods
add-realization!
realizes?
normalize-fields
add-method!
get-method
qualify-op
ops-key
add-name-type!
get-name-type
type-of
current-type-of
get-return-type
get-type-info
get-tag-info
get-fields
get-underlying-type
type-head?
named-arg?
named-arg-type
arglist-types
strip-pub
array-bound?
array-element-type
array-bound
nest-array-type)
;;; Two namespaces: `struct point' and a `point' typedef are separate
;;; declarations. Tags -- struct, union and enum alike -- share the
;;; second table between them
(define +type-db+ (make-hash-table)) ; typedefs and defines
(define +tag-db+ (make-hash-table)) ; struct, union and enums
;;; What type a *name* has, which neither of the two above records:
;;;
;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int)
;;; (var origin (struct point) ...) -> (struct point)
(define +name-db+ (make-hash-table))
(define (strip-pub form)
(if (eq? (car form) 'pub) (cdr form) form))
(define (comment-form? f)
(and (pair? f) (eq? (car f) 'comment)))
;;; Fields are written with the type last and one or more names before
;;; it, so ((x y int) (p (* char))) describes three fields. Flatten that
;;; into one (name type) per field, which is what a caller wants.
(define (normalize-fields fields)
(append-map
(lambda (field)
(if (comment-form? field)
(list)
(let ((type (last field))
(names (drop-right field 1)))
(map (lambda (name) (list name type)) names))))
(remove comment-form? fields)))
;;; ([pub] struct name (fields ...) . attrs)
(define (aggregate-fields form)
(let ((f (strip-pub form)))
(if (and (pair? (cddr f)) (list? (caddr f)))
(caddr f)
(list))))
(define (add-struct name form)
(hash-table-set! +tag-db+ name
(list 'struct name (normalize-fields (aggregate-fields form)))))
(define (add-union name form)
(hash-table-set! +tag-db+ name
(list 'union name (normalize-fields (aggregate-fields form)))))
;;; ([pub] enum name (value ...))
(define (add-enum name form)
(let ((f (strip-pub form)))
(hash-table-set! +tag-db+ name
(list 'enum name (if (and (pair? (cddr f)) (list? (caddr f)))
(caddr f)
(list))))))
;;; ([pub] typedef new-name target)
(define (add-typedef name form)
(hash-table-set! +type-db+ name
(list 'typedef name (last (strip-pub form)))))
;;; <stdint.h>, which nothing parses, as far as arithmetic asks: the
;;; prelude's `u8' is a `uint8-t', so (+ a a) over two of them is an
;;; `int', promoted like any narrow type. The 64-bit pair is `long' on
;;; some hosts; it ranks above the narrower ones either way.
(for-each (lambda (entry) (add-typedef (car entry) (cons 'typedef entry)))
'((int8-t (signed char)) (uint8-t (unsigned char))
(int16-t short) (uint16-t (unsigned short))
(int32-t int) (uint32-t (unsigned int))
(int64-t (long long)) (uint64-t (unsigned long long))))
;;; (define name value ...) -- a C #define, kept so a macro can read a
;;; compile-time constant rather than re-parse the source.
(define (add-define name form)
(hash-table-set! +type-db+ name
(list 'define name (cddr (strip-pub form)))))
;;; `(type-of x)' inside a macro body: the type of the expression the
;;; macro was handed, where `get-name-type' only answers for a name.
;;; The walker that can answer it lives in `semen', which is compiled
;;; after this, so it installs itself here for the length of one
;;; expansion. Outside one there is no scope to ask about, and the
;;; answer is #f.
(define current-type-of (make-parameter (lambda (form) #f)))
(define (type-of form) ((current-type-of) form))
(define (add-name-type! name type)
(hash-table-set! +name-db+ name type))
;;; #f for a name never declared, which is what `printf' looks like
;;; until something parses stdio.h. Not an error here; the caller
;;; decides.
(define (get-name-type name)
(hash-table-ref/default +name-db+ name #f))
;;; What `(make-adder 10)' has for a type: `make-adder's return type,
;;; or #f when NAME is not a function with a signature on record
(define (get-return-type name)
(let ((type (get-name-type name)))
(and (pair? type)
(eq? 'fn (car type))
(= 3 (length type))
(third type))))
(define (get-tag-info name)
(hash-table-ref/default +tag-db+ name #f))
;;; First look up the ordinary identifier, then tag of that id when
;;; no ordinary one was declared, as C does
(define (get-type-info name)
(or (hash-table-ref/default +type-db+ name #f)
(get-tag-info name)))
;;; ((name type) ...) for a struct or union, #f for anything else --
;;; including a name that was never declared. Callers give the better
;;; error, since they know what they wanted it for.
;;;
;;; A typedef is followed to what it stands for, so reflection over an
;;; alias works exactly as it does over the name it aliases.
(define (get-fields name)
(let ((info (resolve-type-info name)))
(and info
(memq (car info) '(struct union))
(caddr info))))
;;; Follow a typedef chain to the name it stands for. #f if NAME is
;;; not a typedef. A typedef that leads back to itself stops rather
;;; than spinning: nothing prevents one from being written.
(define (get-underlying-type name)
(let follow ((name name) (seen (list)))
(and (not (member name seen))
(let ((info (get-type-info name)))
(and info
(eq? (car info) 'typedef)
(let ((target (caddr info)))
(or (and (symbol? target) (follow target (cons name seen)))
target)))))))
;;; The declaration NAME ultimately names. For a typedef that is the
;;; entry of whatever it stands for, and for anything else it is
;;; NAME's own info
(define (target-tag target)
(cond
((symbol? target) target)
((and (pair? target)
(memq (car target) '(struct union enum))
(pair? (cdr target))
(symbol? (cadr target)))
(cadr target))
(else #f)))
(define (resolve-type-info name)
(let ((info (resolve-ordinary-type-info name)))
(if (and info (memq (car info) '(struct union enum)))
info
(or (get-tag-info name) info))))
(define (resolve-ordinary-type-info name)
(let ((info (get-type-info name)))
(and info
(if (eq? (car info) 'typedef)
(let ((tag (target-tag (get-underlying-type name))))
;; A typedef target is written in type position, where
;; `struct point' means the tag
(and tag (or (get-tag-info tag) (get-type-info tag))))
info))))
;;; The name methods, realizations and sums are filed under. A typedef
;;; is followed to the aggregate it names, and one that ends in anything
;;; else stops at the last typedef, so a scalar does not share them:
;;;
;;; (record v ...) (typedef alias v) alias -> v
;;; (typedef meters float) meters -> meters
;;; (typedef km meters) km -> meters
(define (type-key name)
(let follow ((name name) (seen (list)))
(let ((target (and (not (memq name seen)) (typedef-target name))))
(cond ((not target) name)
((symbol? target)
(if (typedef-target target) (follow target (cons name seen)) name))
((target-tag target))
(else name)))))
(define (typedef-target name)
(let ((info (and (symbol? name) (get-type-info name))))
(and info (eq? (car info) 'typedef) (caddr info))))
;;; A sum's variants, in declaration order:
;;;
;;; (sum shape ((circle ((r float))) (empty ())))
;;; -> shape -> ((circle (r float)) (empty))
;;;
;;; Fields are normalized, so a caller counts them and reads their
;;; types without re-parsing the declaration.
(define +sum-db+ (make-hash-table))
(define (add-sum! name variants)
(hash-table-set! +sum-db+ (type-key name) variants))
(define (get-sum name)
(hash-table-ref/default +sum-db+ (type-key name) #f))
;;; shape/circle -> (shape . circle), for each variant of each sum
(define +constructor-db+ (make-hash-table))
(define (add-constructor! constructor sum variant)
(hash-table-set! +constructor-db+ constructor (cons sum variant)))
(define (get-constructor name)
(hash-table-ref/default +constructor-db+ name #f))
(define (variant-fields variants name)
(let ((entry (assq name variants)))
(and entry (cdr entry))))
;;; Methods of an `ops' block: (type . method) -> the qualified name
;;; the call is rewritten to.
;;;
;;; (ops vec2 (fn length ((self (* const vec2))) float ...))
;;; -> (vec2 . length) -> vec2/length
;;;
;;; The signature is not kept here; `vec2/length' is an ordinary
;;; function by the time anything asks, so +name-db+ already has it.
(define +ops-db+ (make-hash-table))
(define (add-method! type method qualified)
(hash-table-set! +ops-db+ (cons (type-key type) method) qualified))
(define (get-method type method)
(hash-table-ref/default +ops-db+ (cons (type-key type) method) #f))
;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength
(define (qualify-op type name)
(string->symbol
(string-append (symbol->string type) "/" (symbol->string name))))
;;; The name an `ops' block was written against: `(struct point)' and a
;;; `const' wrapper both name `point', and anything else names nothing.
(define (ops-key type)
(cond ((symbol? type) (type-key type))
((not (and (pair? type) (symbol? (car type)))) #f)
((memq (car type) '(struct union enum))
(and (pair? (cdr type)) (symbol? (cadr type)) (cadr type)))
((memq (car type) '(const volatile)) (ops-key (cadr type)))
(else #f)))
;;; A spec is a parameter and a list of methods, each of which either
;;; declares a signature or also carries a default body:
;;;
;;; (spec (printable T) (fn show ((self (* const T))) void))
;;; -> printable -> (T (fn show ((self (* const T))) void))
;;;
;;; And a realization is only ever asked whether it exists -- the
;;; methods it provides land in +ops-db+ like any others.
(define +spec-db+ (make-hash-table))
(define +realize-db+ (make-hash-table))
(define (add-spec! name parameter methods)
(hash-table-set! +spec-db+ name (cons parameter methods)))
(define (get-spec name)
(hash-table-ref/default +spec-db+ name #f))
(define (spec-parameter spec) (car spec))
(define (spec-methods spec) (cdr spec))
(define (add-realization! spec type)
(hash-table-set! +realize-db+ (cons spec (type-key type)) #t))
;;; What a generic macro asks before it expands: (realizes? 'ord 'circle)
(define (realizes? spec type)
(hash-table-exists? +realize-db+ (cons spec (type-key type))))
;;; Sums, constructors, methods and specs refuse a second declaration
;;; of the same name, which is per translation unit rather than per
;;; process -- so a process that compiles two units has to start the
;;; second one clean.
(define (reset-declarations!)
(set! +sum-db+ (make-hash-table))
(set! +constructor-db+ (make-hash-table))
(set! +ops-db+ (make-hash-table))
(set! +spec-db+ (make-hash-table))
(set! +realize-db+ (make-hash-table)))
;;; Type matcher macro
;;; (type-match type
;;; (int ...)
;;; ((* const char) ...)
;;; ([int 10] ...)
;;; ((* _) ...) ; a pointer to anything
;;; ((¤ _ _) ...) ; an array of anything, any length
;;; (else ...))
;;;
;;; A type is a form, not an atom, so patterns are matched structurally
;;; rather than dispatched on like `case'. They are literal types and
;;; are not evaluated; `else' is optional and the whole thing is #f when
;;; nothing matches and there is no else.
;;;
;;; `_' in a pattern matches anything in that position, the same thing
;;; it means in a type. Without it every spelling has to be enumerated:
;;; `(closure ((int)) int)' and `(closure ((float)) int)' are separate
;;; clauses for what is one case.
;;;
;;; A `_' written last takes everything that remains, because a type's
;;; words are spread rather than nested -- `(* const char)' is three
;;; elements, so `(* _)' has to cover two of them to mean "a pointer to
;;; anything".
;;;
;;; Nothing destructures: a macro body is ordinary Scheme and a type is
;;; a list, so `(caddr (type-of x))' already reads the length out of
;;; `(¤ int 4)'.
(define-syntax type-match
(syntax-rules (else)
((_ type) #f)
((_ type (else body ...)) (begin body ...))
((_ type (pattern body ...) clause ...)
(if (type-pattern-matches? 'pattern type)
(begin body ...)
(type-match type clause ...)))))
(define (type-pattern-matches? pattern type)
(cond
((eq? pattern '_) #t)
((and (pair? pattern) (pair? type))
(if (and (eq? (car pattern) '_) (null? (cdr pattern)))
#t ; a trailing `_' takes the rest
(and (type-pattern-matches? (car pattern) (car type))
(type-pattern-matches? (cdr pattern) (cdr type)))))
(else (equal? pattern type))))
;;; Map function to each field/value of a structure/union/enum
;;; For enums, field-type is the type of the enum (since C 23), and
;;; field-name the enumerator's name, (wire-varint 0) or not
;;; (map-fields type-name
;;; (lambda (field-name field-type) ...))
;;;
;;; Returns #f if nothing of that name was declared
(define (map-fields struct-union-enum fn)
(let ((info (resolve-type-info struct-union-enum)))
(and info
(case (car info)
((struct union)
(map (lambda (field) (fn (car field) (cadr field)))
(caddr info)))
;; An enumerator's type is the enum itself -- named as it was
;; declared, since `enum some-typedef' is not a C type.
((enum)
(let ((type (list 'enum (cadr info))))
(map (lambda (value)
(fn (if (pair? value) (car value) value) type))
(caddr info))))
(else #f)))))
;;; The shape of a written type
;;;
;;; Where a type ends, asked by an arglist and by an array bound:
;;;
;;; (f1 float) a name and a type (unsigned int) a type
;;; (¤ int 4) four of int (¤ const t) unsized, of const t
;;; (¤ mytype N) N of mytype (¤ * size-t) unsized, of (* size-t)
;;; A qualifier cannot end a type: `(¤ const t)' is unsized, `(¤ int 4)'
;;; is four of int.
(define +c-qualifiers+ '(const volatile restrict _Atomic))
(define +c-specifiers+
'(void char short int long float double signed unsigned
bool _Bool complex _Complex))
;;; Does this list start a type rather than name one? `(const char)'
;;; and `(unsigned int)' are types; `(f1 float)' is a named parameter.
(define (type-head? form)
(and (pair? form)
(symbol? (car form))
(or (memq (car form) '(* ¤ struct union enum))
(memq (car form) +c-qualifiers+)
(memq (car form) +c-specifiers+))))
;;; Does the parameter name itself?
;;; (f1 float) does
;;; (float), (const char), (unsigned int) and (¤ float 4) do not
(define (named-arg? arg)
(and (pair? arg)
(pair? (cdr arg)) ; 1 element args are always type
(not (type-head? arg))))
;;; `(p (* struct point))' writes the type in one piece and
;;; `(p * struct point)' spreads it over the rest; both are
;;; `(* struct point)'
(define (named-arg-type param)
(if (null? (cddr param))
(second param)
(cdr param)))
;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int), and
;;; (self * const v) is ((* const v)) just as (self (* const v)) is.
;;; Anything that names nothing -- a variadic tail -- goes through
;;; untouched.
(define (arglist-types arglist)
(map (lambda (param)
(if (named-arg? param)
(list (named-arg-type param))
param))
arglist))
;;; The last element is a bound unless what precedes it is still
;;; waiting for a type name -- a `*', a tag's keyword, a qualifier with
;;; no type before it. C spells a type with one name at most, so a name
;;; after a name, or after a grouped type, can only be the bound:
;;;
;;; (¤ int 4) four of int (¤ unsigned int) unsized
;;; (¤ pthread-t CAP) CAP of pthread-t (¤ struct point) unsized
;;; (¤ (* T) CAP) CAP of (* T) (¤ const mytype) unsized
;;; (¤ int const N) N of const int (¤ * size-t) unsized
;;;
;;; TYPE is the whole `(¤ ...)' form.
(define (array-bound? type)
(and (> (length type) 2)
(let ((bound (last type))
(preceding (last (drop-right type 1))))
(cond
((and (pair? bound) (every pair? bound)
(aggregate-head? (drop-right (cdr type) 1)))
#f)
((not (symbol? bound)) #t)
((or (memq bound +c-specifiers+) (memq bound +c-qualifiers+)) #f)
((memq preceding '(* struct union enum)) #f)
((memq preceding +c-qualifiers+)
(any (lambda (word)
(not (or (memq word '(* struct union enum))
(memq word +c-qualifiers+))))
(drop-right (cdr type) 2)))
(else #t)))))
;;; Do WORDS end the way a struct's head does, so that a list of fields
;;; after them is its body? A list of anything else is a bound, as in
;;; (¤ struct point (* 2 N)):
;;;
;;; (struct) (struct point) heads (* struct point) (int) not
(define (aggregate-head? words)
(let ((tag-words (if (and (pair? words) (symbol? (last words))
(not (memq (last words) '(struct union enum))))
(drop-right words 1)
words)))
(and (pair? tag-words)
(memq (last tag-words) '(struct union enum))
#t)))
;;; [int 2 3] is two of [int 3], so it declares what [m 1 2] indexes,
;;; m[1][2]. Every trailing bound is a dimension, the first outermost:
;;;
;;; (¤ int 2 3) -> (¤ (¤ int 3) 2)
;;; (¤ char N 3) -> (¤ (¤ char 3) N)
;;; (¤ int 4) -> (¤ int 4)
(define (nest-array-type type)
(let peel ((base type) (bounds (list)))
(if (array-bound? base)
(peel (drop-right base 1) (cons (last base) bounds))
(if (< (length bounds) 2)
type
(let ((inner-first (reverse bounds)))
(fold (lambda (bound inner) (list '¤ inner bound))
(append base (list (car inner-first)))
(cdr inner-first)))))))
;;; How many elements a written array type has, when array-bound? says
;;; it says: (¤ int 4) -> 4, (¤ int 2 3) -> 2
(define (array-bound type)
(last (nest-array-type type)))
;;; What one element of a written array type is:
;;; (¤ struct point 2) -> (struct point), (¤ * const char 2) -> (* const char),
;;; (¤ int 2 3) -> (¤ int 3)
(define (array-element-type type)
(and (pair? type)
(eq? '¤ (car type))
(pair? (cdr type))
(let* ((type (nest-array-type type))
(words (if (array-bound? type)
(drop-right (cdr type) 1)
(cdr type))))
(and (pair? words)
(if (null? (cdr words)) (car words) words)))))