JML

org.multijava.mjc
Class Main

java.lang.Object
  extended byorg.multijava.util.Utils
      extended byorg.multijava.util.compiler.Compiler
          extended byorg.multijava.mjc.Main
All Implemented Interfaces:
Cloneable, TroubleReporter
Direct Known Subclasses:
CTopLevel.CTopLevel$1, Main, Main, Main, TestMjcParser.TestCompiler

public class Main
extends Compiler

This class implements the entry point of the MultiJava compiler. Use java org.multijava.mjc.Main --help to get usage options.


Nested Class Summary
 class Main.CheckInitializerTask
          This class typechecks the initializers of the declarations in the source code.
 class Main.CheckInterfaceTask
          This class checks the interfaces of the declarations in the source code.
static class Main.ContextBehavior
           
static class Main.DFilter
          This class is used with the Directory.list method to list the subdirectories in a directory (ignoring the special case of the 'CVS' subdirectory).
protected static class Main.ExpectedGF
           
protected static class Main.ExpectedIndifferent
           
protected static class Main.ExpectedResult
          This class represents the expected result of parsing a file.
protected static class Main.ExpectedType
           
static class Main.Filter
          This class is used with the Directory.list method to list those files in a directory that this program is interested in processing - in this case, all those that end in '.java'
 class Main.ParseTask
          This class parses a group of files, given by filenames as strings, and generates a forest of ASTs.
 class Main.PreprocessTask
          This class preprocesses type and generic function imports and groups external methods.
 class Main.PrettyPrintTask
          This class pretty prints the trees in the AST forest.
 class Main.ResolveSpecializerTask
          This class resolves value specializer expressions to the compile-time constants they represent.
 class Main.ResolveTopMethodTask
          This class resolves the top methods of all method declarations.
 class Main.Task
          This abstract class represents a single task to be performed by the compiler.
static class Main.TaskTimes
           
 class Main.TranslateMJTask
          This class pretty prints the trees in the AST forest.
 class Main.TreeProcessingTask
          This class is subclasses by classes that represent tasks operating on a forest of ASTs.
static interface Main.Trees
           
 class Main.TypecheckTask
          This class typechecks the source code.
 
Field Summary
protected  Object activeSequenceID
          SequenceID of the currently active Task.
protected  int activeTaskPriority
          The priority of the top-most active task, where top-most is defined in terms of the recursive invocations of processTaskQueue on the call stack.
protected  boolean allowUniverseAnnotations
          Enable the generation of extended bytecode that contains the Universe annotations.
protected  boolean allowUniverseBytecode
          Enable the generation of extended bytecode that contains the Universe annotations.
protected  boolean allowUniverseChecks
          Whether we should check the program for correctness according to the universe type system.
protected  boolean allowUniverseDynChecks
          Enable the generation of dynamic checks that verify that the universe invariant holds during the execution.
protected  boolean allowUniverseKeywords
          Whether the special tokens for the universe type system should be allowed.
protected  boolean allowUniversePurity
          Whether we should check the purity of methods.
private  HashSet alreadyParsedSet
          A set of files previously parsed by the compiler for which the results were not discarded.
protected  String appName
          The name of this app as it should be given in error or information messages.
protected  ArrayList classes
           
protected  boolean codeGenNeeded
           
private static boolean compilationInterrupted
           
private static Main.ContextBehavior contextBehavior
           
protected  HashSet contextsCreated
          Stores all the compilation unit contexts created for this compiler and not yet disposed of.
private  HashMap currentlyParsingRelation
          A relation mapping files currently being parsed by the compiler to the expected results.
protected  Destination destination
           
protected  boolean errorFound
          Records whether an error was found during processing of a task.
protected  int errorLimit
           
private  HashMap failedParsingRelation
          A relation mapping files already parsed by the compiler to the results that were expected but NOT found.
protected  boolean filesFound
          This simply serves to pass some additional information out of the call of parseArguments, in order to aid error reporting.
private  WarningFilter filter
           
private  Object mainSequenceID
          Stores an alias to the sequenceID of the task sequence created for the files given as command line arguments.
protected  int mostSevereWarningIssued
           
private static int nextUniqueTaskNumber
          A unique number that will be assigned to the next task created.
protected  MjcCommonOptions options
           
protected  boolean parseJavadoc
          When the following flag is false, the parser ignores javadoc comments (as it does regular comments); when the flag is true, javadoc comments are collected as part of the AST; derived classes should set this flag after the super class constructor is called, but before parsing is begun.
static int PRI_CHECK_INITIALIZER
           
static int PRI_CHECK_INTERFACE
           
static int PRI_PARSE
           
static int PRI_PREPROCESS
           
static int PRI_PRETTY_PRINT
           
static int PRI_RESOLVE_SPECIALIZER
           
static int PRI_TOP_METHODS
           
static int PRI_TRANSLATE_MJ
           
static int PRI_TYPECHECK
           
protected  TreeSet taskQueue
          Priority queue of tasks to be completed.
