3 ;;; Collections of properties
5 ;;; (c) 2009 Straylight/Edgeware
8 ;;;----- Licensing notice ---------------------------------------------------
10 ;;; This file is part of the Simple Object Definition system.
12 ;;; SOD is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2 of the License, or
15 ;;; (at your option) any later version.
17 ;;; SOD is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;;; GNU General Public License for more details.
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with SOD; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
28 ;;;--------------------------------------------------------------------------
29 ;;; Property representation.
31 (defun property-key (name)
32 "Convert NAME into a keyword.
34 If NAME isn't a symbol already, then flip its case (using FROB-CASE),
35 replace underscores by hyphens, and intern into the KEYWORD package."
38 (string (intern (substitute #\- #\_ (frob-case name)) :keyword))))
40 (defun property-type (value)
41 "Guess a sensible property type to use for VALUE."
52 (:constructor make-property
54 &key (type (property-type value))
57 &aux (key (property-key name))
58 (location (file-location %loc)))))
59 "A simple structure for holding a property in a property set.
61 The main useful feature is the ability to tick off properties which have
62 been used, so that we can complain about unrecognized properties.
64 An explicit type tag is necessary because we need to be able to talk
65 distinctly about identifiers, strings and symbols, and we've only got two
66 obvious Lisp types to play with. Sad, but true."
68 (name nil :type (or string symbol))
70 (type nil :type symbol)
71 (location (file-location nil) :type file-location)
72 (key nil :type symbol)
73 (seenp nil :type boolean))
75 (defun string-to-symbol (string &optional (package *package*))
76 "Convert STRING to a symbol in PACKAGE.
78 If PACKAGE is nil, then parse off a `PACKAGE:' prefix from STRING to
79 identify the package. A doubled colon allows access to internal symbols,
80 and will intern if necessary. Note that escape characters are /not/
81 processed; don't put colons in package names if you want to use them from
84 (let* ((length (length string))
85 (colon (position #\: string)))
86 (multiple-value-bind (start internalp)
87 (cond ((not colon) (values 0 t))
88 ((and (< (1+ colon) length)
89 (char= (char string (1+ colon)) #\:))
90 (values (+ colon 2) t))
92 (values (1+ colon) nil)))
94 (let* ((package-name (subseq string 0 colon))
95 (found (find-package package-name)))
97 (error "Unknown package `~A'" package-name))
98 (setf package found)))
99 (let ((name (subseq string start)))
100 (multiple-value-bind (symbol status)
101 (funcall (if internalp #'intern #'find-symbol) name package)
102 (cond ((or internalp (eq status :external))
105 (error "Symbol `~A' not found in package `~A'"
106 name (package-name package)))
108 (error "Symbol `~A' not external in package `~A'"
109 name (package-name package)))))))))
111 (defgeneric coerce-property-value (value type wanted)
113 "Convert VALUE, a property of type TYPE, to be of type WANTED.
115 It's sensible to add additional methods to this function, but there are
116 all the ones we need.")
118 ;; If TYPE matches WANTED, we'll assume that VALUE already has the right
119 ;; form. Otherwise, if nothing else matched, then I guess we'll have to
120 ;; say it didn't work.
121 (:method (value type wanted)
122 (if (eql type wanted)
124 (error "Incorrect type: expected ~A but found ~A" wanted type)))
126 ;; If the caller asks for type T then give him the raw thing.
127 (:method (value type (wanted (eql t)))
131 (:method ((value symbol) (type (eql :symbol)) (wanted (eql :keyword)))
133 (:method ((value string) (type (eql :id)) (wanted (eql :keyword)))
134 (string-to-symbol (substitute #\- #\_ (frob-case value)) :keyword))
135 (:method ((value string) (type (eql :string)) (wanted (eql :keyword)))
136 (string-to-symbol (frob-case value) :keyword))
139 (:method ((value string) (type (eql :id)) (wanted (eql :symbol)))
140 (string-to-symbol (substitute #\- #\_ (frob-case value))))
141 (:method ((value string) (type (eql :string)) (wanted (eql :symbol)))
142 (string-to-symbol (frob-case value)))
145 (:method ((value symbol) (type (eql :symbol)) (wanted (eql :id)))
146 (substitute #\_ #\- (frob-case (symbol-name value)))))
148 ;;;--------------------------------------------------------------------------
149 ;;; Property set representation.
151 ;;; There shouldn't be any code elsewhere which depends on the
152 ;;; representation. It's changed before; it may change again.
154 (defstruct (pset (:constructor %make-pset)
158 Wrapped up in a structure so that we can define a print function."
159 (hash (make-hash-table) :type hash-table))
161 (declaim (inline make-pset pset-get pset-store pset-map))
164 "Constructor for property sets."
167 (defun pset-get (pset key)
168 "Look KEY up in PSET and return what we find.
170 If there's no property by that name, return NIL."
171 (values (gethash key (%pset-hash pset))))
173 (defun pset-store (pset prop)
174 "Store property PROP in PSET.
176 Overwrite or replace any previous property with the same name. Mutates
178 (setf (gethash (p-key prop) (%pset-hash pset)) prop))
180 (defun pset-map (func pset)
181 "Call FUNC for each property in PSET."
182 (maphash (lambda (key value) (declare (ignore key)) (funcall func value))
185 ;;;--------------------------------------------------------------------------
186 ;;; `Cooked' property set operations.
188 (defun store-property
189 (pset name value &key (type (property-type value)) location)
190 "Store a property in PSET."
192 (make-property name value :type type :location location)))
194 (defun get-property (pset name type &optional default)
195 "Fetch a property from a property set.
197 If a property NAME is not found in PSET, or if a property is found, but
198 its type doesn't match TYPE, then return DEFAULT and NIL; otherwise return
199 the value and its file location. In the latter case, mark the property as
202 The value returned depends on the TYPE argument provided. If you pass NIL
203 then you get back the entire PROPERTY object. If you pass T, then you get
204 whatever was left in the property set, uninterpreted. Otherwise the value
205 is coerced to the right kind of thing (where possible) and returned.
207 If PSET is nil, then return DEFAULT."
209 (let ((prop (and pset (pset-get pset (property-key name)))))
210 (with-default-error-location ((and prop (p-location prop)))
212 (values default nil))
214 (setf (p-seenp prop) t)
215 (values prop (p-location prop)))
217 (setf (p-seenp prop) t)
218 (values (coerce-property-value (p-value prop)
221 (p-location prop)))))))
224 (pset name value &key (type (property-type value)) location)
225 "Add a property to PSET.
227 If a property with the same NAME already exists, report an error."
229 (with-default-error-location (location)
230 (let ((existing (get-property pset name nil)))
232 (error "Property ~S already defined~@[ at ~A~]"
233 name (p-location existing)))
234 (store-property pset name value :type type :location location))))
236 (defun make-property-set (&rest plist)
237 "Make a new property set, with given properties.
239 This isn't the way to make properties when parsing, but it works well for
240 programmatic generation. The arguments should form a property list
241 (alternating keywords and values is good).
243 An attempt is made to guess property types from the Lisp types of the
244 values. This isn't always successful but it's not too bad. The
245 alternative is manufacturing a PROPERTY-VALUE object by hand and stuffing
248 (do ((pset (make-pset))
249 (plist plist (cddr plist)))
251 (add-property pset (car plist) (cadr plist))))
253 (defmethod print-object ((pset pset) stream)
254 (print-unreadable-object (pset stream :type t)
255 (pprint-logical-block (stream nil)
257 (pset-map (lambda (prop)
258 (cond (firstp (setf firstp nil))
259 (t (write-char #\space stream)
260 (pprint-newline :linear stream)))
261 (format stream "~:@<~S ~@_~S ~@_~S~:>"
262 (p-name prop) (p-type prop) (p-value prop)))
265 (defun check-unused-properties (pset)
266 "Issue errors about unused properties in PSET."
268 (pset-map (lambda (prop)
269 (unless (p-seenp prop)
270 (cerror*-with-location (p-location prop)
271 "Unknown property `~A'"
275 ;;;--------------------------------------------------------------------------
276 ;;; Expression parser.
278 (defun parse-expression (lexer)
279 "Parse an expression from the LEXER.
281 The return values are the expression's VALUE and TYPE; currently the types
282 are :ID, :INTEGER, :STRING, and :CHAR. If an error prevented a sane value
283 being produced, the TYPE :INVALID is returned.
285 Expression syntax is rather limited at the moment:
287 expression : term | expression `+' term | expression `-' term
288 term : factor | term `*' factor | term `/' factor
289 factor : primary | `+' factor | `-' factor
290 primary : integer | identifier | string
292 | `?' lisp-expression
294 Identifiers are just standalone things. They don't name values. The
295 operators only work on integer values at the moment. (Confusingly, you
296 can manufacture rational numbers using the division operator, but they
297 still get called integers.)"
302 ;; The following is a simple operator-precedence parser: the
303 ;; recursive-descent parser I wrote the first time was about twice the
304 ;; size and harder to extend.
306 ;; The parser flips between two states, OPERAND and OPERATOR. It starts
307 ;; out in OPERAND state, and tries to parse a sequence of prefix
308 ;; operators followed by a primary expression. Once it's found one, it
309 ;; pushes the operand onto the value stack and flips to OPERATOR state;
310 ;; if it fails, it reports a syntax error and exits. The OPERAND state
311 ;; tries to read a sequence of postfix operators followed by an infix
312 ;; operator; if it fails, it assumes that it hit the stuff following the
313 ;; expression and stops.
315 ;; Each operator is pushed onto a stack consisting of lists of the form
316 ;; (FUNC PREC TY*). The PREC is a precedence -- higher numbers mean
317 ;; tighter binding. The TY* are operand types; operands are popped off
318 ;; the operand stack, checked against the requested types, and passed to
319 ;; the FUNC, which returns a new operand to be pushed in their place.
321 ;; Usually, when a binary operator is pushed, existing stacked operators
322 ;; with higher precedence are applied. Whether operators with /equal/
323 ;; precedence are also applied depends on the associativity of the
324 ;; operator: apply equal precedence operators for left-associative
325 ;; operators, don't apply for right-associative. When we reach the end
326 ;; of the expression, all the remaining operators on the stack are
329 ;; Parenthesized subexpressions are implemented using a hack: when we
330 ;; find an open paren in operand position, a fake operator is pushed with
331 ;; an artificially low precedece, which protects the operators beneath
332 ;; from premature application. The fake operator's function reports an
333 ;; error -- this will be triggered only if we reach the end of the
334 ;; expression before a matching close-paren, because the close-paren
335 ;; handler will pop the fake operator before it does any harm.
338 (labels ((apply-op (op)
339 ;; Apply the single operator list OP to the values on the
341 (let ((func (pop op))
343 (dolist (ty (reverse (cdr op)))
344 (let ((arg (pop valstack)))
345 (cond ((eq (car arg) :invalid)
348 (push (cdr arg) args))
350 (cerror* "Type mismatch: wanted ~A; found ~A"
354 (multiple-value-bind (type value) (apply func args)
355 (push (cons type value) valstack))
356 (push '(:invalid . nil) valstack))))
359 ;; Apply all operators with precedence PREC or higher.
361 (when (or (null opstack) (< (cadar opstack) prec))
363 (apply-op (pop opstack)))))
368 ;; Operand state. Push prefix operators, and try to read a
370 (case (token-type lexer)
372 ;; Aha. A primary. Push it onto the stack, and see if
373 ;; there's an infix operator.
374 ((:integer :id :string :char)
375 (push (cons (token-type lexer)
380 ;; Look for a Lisp S-expression.
382 (with-lexer-stream (stream lexer)
383 (let ((value (eval (read stream t))))
384 (push (cons (property-type value) value) valstack)))
387 ;; Arithmetic unary operators. Push an operator for `+' for
388 ;; the sake of type-checking.
390 (push (list (lambda (x) (values :integer x))
394 (push (list (lambda (x) (values :integer (- x)))
398 ;; The open-paren hack. Push a magic marker which will
399 ;; trigger an error if we hit the end of the expression.
400 ;; Inside the paren, we're still looking for an operand.
402 (push (list (lambda ()
403 (error "Expected `)' but found ~A"
404 (format-token lexer)))
408 ;; Failed to find anything. Report an error and give up.
410 (error "Expected expression but found ~A"
411 (format-token lexer))))
413 ;; Assume prefix operators as the default, so go round for more.
418 ;; Operator state. Push postfix operators, and try to read an
419 ;; infix operator. It turns out that we're always a token
420 ;; behind here, so catch up.
422 (case (token-type lexer)
426 (push (list (lambda (x y) (values :integer (+ x y)))
430 (push (list (lambda (x y) (values :integer (- x y)))
434 (push (list (lambda (x y) (values :integer (* x y)))
438 (push (list (lambda (x y)
440 (progn (cerror* "Division by zero")
441 (values nil :invalid))
442 (values (/ x y) :integer)))
446 ;; The close-paren hack. Finish off the operators pushed
447 ;; since the open-paren. If the operator stack is now empty,
448 ;; this is someone else's paren, so exit. Otherwise pop our
449 ;; magic marker, and continue looking for an operator.
456 ;; Nothing useful. Must have hit the end, so leave.
459 ;; Assume we found the binary operator as a default, so snarf a
460 ;; token and head back.
466 ;; Apply all the pending operators. If there's an unmatched
467 ;; open paren, this will trigger the error message.
470 ;; If everything worked out, we should have exactly one operand
471 ;; left. This is the one we want.
472 (assert (and (consp valstack)
473 (null (cdr valstack))))
474 (values (cdar valstack) (caar valstack)))
476 :report "Return an invalid value and continue."
477 (values nil :invalid)))))
479 ;;;--------------------------------------------------------------------------
480 ;;; Property set parsing.
482 (defun parse-property (lexer pset)
483 "Parse a single property from LEXER; add it to PSET."
484 (let ((name (require-token lexer :id)))
485 (require-token lexer #\=)
486 (multiple-value-bind (value type) (parse-expression lexer)
487 (unless (eq type :invalid)
488 (add-property pset name value :type type :location lexer)))))
490 (defun parse-property-set (lexer)
491 "Parse a property set from LEXER.
493 If there wasn't one to parse, return nil; this isn't considered an error,
494 and GET-PROPERTY will perfectly happily report defaults for all requested
497 (when (require-token lexer #\[ :errorp nil)
498 (let ((pset (make-pset)))
500 (parse-property lexer pset)
501 (unless (require-token lexer #\, :errorp nil)
503 (require-token lexer #\])
506 ;;;--------------------------------------------------------------------------
510 (with-input-from-string (raw "[role = before, integer = 42 * (3 - 1)]")
511 (let* ((in (make-instance 'position-aware-input-stream :stream raw))
512 (lexer (make-instance 'sod-lexer :stream in)))
515 (multiple-value-call #'values
516 (parse-property-set lexer)
517 (token-type lexer))))
519 ;;;----- That's all, folks --------------------------------------------------