preprocessing java source

Per Bothner per@bothner.com
Sun Jun 24 13:16:00 GMT 2001


Ant allows files to be filtered, using the same syntax as autoconf
substitution variables: @TOKEN@. This has the advantage that it can
be implemented easily using sed or Ant or some other tool. I also use
the @TOKEN@ syntax in Kawa, simplemented using sed.
The problem is how to handle conditionals. In Kaw I uses @if TOKEN@
and @endif TOKEN@. This is easy enough to handle with sed, assuming
conditionals do not nest:
SED_COLLECTIONS_SUBS = $(SED_@JAVA_COLLECTIONS_SELECTED@_SUBS) \
 -e '1i\' -e '// DO NOT EDIT! -*- buffer-read-only: t -*-' 
SED_WITH_JAVA_COLLECTIONS_SUBS = \
 -e '/@if WITHOUT COLLECTIONS@/,/@endif WITHOUT COLLECTIONS@/d' \
 -e '/@*if WITH COLLECTIONS@/d'
SED_WITHOUT_JAVA_COLLECTIONS_SUBS = \
 -e '/@if WITH COLLECTIONS@/,/@endif WITH COLLECTIONS@/d' \
 -e '/@*if WITHOUT COLLECTIONS@/d'
Sequence.java: $(srcdir)/Sequence.java.in
 sed $(SED_COLLECTIONS_SUBS) \
	 -e '1s|//.*-Java-.*|// This file is automatically generated from Sequence.java.in.|' \
	 <$(srcdir)/Sequence.java.in >Sequence.java
(Notice the refinement of setting -*- buffer-read-only: t -*- in the output
file to prevent accidental editing if you're using Emacs.)
Two problems with this approach: The line numbers don't match up, plus
you can't (currently) use this approach with Ant. (Not an issue for libgcj,
but may be an issue for other libraries like Kawa.)
The solution may be to use comments. One approach is per-line:
 @if-FEATURE@ code for feature line1;
 @if-FEATURE@ code for feature line2;
with @if-FEATURE@ replaced by "" if FEATURE is enabled or "//" if feature is
dsiabled. The disadvantage of this is that a Java-aware editor is unlikely
to be able to handle lines starting with @if-FEATURE*, so you won't get
automatic indentation etc. On the other hand, it probably wouldn't be
that difficult to extend EMacs Java mode to handle these, if we declare
this a GNU standard.
The other solution uses block comments:
 @ifdef FEATURE@
 code for feature line1;
 code for feature line2;
 @endif FEATURE@
with @ifdef FEATURE@ and @endif FEATURE@ both replaced by "" if
FEATURE is enabled, or respectively "/* FEATURE disabled" and "*/"
if feature is disabled. This does allows better editing of the
conditional code. (Emacs does tolerably well editing Sequence.java.in.)
However, it doesn't allow you comment out code containing block comments.
Specifically, you can't comment out entire methods if they have Javadoc
comments. At least not using simple substitution as supported by Ant.
One can of course allow both styles, and that would be my suggestion.
-- 
	--Per Bothner
per@bothner.com http://www.bothner.com/per/


More information about the Java mailing list

AltStyle によって変換されたページ (->オリジナル) /