protected  boolean uncheckedWarningsIssued
          Whether any unchecked warning has been issued during compilation.
static String UNIVERSE_ANNOTATIONS
          AHS: Command line option that chooses Java 5 annotations as output style for universe modifiers.
static String UNIVERSE_BYTECODE
          Command line option to enable allowUniverseBytecode.
static String UNIVERSE_CHECKS
          Command line option to enable allowUniverseChecks.
static String UNIVERSE_DYNCHECKS
          Command line option to enable allowUniverseDynChecks.
static String UNIVERSE_FULL
          Command line option to make all universe features enabled.
static String UNIVERSE_NO
          Command line option to disable all universe features.
static String UNIVERSE_PARSE
          Command line option to enable allowUniverseKeywords.
static String UNIVERSE_PURITY
          Command line option to enable allowUniversePurity.
protected  String universeVersion
          Universe encoding version.
 
Fields inherited from class org.multijava.util.compiler.Compiler
PRINT_TO_ERR, PRINT_TO_OUT
 
Fields inherited from class org.multijava.util.Utils
DBG_LEVEL_HIGH, DBG_LEVEL_LOW, DBG_LEVEL_NO
 
Constructor Summary
Main()
           
Main(ModifierUtility modUtil)
           
 
Method Summary
protected  Object activeSequenceID()
          Returns the sequence ID of the currently active task.
private  void addFiles(File directory, ArrayList infiles)
          This is a helper function that (a) adds any relevant files in the directory to 'infiles', and (b) if we are searching directories recursively, calls addFiles on any subdirectories of 'directory'.
 void adoptCompilationUnitContext(CCompilationUnitContextType childContext)
          Signals to this compiler that the given context is no longer needed.
static void bugReportBoilerplate(boolean isReportBelow)
           
static void bugReportProperty(String key)
           
static void bugReportRequest(Throwable e, String[] args)
           
 void catchUp(File filename)
          Compiles the named file (using the options of the current compilation session) up to the same compilation pass as the currently active task in the task queue.
 void catchUp(JTypeDeclarationType decl)
          Compiles the given AST (using the options of the current compilation session) up to the same compilation pass as the currently active task in the task queue.
 void catchUpGF(File filename, String qualifiedName)
          This version of catchUp also parses the given file through the TaskQueue passes as far as other files have been processed, but: after the ParseTask phase, checks that the given qualifiedName actually has a successful generic function definition that is now loaded.
 void catchUpType(File filename, String qualifiedName)
          This version of catchUp also parses the given file through the TaskQueue passes as far as other files have been processed, but discards the result if the file did not contain a declaration of the type qualifiedName.
 String checkPackageName(String packageName, boolean quiet)
          Checks whether a syntactically valid package name actually exists, and returns the directory location of the root of the package or null if there is no package by that name on the sourcepath or classpath.
 void classToGenerate(CSourceClass clazz)
          Adds a class to the list of classes to be generated in bytecode.
static boolean compile(String[] args)
          Second entry point
static boolean compile(String[] args, MjcCommonOptions opt, OutputStream os)
          Entry point for the GUI
static Main.ContextBehavior contextBehavior()
           
 CCompilationUnitContextType createCompilationUnitContext(JCompilationUnitType jc, CCompilationUnit cunit)
          Creates a compilation unit context for this compiler.
protected  Main.Task createTaskAfter(Main.Task oldTask)
          This method uses the dynamic type of oldTask along with the command line options to determine what task to add to the task queue after the given task completes.
protected  void currentlyParsingFor(File f, Main.ExpectedResult expected)
          Registers with the current session that the given file is being parsed in hopes of finding the given expected result.
private  Set currentlyParsingSetFor(File f)
          Returns the set of expected results for processing the given file.
protected  String[] expandAtFiles(String[] infiles)
          Expands a list of files containing the @files syntax into a list of literal arguments.
 boolean experimentalArrayHandling()
           
protected  void failedParsing(File f, JCompilationUnitType cu)
          Called when a file is parsed and found to not contain the expected declarations.
protected  FilenameFilter filenameFilter()
          Overridable method that provides a filter to list all the relevant files in a directory; for mjc this is all files whose names end in ".java".
 Main.Task firstCheckingTask(JTypeDeclarationType decl)
          Generates the first task in the compilation sequence for an already formed AST.
 Main.ParseTask firstTask(File filename, Main.ExpectedResult expected)
          Generates the first task in the compilation sequence.
 Main.ParseTask firstTask(ArrayList infiles)
          Generates the first task in the compilation sequence.
 void genCode()
          Generates the code for all the classes.
 boolean Generic()
           
 boolean Generic(CClass host)
           
 CSourceClass[] getClasses()
          Returns the classes to generate
protected  WarningFilter getDefaultFilter()
          Return an instance of the default warning filter.
protected  WarningFilter getFilter()
          Return the warning filter.
