简单脚本
这是 Common Lisp 中的一个示例,假设您的输入在文件 "/tmp/ex.cad" 中(也可以通过读取进程的输出流来获得)。
主要处理循环包括打开文件以获得输入流in(在with-open-file结束时自动关闭),循环文件中的所有表单,处理它们并可能输出它们到标准输出。您可以根据需要尽可能地复杂化该过程,但以下内容就足够了:
(with-open-file (in #"/tmp/ex.cad")
(let ((*read-eval* nil))
(ignore-errors
(loop (process-form (read in))))))
假设您想增加fp_line 条目的宽度,忽略fp_text 并打印未修改的表单,您可以定义process-form 如下:
(defun process-form (form)
(destructuring-bind (header . args) form
(print
(case header
(fp_line (let ((width (assoc 'width args)))
(when width (incf (second width) 3)))
form)
(fp_text (return-from process-form))
(t form)))))
运行前一个循环会输出:
(FP_LINE (START -27.04996 -3.986) (END -27.24996 -3.786) (LAYER F.FAB) (WIDTH 3.1))
(PAD "" NP_THRU_HOLE CIRCLE (AT 35.56 0) (SIZE 3.175 3.175) (DRILL 3.175) (LAYERS *.CU *.MASK) (CLEARANCE 1.5875))
(PAD 96 SMD RECT (AT 1.25 3.08473) (SIZE 0.29972 1.45034) (LAYERS F.CU F.PASTE F.MASK) (CLEARANCE 0.09906))
更安全
从那里,您可以根据需要借助模式匹配或宏构建更精细的管道。您必须考虑一些安全措施,例如将 *read-eval* 绑定到 nil,使用 with-standard-io-syntax
并按照 tfb 的建议将 *print-circte* 绑定到 T,禁止使用完全限定符号(通过让 #\: 发出错误信号)等等。最终,就像 Shell 脚本单行一样,您需要采取的预防措施add 取决于您对输入的信任程度:
;; Load libraries
(ql:quickload '(:alexandria :optima))
;; Import symbols in current package
(use-package :optima)
(use-package :alexandria)
;; Transform source into a stream
(defgeneric ensure-stream (source)
(:method ((source pathname)) (open source))
(:method ((source string)) (make-string-input-stream source))
(:method ((source stream)) source))
;; make reader stop on illegal characters
(defun abort-reader (&rest values)
(error "Aborting reader: ~s" values))
KiCad 符号的专用包(导出是可选的):
(defpackage :kicad
(:use)
(:export #:fp_text
#:fp_line
#:pad
#:size))
循环表单:
(defmacro do-forms ((form source &optional result) &body body)
"Loop over forms from source, eventually return result"
(with-gensyms (in form%)
`(with-open-stream (,in (ensure-stream ,source))
(with-standard-io-syntax
(let ((*read-eval* nil)
(*print-circle* t)
(*package* (find-package :kicad))
(*readtable* (copy-readtable)))
(set-macro-character #\: #'abort-reader nil)
(loop
:for ,form% := (read ,in nil ,in)
:until (eq ,form% ,in)
:do (let ((,form ,form%)) ,@body)
:finally (return ,result)))))))
例子:
;; Print lines at which there is a size parameter, and its value
(let ((line 0))
(labels ((size (alist) (second (assoc 'kicad:size alist)))
(emit (size) (when size (print `(:line ,line :size ,size))))
(process (options) (emit (size options))))
(do-forms (form #P"/tmp/ex.cad")
(match form
((list* 'kicad:fp_text _ _ options) (process options))
((list* 'kicad:fp_line options) (process options))
((list* 'kicad:pad _ _ _ options) (process options)))
(incf line))))
输出
(:LINE 2 :SIZE 3.175)
(:LINE 3 :SIZE 0.29972)