Re: best way to write a source code generator?



hi,

maybe 'linj' project have a connection with what you are trying to
achive
http://www.evaluator.pt/linj.html

the tutorial page may give some hints
http://www.evaluator.pt/downloads/tutorial.html

regards,

cmo-0

Frank Buss wrote:
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

.



Relevant Pages