protected  MjcCommonOptions getOptionsInstance(MjcCommonOptions opt)
          Used as a hook for other subclasses of mjc to override.
protected  String getWarningFilterNameFromOptions(MjcCommonOptions opts)
          Get the warning filter's class name from the options structure.
 void handleDirectories(ArrayList dirs, ArrayList infiles)
          This processes a list of directories found in the command-line, adding files to infiles as the overridable method sees fit; in this case any java files found in the directory are added.
 boolean handleNonOptions(ArrayList infiles)
          This method does any processing of the non-option arguments on the command-line, by mutating the given ArrayList (of String) containing all those arguments; this implementation replaces any directories by files within the directory that are eligible for processing.
 File handlePackageName(String packageName, ArrayList dirs)
          Finds the package named by 'packageName' and adds it to the list of File objects in 'dirs'.
 void handlePackages(ArrayList packages, ArrayList dirs, ArrayList infiles)
          Processes all the package names found on the command-line, altering the list of directories or files as appropriate.
protected  boolean hasAlreadyFailedToParseFor(File f, Main.ExpectedResult expected)
          Returns true if we have already tried and failed to parse the given file for the given expected result.
protected  boolean hasAlreadySuccessfullyParsed(File f)
          Returns true iff the given file has already been parsed and the results were not discarded.
protected  void initialize()
          Initialize the compiler (read classpath, initialize type descriptors)
protected  void initSession()
          Initializes this compilation session using the default "class loader".
protected  void initSession(TypeLoader l)
          Initializes this compilation session using the given type loader.
static void interruptCompilation()
          Interrupts an executing compilation process.
protected  boolean isAnExpectedResult(File f, JCompilationUnitType cu)
          Returns true iff the given compilation unit contains the results that were expected from parsing the given file.
protected  boolean isCurrentlyParsingFor(File f, Main.ExpectedResult expected)
          Returns true iff the given file is currently being parsed in hopes of finding the given expected result.
static void main(String[] args)
          Entry point
 Object mainSequenceID()
           
protected  MjcCommonOptions makeOptionsInstance()
          Overridable method that returns an instance of an object that will process command-line options.
 boolean nonNullTypes()
           
protected  void noteError()
          Register that an error was found during processing of a task.
 int optimizeCode()
           
 MjcCommonOptions options()
           
 boolean parseArguments(String[] args, ArrayList infiles)
          Parses the argument list.
protected  void parseAtFile(File f, ArrayList v)
          Does the actual tokenizing of the @-file, and puts each element into the list v.
 boolean parseComments()
          Returns true iff comments should be parsed (false if to be skipped)
 void prettyPrint(CompilerPassEnterable tree)
           
protected  void processTaskQueue()
          Reentrant procedure processes tasks from the task queue until all tasks have been completed whose priority is higher than the current priority when this was reentered.
 boolean quietMode()
          Returns true if quiet mode is enabled.
 boolean RecommendedWarning(String warning)
          Returns whether the recommended warnings type identified by warning is enabled in the compiler.
 void reportTrouble(Exception trouble)
          Reports a trouble (error or warning).
 void reportTroubleFiltered(Exception trouble)
          This method is intended for overriding by subclasses - all error and warning output (except that filtered out by the -w or -filter option) should pass through here.
 boolean RMJ()
           
 boolean run(String[] args)
          Runs a compilation session
 boolean run(String[] args, MjcCommonOptions opt, OutputStream os)
          Runs a compilation session for the GUI
protected  boolean runCompilation(long startTime)
          Runs the compilation session for both the command line and GUI
protected  boolean runInitialization(String[] args)
          Invoked from within the method run to do the argument parsing and compiler setup prior to actually parsing files via the task mechanism; returns true if no errors are encountered during initialization; if false is returned the initialization is not necessarily complete.
 boolean runParser(String[] args, MjcCommonOptions opt, ArrayList infiles)
          Runs the argument parser only so the GUI can process options from the command line
protected  void runSetInitialTasks(ArrayList infiles)
          Sets up the initial tasks that start the parsing.
 boolean safeMath()
           
protected  void setAllowUniverses(String option)
          From the given String parameter determine what universe checks should be enabled.
protected static void setContextBehavior(Main.ContextBehavior cb)
           
 void setMainSequenceID(Object sequenceID)
           
 void setUniverseChecks(boolean check)
          Used to temporarily disable universe checks, to not cause any confusion with dynamic universe type checks.
 void setUniversePurity(boolean check)
          Used to temporarily disable purity checks, to not cause any confusion with dynamic universe type checks.
protected  FilenameFilter subdirectoryFilter()
          Overridable method that provides a filter to list all the relevant subdirectories in a directory; for mjc this is all subdirectories that are not named 'CVS'.
protected  void successfullyParsed(File f)
          Called when a file is parsed and found to contain the expected declarations.
protected  boolean suppressWarning(CWarning warning)
          Returns true if the given warning should be suppressed.
