best way to write a source code generator?
- From: Frank Buss <fb@xxxxxxxxxxxxx>
- Date: Thu, 21 Sep 2006 21:00:31 +0200
If I want to create Java files and files in other languages like this:
public class Test {
public int foo;
public String bar;
public int getFoo() {
return foo;
}
public void setFoo(int foo) {
this.foo = foo;
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
public String serialize() {
return "foo=" + foo + " bar=" + Utils.escapeString(bar);
}
public static Test deserialize(String data) {
Test result = new Test();
String elements[] = data.split(" ");
for (String element in elements) {
String pair = element.split("=");
String name = pair[0];
String value = pair[1];
if (name.equals("foo")) {
foo = Integer.parseInt(value);
} else if (name.equals("bar")) {
bar = value;
}
}
}
}
How do I write a generator for this in Lisp? I've started with this:
(define-class "Test" ()
(("foo" number)
("bar" string)))
With this definitions:
(defparameter *classes* (make-hash-table :test 'equal))
(defmacro define-class (name base-class fields)
`(setf (gethash ,name *classes*) (cons (car ',base-class) ',fields)))
But then it starts getting ugly:
(defun write-java-classes ()
(loop for class being the hash-keys in *classes* using (hash-value value)
do
(let* ((filename (concatenate 'string *java-directory* class
".java"))
(custom-section (read-custom-section filename)))
(format t "writing file ~a~%" filename)
(with-open-file (s (concatenate 'string filename)
:direction :output
:if-exists :supersede)
(destructuring-bind (base-class . fields) value
(format s "public class ~a ~a implements Foo {~%"
class
(if base-class (format nil "extends ~a" base-class)
""))
(write-custom-section s custom-section)
(loop for (name type) in fields do
(format s " public ~a ~a = ~a;~%"
(get-java-type-name type)
name
(get-default-value type)))
(format s " public String serialize() throws Exception {~%")
....
Lots of formats and difficult to read code, because of mixed target
language code within format strings and Lisp code, which is difficult to
maintain. How can I improve this?
--
Frank Buss, fb@xxxxxxxxxxxxx
http://www.frank-buss.de, http://www.it4-systems.de
.
- Follow-Ups:
- Re: best way to write a source code generator?
- From: cmo
- Re: best way to write a source code generator?
- From: Paolo Amoroso
- Re: best way to write a source code generator?
- From: Ivan Shvedunov
- Re: best way to write a source code generator?
- From: Rob Warnock
- Re: best way to write a source code generator?
- From: Rainer Joswig
- Re: best way to write a source code generator?
- From: Pascal Costanza
- Re: best way to write a source code generator?
- Prev by Date: Re: Clipboard Access on Windows
- Next by Date: Re: How to distinguish gobal and local variables in lisp?
- Previous by thread: (read-from-string "#.(values) 42")
- Next by thread: Re: best way to write a source code generator?
- Index(es):
Relevant Pages
|