protected  void taskQueueEmptied()
          This method is called by run(String[]) when all reentrant invocations of processTaskQueue() have been exited and in this implementation the method generates any required bytecode.
 boolean universeBytecode()
          Returns whether the extended bytecode for the universe type system should be enabled.
 boolean universeBytecodeAnnotations()
          Returns whether to use Java 5 annotations to represent universe modifiers in generated classfiles.
 boolean universeChecks()
          Returns whether the checking of universes should be enabled.
 boolean universeDynChecks()
          Returns whether the dynamic checks for the universe type system should be enabled.
 boolean universeKeywords()
          Returns whether the new keywords for the universe type system should be enabled.
 boolean universePurity()
          Returns whether the (conservative) purity checking of methods should be enabled.
 String universeVersion()
          Returns the version of the encoding used to the encode the universe type modifiers.
static boolean validPackageName(String name)
          Returns true if the string is syntactically a valid package name.
 boolean verboseMode()
           
 
Methods inherited from class org.multijava.util.compiler.Compiler
getTimestamp, inform, inform, inform, inform, inform, inform, inform, inform, inform, modUtil, run, setOutputStream, verifyFiles, verifyFiles
 
Methods inherited from class org.multijava.util.Utils
assertTrue, assertTrue, combineArrays, escapeString, escapeString, fail, fail, getFilePath, hasFlag, hasOtherFlags, parsePathParts, relativePathTo, splitQualifiedName, splitQualifiedName, stripJavaModifiers, stripNonJavaModifiers, stripPrivateModifier, unescapeString, vectorToArray, vectorToIntArray
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

contextBehavior

private static Main.ContextBehavior contextBehavior

filesFound

protected boolean filesFound
This simply serves to pass some additional information out of the call of parseArguments, in order to aid error reporting.


PRI_PARSE

public static final int PRI_PARSE

PRI_PREPROCESS

public static final int PRI_PREPROCESS

PRI_CHECK_INTERFACE

public static final int PRI_CHECK_INTERFACE

PRI_CHECK_INITIALIZER

public static final int PRI_CHECK_INITIALIZER

PRI_RESOLVE_SPECIALIZER

public static final int PRI_RESOLVE_SPECIALIZER

PRI_TOP_METHODS

public static final int PRI_TOP_METHODS

PRI_TYPECHECK

public static final int PRI_TYPECHECK

PRI_PRETTY_PRINT

public static final int PRI_PRETTY_PRINT

PRI_TRANSLATE_MJ

public static final int PRI_TRANSLATE_MJ

taskQueue

protected TreeSet taskQueue
Priority queue of tasks to be completed.

See Also:
Main.Task

activeTaskPriority

protected int activeTaskPriority
The priority of the top-most active task, where top-most is defined in terms of the recursive invocations of processTaskQueue on the call stack.


errorFound

protected boolean errorFound
Records whether an error was found during processing of a task.


errorLimit

protected int errorLimit

mostSevereWarningIssued

protected int mostSevereWarningIssued

uncheckedWarningsIssued

protected boolean uncheckedWarningsIssued
Whether any unchecked warning has been issued during compilation.


options

protected MjcCommonOptions options

filter

private WarningFilter filter

classes

protected ArrayList classes

destination

protected Destination destination

codeGenNeeded

protected boolean codeGenNeeded

contextsCreated

protected HashSet contextsCreated
Stores all the compilation unit contexts created for this compiler and not yet disposed of.

See Also:
createCompilationUnitContext(JCompilationUnitType, CCompilationUnit), adoptCompilationUnitContext(CCompilationUnitContextType)

parseJavadoc

protected boolean parseJavadoc
When the following flag is false, the parser ignores javadoc comments (as it does regular comments); when the flag is true, javadoc comments are collected as part of the AST; derived classes should set this flag after the super class constructor is called, but before parsing is begun.


mainSequenceID

private Object mainSequenceID
Stores an alias to the sequenceID of the task sequence created for the files given as command line arguments.

 private invariant (\forall Task t; t != null; 
                    t.sequenceID() == mainSequenceID <==>
                    (* t does not belong to a task sequence used to 
                       catch up recursively loaded files *));
 


activeSequenceID

protected Object activeSequenceID
SequenceID of the currently active Task.


currentlyParsingRelation

private HashMap currentlyParsingRelation
A relation mapping files currently being parsed by the compiler to the expected results.


failedParsingRelation

private HashMap failedParsingRelation
A relation mapping files already parsed by the compiler to the results that were expected but NOT found.


alreadyParsedSet

private HashSet alreadyParsedSet
A set of files previously parsed by the compiler for which the results were not discarded.


nextUniqueTaskNumber

private static int nextUniqueTaskNumber
A unique number that will be assigned to the next task created. This really should be a static member of the Task inner class, but Java does not allow inner classes to have static members.


appName

protected String appName
The name of this app as it should be given in error or information messages.


compilationInterrupted

private static boolean compilationInterrupted

allowUniverseKeywords

protected boolean allowUniverseKeywords
Whether the special tokens for the universe type system should be allowed. This separation was added for JML support, where special tokens with a preceding backslash will always be allowed. Then we need to be able to just turn on the typechecking. By WMD.


allowUniverseChecks

protected boolean allowUniverseChecks
Whether we should check the program for correctness according to the universe type system. For MultiJava this should always be the same as allowUniverseTokens, but for JML this might be different. There it should be possible to typecheck a program without the new keywords. Keywords within JML-comments starting with backslash will be used there. By WMD.


allowUniversePurity

protected boolean allowUniversePurity
Whether we should check the purity of methods. We currently have a rather restrictive definition of purity and there exist better, but more complex, algorithms. You can combine your own purity checks with our Universe checks by not enabling this option. This only influences the purity checking, the other universe rules are not influenced, i.e. we still only allow that pure methods are called on readonly references. By WMD.


allowUniverseDynChecks

protected boolean allowUniverseDynChecks
Enable the generation of dynamic checks that verify that the universe invariant holds during the execution. This creates checks for things like casts and instanceof tests. Needs allowUniverseChecks to also be true, to make sure that the static properties hold. By WMD.


allowUniverseBytecode

protected boolean allowUniverseBytecode
Enable the generation of extended bytecode that contains the Universe annotations. This version generates attributes containing the Universe modifiers. This allows easy compilation of programs without access to all source files. Needs allowUniverseChecks to also be true, to make sure that the static properties hold. By WMD.


allowUniverseAnnotations

protected boolean allowUniverseAnnotations
Enable the generation of extended bytecode that contains the Universe annotations. This version generates Java 5 annotations for the Universe modifiers. By AHS.


universeVersion

protected String universeVersion
Universe encoding version. By AHS.


UNIVERSE_FULL

public static final String UNIVERSE_FULL
Command line option to make all universe features enabled.


UNIVERSE_DYNCHECKS

public static final String UNIVERSE_DYNCHECKS
Command line option to enable allowUniverseDynChecks.


UNIVERSE_BYTECODE

public static final String UNIVERSE_BYTECODE
Command line option to enable allowUniverseBytecode.


UNIVERSE_ANNOTATIONS

public static final String UNIVERSE_ANNOTATIONS
AHS: Command line option that chooses Java 5 annotations as output style for universe modifiers.


UNIVERSE_PARSE

public static final String UNIVERSE_PARSE
Command line option to enable allowUniverseKeywords.


UNIVERSE_CHECKS

public static final String UNIVERSE_CHECKS
Command line option to enable allowUniverseChecks.


UNIVERSE_PURITY

public static final String UNIVERSE_PURITY
Command line option to enable allowUniversePurity.


UNIVERSE_NO

public static final String UNIVERSE_NO
Command line option to disable all universe features.

Constructor Detail

Main

public Main()

Main

public Main(ModifierUtility modUtil)
Method Detail

main

public static void main(String[] args)
Entry point

Parameters:
args - the command line arguments

compile

public static boolean compile(String[] args)
Second entry point


run

public boolean run(String[] args)
Runs a compilation session

Parameters:
args - the command line arguments

bugReportRequest

public static void bugReportRequest(Throwable e,
                                    String[] args)

bugReportBoilerplate

public static void bugReportBoilerplate(boolean isReportBelow)

bugReportProperty

public static void bugReportProperty(String key)

runParser

public boolean runParser(String[] args,
                         MjcCommonOptions opt,
                         ArrayList infiles)
Runs the argument parser only so the GUI can process options from the command line


compile

public static boolean compile(String[] args,
                              MjcCommonOptions opt,
                              OutputStream os)
Entry point for the GUI

Parameters:
args - the command line arguments
opt - the compiler options from the GUI
os - the output stream for the compiler messages

run

public boolean run(String[] args,
                   MjcCommonOptions opt,
                   OutputStream os)
Runs a compilation session for the GUI

Parameters:
args - the non-options: files, packages, and directories
opt - the compiler options
os - the output stream to use for output messages - if null, no change is made

getOptionsInstance

protected MjcCommonOptions getOptionsInstance(MjcCommonOptions opt)
Used as a hook for other subclasses of mjc to override. In these subclasses, the opt variable must be assigned to the local instance of the specific option class for that tool (such as MjcOptions is specific to mjc). Thus, methods that override this method must perform additional tasks before returning opt, because they must both assign opt to the local instance and to the protected variable MjcCommonOptions options in this class.

Parameters:
opt - The compiler options

interruptCompilation

public static final void interruptCompilation()
Interrupts an executing compilation process. Typically used by GUI to halt executing compilation process.


runInitialization

protected boolean runInitialization(String[] args)
Invoked from within the method run to do the argument parsing and compiler setup prior to actually parsing files via the task mechanism; returns true if no errors are encountered during initialization; if false is returned the initialization is not necessarily complete.

Parameters:
args - The array of command-line arguments
Returns:
true if no errors encountered during initialization

runCompilation

protected boolean runCompilation(long startTime)
Runs the compilation session for both the command line and GUI

Parameters:
startTime - The time the compilation started in the run method
Returns:
true if no errors encountered during compilation

expandAtFiles

protected String[] expandAtFiles(String[] infiles)
Expands a list of files containing the @files syntax into a list of literal arguments. See Sun's documentation for javac.


parseAtFile

protected void parseAtFile(File f,
                           ArrayList v)
Does the actual tokenizing of the @-file, and puts each element into the list v.


runSetInitialTasks

protected void runSetInitialTasks(ArrayList infiles)
Sets up the initial tasks that start the parsing. Additional tasks may be generated if these files reference other classes that need parsing.


initSession

protected void initSession()
Initializes this compilation session using the default "class loader".


initSession

protected final void initSession(TypeLoader l)
Initializes this compilation session using the given type loader.


contextBehavior

public static Main.ContextBehavior contextBehavior()

setContextBehavior

protected static void setContextBehavior(Main.ContextBehavior cb)

parseArguments

public boolean parseArguments(String[] args,
                              ArrayList infiles)
Parses the argument list. Mutates infiles, options: handles all options in the command-line, and puts all non-option arguments into 'infiles'.


handleNonOptions

public boolean handleNonOptions(ArrayList infiles)
This method does any processing of the non-option arguments on the command-line, by mutating the given ArrayList (of String) containing all those arguments; this implementation replaces any directories by files within the directory that are eligible for processing.

Returns:
true if the arguments are well-formed

validPackageName

public static boolean validPackageName(String name)
Returns true if the string is syntactically a valid package name.


handleDirectories

public void handleDirectories(ArrayList dirs,
                              ArrayList infiles)
This processes a list of directories found in the command-line, adding files to infiles as the overridable method sees fit; in this case any java files found in the directory are added.

Parameters:
dirs - a ArrayList of File objects
infiles - a ArrayList of String names of files

handlePackages

public void handlePackages(ArrayList packages,
                           ArrayList dirs,
                           ArrayList infiles)
Processes all the package names found on the command-line, altering the list of directories or files as appropriate. The implementation for mjc simply converts package names to the absolute path names of the directories in which they are found (per the sourcepath and classpath) and adds the directory to the list in dirs.

Parameters:
packages - the ArrayList of String containing a list of package names
dirs - a ArrayList of File containing a list of directory locations
infiles - a ArrayList of String containing a list of file paths

handlePackageName

public File handlePackageName(String packageName,
                              ArrayList dirs)
Finds the package named by 'packageName' and adds it to the list of File objects in 'dirs'.

Parameters:
packageName - the name of a package from the command-line
dirs - a list of File objects that are directories to be processed

checkPackageName

public String checkPackageName(String packageName,
                               boolean quiet)
Checks whether a syntactically valid package name actually exists, and returns the directory location of the root of the package or null if there is no package by that name on the sourcepath or classpath.


filenameFilter

protected FilenameFilter filenameFilter()
Overridable method that provides a filter to list all the relevant files in a directory; for mjc this is all files whose names end in ".java".


subdirectoryFilter

protected FilenameFilter subdirectoryFilter()
Overridable method that provides a filter to list all the relevant subdirectories in a directory; for mjc this is all subdirectories that are not named 'CVS'.


addFiles

private void addFiles(File directory,
                      ArrayList infiles)
This is a helper function that (a) adds any relevant files in the directory to 'infiles', and (b) if we are searching directories recursively, calls addFiles on any subdirectories of 'directory'. "Relevant files" are those that are selected by the FilenameFilter object that is returned by the method filenameFilter(). "Subdirectories" are those that are selected by the FilenameFilter object that is returned by the method subdirectoryFilter().


makeOptionsInstance

protected MjcCommonOptions makeOptionsInstance()
Overridable method that returns an instance of an object that will process command-line options.


createCompilationUnitContext

public CCompilationUnitContextType createCompilationUnitContext(JCompilationUnitType jc,
                                                                CCompilationUnit cunit)
Creates a compilation unit context for this compiler.

 requires cunit != null;
 ensures \result != null && contextsCreated.contains(\result);
 


adoptCompilationUnitContext

public void adoptCompilationUnitContext(CCompilationUnitContextType childContext)
Signals to this compiler that the given context is no longer needed.

 requires childContext != null && contextsCreated.contains(childContext);
 ensures !contextsCreated.contains(childContext);
 


firstTask

public Main.ParseTask firstTask(ArrayList infiles)
Generates the first task in the compilation sequence. This is a method so subclasses can modify the task sequence.

 requires infiles != null && (\forall Object o; infiles.contains(o);
                                  o instanceof String);
 


firstTask

public Main.ParseTask firstTask(File filename,
                                Main.ExpectedResult expected)
Generates the first task in the compilation sequence. This is a method so subclasses can modify the task sequence.

 requires filename != null && expected != null;
 


processTaskQueue

protected final void processTaskQueue()
Reentrant procedure processes tasks from the task queue until all tasks have been completed whose priority is higher than the current priority when this was reentered. The method returns true if the compilation had to be aborted prematurely because of errors, or false (with either errorFound true or false) if compilation ran to completion, possibly finding errors along the way.


taskQueueEmptied

protected void taskQueueEmptied()
This method is called by run(String[]) when all reentrant invocations of processTaskQueue() have been exited and in this implementation the method generates any required bytecode. This method should be overridden by subclasses to perform final work after completion of all tasks.


catchUp

public void catchUp(File filename)
Compiles the named file (using the options of the current compilation session) up to the same compilation pass as the currently active task in the task queue. Adds the result to the set of compilation units to be processed to completion.

Parameters:
filename - the file descriptor of the file to be compiled

 also
 requires filename != null && (* filename.canRead() *); // !FIXME!
 

catchUpType

public void catchUpType(File filename,
                        String qualifiedName)
This version of catchUp also parses the given file through the TaskQueue passes as far as other files have been processed, but discards the result if the file did not contain a declaration of the type qualifiedName.

 requires qualifiedName != null;
 requires filename != null;
 


catchUpGF

public void catchUpGF(File filename,
                      String qualifiedName)
This version of catchUp also parses the given file through the TaskQueue passes as far as other files have been processed, but: after the ParseTask phase, checks that the given qualifiedName actually has a successful generic function definition that is now loaded.

requires qualifiedName != null;
requires filename != null;
 


catchUp

public void catchUp(JTypeDeclarationType decl)

Compiles the given AST (using the options of the current compilation session) up to the same compilation pass as the currently active task in the task queue. Adds the result to the set of compilation units to be processed to completion.

Since in this statically overloaded method the argument is an AST for a type declaration some of the initial passes are skipped.

This entry point is accessed for compiling type declaration statements and anonymous class instantiation expressions.

Parameters:
decl - the AST for the type declaration to be compiled

 requires decl != null;
 

firstCheckingTask

public Main.Task firstCheckingTask(JTypeDeclarationType decl)
Generates the first task in the compilation sequence for an already formed AST. This is a method so subclasses can modify the task sequence.

 requires decl != null && decl.arePassParametersCached;
 


genCode

public void genCode()
Generates the code for all the classes.


initialize

protected void initialize()
Initialize the compiler (read classpath, initialize type descriptors)


verboseMode

public boolean verboseMode()
Description copied from class: Compiler
Returns true iff compilation runs in verbose mode.

Returns:
true if compilation in verbose mode

optimizeCode

public int optimizeCode()
Returns:
the optimization level

quietMode

public boolean quietMode()
Returns true if quiet mode is enabled.


RMJ

public boolean RMJ()
Returns:
true if supporting Relaxed MultiJava extensions

Generic

public boolean Generic()

Generic

public boolean Generic(CClass host)

RecommendedWarning

public boolean RecommendedWarning(String warning)
Returns whether the recommended warnings type identified by warning is enabled in the compiler.

Parameters:
warning - The recommended warning type to check for.
Returns:
Whether the given warning type is enabled.

safeMath

public boolean safeMath()
Returns:
true iff "safe math", i.e. integral arithmetic overflow, is enabled.

nonNullTypes

public boolean nonNullTypes()
Returns:
true iff the non-null type system is to be used.

experimentalArrayHandling

public boolean experimentalArrayHandling()

universeChecks

public boolean universeChecks()
Returns whether the checking of universes should be enabled. By WMD.

Returns:
true iff "universes", i.e. universe type modifiers, are enabled.
See Also:
allowUniverseChecks

setUniverseChecks

public void setUniverseChecks(boolean check)
Used to temporarily disable universe checks, to not cause any confusion with dynamic universe type checks. (The dyn.checks call methods taking peer arguments with rep variables. Universe typechecks don't allow this normally)

Parameters:
check - enable/disable universe checks. By scdaniel.

universeKeywords

public boolean universeKeywords()
Returns whether the new keywords for the universe type system should be enabled. By WMD.

See Also:
allowUniverseKeywords

universePurity

public boolean universePurity()
Returns whether the (conservative) purity checking of methods should be enabled. By WMD.

See Also:
allowUniversePurity

setUniversePurity

public void setUniversePurity(boolean check)
Used to temporarily disable purity checks, to not cause any confusion with dynamic universe type checks. (The dyn.checks call non-pure methods, the purity checks would not allow this)

Parameters:
check - enable/disable purity checks.

universeDynChecks

public boolean universeDynChecks()
Returns whether the dynamic checks for the universe type system should be enabled. By WMD.

See Also:
allowUniverseBytecode

universeBytecode

public boolean universeBytecode()
Returns whether the extended bytecode for the universe type system should be enabled. By WMD.

See Also:
allowUniverseBytecode

universeBytecodeAnnotations

public boolean universeBytecodeAnnotations()
Returns whether to use Java 5 annotations to represent universe modifiers in generated classfiles. By AHS.

See Also:
#unverseBytecodeAnnotations

universeVersion

public String universeVersion()
Returns the version of the encoding used to the encode the universe type modifiers. By AHS.

See Also:
universeVersion

setAllowUniverses

protected void setAllowUniverses(String option)
From the given String parameter determine what universe checks should be enabled. By WMD.


reportTrouble

public void reportTrouble(Exception trouble)
Reports a trouble (error or warning). All error and warning output should go through this method so that subclasses can handle such output as they see fit (it is best if all output other than the progress output that is shut off by -quiet go through here - no direct uses of System.out).

Parameters:
trouble - a description of the trouble to report.

reportTroubleFiltered

public void reportTroubleFiltered(Exception trouble)
This method is intended for overriding by subclasses - all error and warning output (except that filtered out by the -w or -filter option) should pass through here. The implementation here sends it to System.out or System.err, but subclasses can do whatever - write to a file, put up a dialog, etc.

Parameters:
trouble - An exception indicating the error or warning. This will often be a PositionedError or FormattedException containing information about a source location, but might also be an unexpected exception that is thrown somewhere.

suppressWarning

protected boolean suppressWarning(CWarning warning)
Returns true if the given warning should be suppressed.


getFilter

protected WarningFilter getFilter()
Return the warning filter.


getWarningFilterNameFromOptions

protected String getWarningFilterNameFromOptions(MjcCommonOptions opts)
Get the warning filter's class name from the options structure. This is a hook method that can be overridden by subclasses.

Returns:
null if there is no warning filter option specified.

getDefaultFilter

protected WarningFilter getDefaultFilter()
Return an instance of the default warning filter. This is a hook method that can be overridden by subclasses.


parseComments

public boolean parseComments()
Returns true iff comments should be parsed (false if to be skipped)


getClasses

public CSourceClass[] getClasses()
Returns the classes to generate


classToGenerate

public void classToGenerate(CSourceClass clazz)
Adds a class to the list of classes to be generated in bytecode.

 requires clazz != null;
 assignable classes;
 ensures classes.contains(clazz);
 


currentlyParsingFor

protected final void currentlyParsingFor(File f,
                                         Main.ExpectedResult expected)
Registers with the current session that the given file is being parsed in hopes of finding the given expected result.

 requires f != null && expected != null;
 


isCurrentlyParsingFor

protected final boolean isCurrentlyParsingFor(File f,
                                              Main.ExpectedResult expected)
Returns true iff the given file is currently being parsed in hopes of finding the given expected result.

 requires f != null && expected != null;
 


isAnExpectedResult

protected final boolean isAnExpectedResult(File f,
                                           JCompilationUnitType cu)
Returns true iff the given compilation unit contains the results that were expected from parsing the given file.

 requires f != null;
 requires (* currentlyParsingRelation.containsKey(getFilePath(f)) *);
 


currentlyParsingSetFor

private final Set currentlyParsingSetFor(File f)
Returns the set of expected results for processing the given file. The result is an alias to the set stored in currentlyParsingRelation and can be mutated to change the set of expected results mapped to be the given file.

 requires f != null;
 


hasAlreadyFailedToParseFor

protected final boolean hasAlreadyFailedToParseFor(File f,
                                                   Main.ExpectedResult expected)
Returns true if we have already tried and failed to parse the given file for the given expected result.


failedParsing

protected final void failedParsing(File f,
                                   JCompilationUnitType cu)
Called when a file is parsed and found to not contain the expected declarations. This method removes the given file from the set of those currently being parsed. The method also removes from the global cache all reference to the given compilation unit.


successfullyParsed

protected final void successfullyParsed(File f)
Called when a file is parsed and found to contain the expected declarations. This method removes the given file from the set of those currently being parsed and adds it to the set of already parsed files.


hasAlreadySuccessfullyParsed

protected final boolean hasAlreadySuccessfullyParsed(File f)
Returns true iff the given file has already been parsed and the results were not discarded.

 requires f != null;
 


createTaskAfter

protected Main.Task createTaskAfter(Main.Task oldTask)
This method uses the dynamic type of oldTask along with the command line options to determine what task to add to the task queue after the given task completes.

 requires oldTask != null && oldTask.completed;
 ensures \result == null || 
         (\result.sequenceID() == oldTask.sequenceID());
 


setMainSequenceID

public void setMainSequenceID(Object sequenceID)

mainSequenceID

public Object mainSequenceID()

activeSequenceID

protected Object activeSequenceID()
Returns the sequence ID of the currently active task. If no task is active, null is returned.


prettyPrint

public void prettyPrint(CompilerPassEnterable tree)

noteError

protected void noteError()
Register that an error was found during processing of a task.


options

public MjcCommonOptions options()

JML

JML is Copyright (C) 1998-2002 by Iowa State University and is distributed under the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This release depends on code from the MultiJava project and is based in part on the Kopi project Copyright (C) 1990-99 DMS Decision Management Systems Ges.m.b.H.