signature:
public class CircularArrayMap { /** * Expands the size of the storage to whichever is the larger of 1.5 times the old size , or an array large enough to
 * hold the proposed key that caused the expansion , copying the old data into a new array .
 * @ param key The key that was too large and caused expansion . */
private void expand ( int key ) { } }

implementation:
// Set the new size to whichever is the larger of 1.5 times the old size , or an array large enough to hold
// the proposed key that caused the expansion .
int newFactorSize = ( ( length * 3 ) / 2 ) + 1 ; int newSpaceSize = spaceRequired ( key ) ; int newSize = ( newSpaceSize > newFactorSize ) ? newSpaceSize : newFactorSize ; Object [ ] oldData = data ; data = new Object [ newSize ] ; // The valid data in the old array runs from offset ( start ) to offset ( end ) when offset ( start ) < offset ( end ) , and
// from offset ( start ) to length - 1 and 0 to offset ( end ) when offset ( start ) > = offset ( end ) .
int offsetStart = offset ( start ) ; int offsetEnd = offset ( end ) ; if ( offsetStart < offsetEnd ) { System . arraycopy ( oldData , offsetStart , data , 0 , end - start ) ; } else { System . arraycopy ( oldData , offsetStart , data , 0 , length - offsetStart ) ; System . arraycopy ( oldData , 0 , data , length - offsetStart , offsetEnd ) ; } offset = - start ; length = newSize ;


signature: public class SeleniumRadioControl { @ Override public void setValue ( String value ) { } }

implementation: checkArgument ( ! UNCHECKED_VALUE . equals ( value ) , "Cannot uncheck radio control" ) ; super . setValue ( value ) ;


signature:
public class TextGridImpl { /** * { @ inheritDoc } */
public void insert ( String string , int c , int r ) { } }

implementation: for ( char character : string . toCharArray ( ) ) { internalInsert ( character , c ++ , r ) ; } updateListeners ( ) ;


signature:
public class TextGridImpl { /** * { @ inheritDoc } */
public char getCharAt ( int c , int r ) { } }

implementation: Character character = data . get ( ( long ) c , ( long ) r ) ; if ( character == null ) { return ' ' ; } else { return character ; }


signature:
public class TextGridImpl { /** * { @ inheritDoc } */
public TextGridModel createInnerGrid ( int c , int r , int w , int h ) { } }

implementation: return new NestedTextGridImpl ( c , r , w , h , this ) ;


signature:
public class TextGridImpl { /** * { @ inheritDoc } */
public TextTableModel createTable ( int c , int r , int w , int h ) { } }

implementation:
// Supply a text table , with this grid set up to listen for updates to the table , and to be re - rendered as the
// table changes .
TextTableModel textTable = new TextTableImpl ( ) ; textTable . addTextTableListener ( new TableListener ( ) ) ; return textTable ;


signature:
public class TextGridImpl { /** * Notifies all interested listeners of an update to this model . */
protected void updateListeners ( ) { } }

implementation: TextGridEvent event = new TextGridEvent ( this ) ; for ( TextGridListener listener : listeners ) { listener . changedUpdate ( event ) ; }


signature:
public class TextGridImpl { /** * Inserts a single character into the grid at the specified location . This is a private insert method , that does
 * not notify model listeners , so that the public insert methods can do that as a separate step .
 * @ param character The character to insert .
 * @ param c The column position .
 * @ param r The row position . */
private void internalInsert ( char character , int c , int r ) { } }

implementation: maxColumn = ( c > maxColumn ) ? c : maxColumn ; maxRow = ( r > maxRow ) ? r : maxRow ; data . put ( ( long ) c , ( long ) r , character ) ;


signature:
public class SentenceParser { /** * Parses the next sentence from the current token source .
 * @ return The fully parsed syntax tree for the next sentence , or null if no more sentences are available , for
 * example , because an end of file has been reached .
 * @ throws SourceCodeException If the source being parsed does not match the grammar . */
public Sentence < Clause > parse ( ) throws SourceCodeException { } }

implementation: if ( parser . peekAndConsumeEof ( ) ) { return null ; } else { return new SentenceImpl < Clause > ( parser . sentence ( ) ) ; }


signature:
public class Cut { /** * { @ inheritDoc } */
public boolean proofStep ( ResolutionState state ) { } }

implementation:
if ( TRACE ) { /* trace . fine ( state . getTraceIndenter ( ) . generateTraceIndent ( ) + " Cutting choice points . . . " ) ; */
} Queue < ResolutionState > choicePointStates = parentChoicePointState . getChoicePoints ( ) ; if ( choicePointStates != null ) { for ( ResolutionState choicePointState : choicePointStates ) { choicePointState . cut ( ) ; } } state . getGoalStack ( ) . poll ( ) ; return true ;


signature:
public class UniformCostComparator { /** * Compares two search nodes by their path cost .
 * @ param object1 The first search node to compare .
 * @ param object2 The second search node to compare .
 * @ return 1 if the first node has a higher path cost than the second , - 1 if it has a lower path cost and 0 if they
 * have the same path cost . */
public int compare ( SearchNode object1 , SearchNode object2 ) { } }

implementation: float cost1 = object1 . getPathCost ( ) ; float cost2 = object2 . getPathCost ( ) ; return ( cost1 > cost2 ) ? 1 : ( ( cost1 < cost2 ) ? - 1 : 0 ) ;


signature:
public class IntegerType { /** * { @ inheritDoc } */
public void accept ( TermVisitor visitor ) { } }

implementation: if ( visitor instanceof IntegerTypeVisitor ) { ( ( IntegerTypeVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; }


signature:
public class DynamicOperatorParser { /** * Parses a flat list of terms , which are literals , variables , functors , or operators into a tree in such a way that
 * the operators associativity and precendence is obeyed .
 * @ param terms A flat list of terms possibly containing operators , to be parsed .
 * @ return The functor at the root of the sequence of terms parsed into an abstract syntax tree .
 * @ throws SourceCodeException If the list of terms does not form a valid syntactical construction under the current
 * set of defined operators . */
public Term parseOperators ( Term [ ] terms ) throws SourceCodeException { } }

implementation:
// Initialize the parsers state .
stack . offer ( 0 ) ; state = 0 ; position = 0 ; nextTerm = null ; // Consume the terms from left to right .
for ( position = 0 ; position <= terms . length ; ) { Symbol nextSymbol ; // Decide what the next symbol to parse is ; candidate op , term or final .
if ( position < terms . length ) { nextTerm = terms [ position ] ; if ( nextTerm instanceof CandidateOpSymbol ) { nextSymbol = Symbol . Op ; } else { nextSymbol = Symbol . Term ; } } else { nextSymbol = Symbol . Final ; } // Look in the action table to find the action associated with the current symbol and state .
Action action = actionTable [ state ] [ nextSymbol . ordinal ( ) ] ; // Apply the action .
action . apply ( ) ; } return ( Functor ) outputStack . poll ( ) ;


signature:
public class DynamicOperatorParser { /** * Sets the priority and associativity of a named operator in this table . This method may be used to remove
 * operators by some implementations , through a special setting of the priority value . A priority value of zero will
 * remove any existing operator matching the fixity of the one specified ( that is pre , or post / infix ) . To be
 * accepted , the operator must have a priority between 0 and 1200 inclusive , and can only be a postfix operator when
 * an infix is not already defined with the same name , and similarly for infix operators when a postfix operator is
 * already defined .
 * @ param name The interned name of the operator to set in the table .
 * @ param textName The text name of the operator to set in the table .
 * @ param priority The priority of the operator . Zero removes the operator .
 * @ param associativity The associativity of the operator . */
public void setOperator ( int name , String textName , int priority , OpSymbol . Associativity associativity ) { } }

implementation:
// Check that the name of the operator is valid .
// Check that the priority of the operator is valid .
if ( ( priority < 0 ) || ( priority > 1200 ) ) { throw new IllegalArgumentException ( "Operator priority must be between 0 and 1200 inclusive." ) ; } OpSymbol opSymbol = new OpSymbol ( name , textName , associativity , priority ) ; // Consult the defined operators to see if there are any already defined that match the name of the
// new definition , otherwise a map of operators by fixity needs to be created .
EnumMap < OpSymbol . Fixity , OpSymbol > operatorMap = operators . get ( textName ) ; // Check if the priority is non - zero in which case the operator is being added or redefined .
if ( priority > 0 ) { if ( operatorMap == null ) { operatorMap = new EnumMap < OpSymbol . Fixity , OpSymbol > ( OpSymbol . Fixity . class ) ; operators . put ( textName , operatorMap ) ; } // Check if the operators fixity to see if further rules regarding simultaneous definition of post and
// infix operators need to be applied .
if ( opSymbol . isPostfix ( ) ) { // Postfix , so check if an infix definition already exists , which is not allowed .
if ( operatorMap . containsKey ( OpSymbol . Fixity . In ) ) { throw new IllegalArgumentException ( "Cannot define a postfix operator when an infix one with the same name already exists." ) ; } } else if ( opSymbol . isInfix ( ) ) { // Infix , so check if a postfix definition already exists , which is not allowed .
if ( operatorMap . containsKey ( OpSymbol . Fixity . Post ) ) { throw new IllegalArgumentException ( "Cannot define an infix operator when an postfix one with the same name already exists." ) ; } } // Add the operator to the table replacing any previous definition of the same fixity .
operatorMap . put ( opSymbol . getFixity ( ) , opSymbol ) ; } else { // The priority is zero , in which case the operator is to be removed .
if ( ( operatorMap != null ) && opSymbol . isPrefix ( ) ) { // Remove it from the prefix table , if it exists there .
operatorMap . remove ( OpSymbol . Fixity . Pre ) ; } else if ( ( operatorMap != null ) && ( opSymbol . isPostfix ( ) || opSymbol . isInfix ( ) ) ) { // Remove it from the postfix / infix table , if it exists there .
operatorMap . remove ( OpSymbol . Fixity . Post ) ; operatorMap . remove ( OpSymbol . Fixity . In ) ; } }


signature:
public class DynamicOperatorParser { /** * Checks the operator table for all possible operators matching a given name .
 * @ param name The interned name of the operator to find .
 * @ return An array of matching operators , or < tt > null < / tt > if none can be found . */
public EnumMap < OpSymbol . Fixity , OpSymbol > getOperatorsMatchingNameByFixity ( String name ) { } }

implementation: return operators . get ( name ) ;


signature:
public class DynamicOperatorParser { /** * Checks if a candidate operator symbol can have one of the specified fixities , and resolve it to an oeprator with
 * that fixity if so . If it cannot be resolved an exception is raised .
 * @ param candidate The candidate operator symbol to resolve .
 * @ param fixities The possible fixities to resolve the symbol to .
 * @ return The candidate operator resolved to an actual operator .
 * @ throws SourceCodeException If the candidate operator cannot be resolved . */
protected static OpSymbol checkAndResolveToFixity ( CandidateOpSymbol candidate , OpSymbol . Fixity ... fixities ) throws SourceCodeException { } }

implementation: OpSymbol result = null ; for ( OpSymbol . Fixity fixity : fixities ) { result = candidate . getPossibleOperators ( ) . get ( fixity ) ; if ( result != null ) { break ; } } if ( result == null ) { throw new SourceCodeException ( "Operator " + candidate + " must be one of " + Arrays . toString ( fixities ) + ", but does not have the required form." , null , null , null , candidate . getSourceCodePosition ( ) ) ; } return result ;


signature:
public class SearchNode { /** * Expands a node into its successors . The successors are added to the specified collection which is returned as the
 * result of this function . The reason that the collection is passed as an argument is that there are many different
 * styles of buffer ( fifo , lifo , etc ) that search functions can use to implement different kinds of search and it is
 * more efficient to expand directly into the buffer than to have to copy the results into it after this method is
 * called , which would be the case if this method returned a collection .
 * < p > If a repeated state filter has been attached to the search nodes then this method applies it here to all the
 * potential successor states . Only those that pass the filter are expanded into the collection .
 * @ param expandInto The collection to place the successors in .
 * @ param reverse When set , indicates that the expansion should be done backwards .
 * @ return The number of successor expanded .
 * @ throws SearchNotExhaustiveException If the successor nodes cannot be created . This may happen when using a
 * custom node implementation that is not publicly accessible or that causes
 * other class loading / creation errors . */
public int expandSuccessors ( Queue < SearchNode < O , T > > expandInto , boolean reverse ) throws SearchNotExhaustiveException { } }

implementation:
// Used to keep count of the number of successors .
int numSuccessors = 0 ; for ( Iterator < Successor < O > > successors = getState ( ) . successors ( reverse ) ; successors . hasNext ( ) ; ) { numSuccessors ++ ; // Get the next successor state
Successor < O > next = successors . next ( ) ; // Check if a repeated state filter is to be applied
if ( repeatedStateFilter != null ) { // Filter the successor state and check if it should be accepted
if ( repeatedStateFilter . evaluate ( ( T ) next . getState ( ) , this ) ) { // Add the filtered state to the successors
expandInto . offer ( makeNode ( next ) ) ; } } // No repeated state filter is to be applied so add the successor state
else { expandInto . offer ( makeNode ( next ) ) ; } } // Successors have been expanded .
expanded = true ; return numSuccessors ;


signature:
public class SearchNode { /** * Makes a new node of the same type as this one from a Successor state .
 * @ param successor The successor state to turn into a search node .
 * @ return A search node covering the successor state .
 * @ throws SearchNotExhaustiveException If the successor nodes cannot be created . This may happen when using a
 * custom node implementation that is not publicly accessible or that causes
 * other class loading / creation errors . */
public SearchNode < O , T > makeNode ( Successor successor ) throws SearchNotExhaustiveException { } }

implementation:
SearchNode newNode ; try { // Create a new instance of this class
newNode = getClass ( ) . newInstance ( ) ; // Set the state , operation , parent , depth and cost for the new search node
newNode . state = successor . getState ( ) ; newNode . parent = this ; newNode . appliedOp = successor . getOperator ( ) ; newNode . depth = depth + 1 ; newNode . pathCost = pathCost + successor . getCost ( ) ; // Check if there is a repeated state filter and copy the reference to it into the new node if so
if ( repeatedStateFilter != null ) { newNode . setRepeatedStateFilter ( repeatedStateFilter ) ; } return newNode ; } catch ( InstantiationException e ) { // In practice this should never happen but may if the nodes if some class loader error were to occur whilst
// using a custom node implementation . Rethrow this as a RuntimeException .
throw new IllegalStateException ( "InstantiationException during creation of new search node." , e ) ; } catch ( IllegalAccessException e ) { // In practice this should never happen but may if the nodes to use are not public whilst using a custom node
// implementation . Rethrow this as a RuntimeException .
throw new IllegalStateException ( "IllegalAccessException during creation of new search node." , e ) ; }


signature:
public class ClientOutputStream { /** * Writes the specified byte < code > b < / code > to this output stream .
 * @ param b The byte to write .
 * @ throws IOException If an IOException occurs in the wrapped sink stream or a remote exception occurs . */
public void write ( int b ) throws IOException { } }

implementation: try { sink . write ( b ) ; } catch ( RemoteException e ) { throw new IOException ( "There was a Remote Exception." , e ) ; }


signature:
public class ClientOutputStream { /** * Writes bytes from the specified byte array < code > b < / code > , starting from index specified by < code > off < / code > , and
 * continuing for < code > len < / code > bytes , to this output stream .
 * @ param b The data .
 * @ param off The start offset in the data .
 * @ param len The number of bytes to write .
 * @ throws IOException If an IOException occurs in the wrapped sink stream or a remote exception occurs . */
public void write ( byte [ ] b , int off , int len ) throws IOException { } }

implementation: try { sink . write ( b , off , len ) ; } catch ( RemoteException e ) { throw new IOException ( "There was a Remote Exception." , e ) ; }


signature:
public class CommandLineParser { /** * Right pads a string with a given string to a given size . This method will repeat the padder string as many times
 * as is necessary until the exact specified size is reached . If the specified size is less than the size of the
 * original string then the original string is returned unchanged .
 * < pre >
 * Example1 - original string " cat " , padder string " white " , size 8 gives " catwhite " .
 * Example2 - original string " cat " , padder string " white " , size 15 gives " catwhitewhitewh " .
 * Example3 - original string " cat " , padder string " white " , size 2 gives " cat " .
 * < / pre >
 * @ param stringToPad The original string .
 * @ param padder The string to pad onto the original string .
 * @ param size The required size of the new string .
 * @ return The newly padded string . */
public static String rightPad ( String stringToPad , String padder , int size ) { } }

implementation: if ( padder . length ( ) == 0 ) { return stringToPad ; } StringBuffer strb = new StringBuffer ( stringToPad ) ; CharacterIterator sci = new StringCharacterIterator ( padder ) ; while ( strb . length ( ) < size ) { for ( char ch = sci . first ( ) ; ch != CharacterIterator . DONE ; ch = sci . next ( ) ) { if ( strb . length ( ) < size ) { strb . append ( String . valueOf ( ch ) ) ; } } } return strb . toString ( ) ;


signature:
public class CommandLineParser { /** * Lists all the parsing errors from the most recent parsing in a string .
 * @ return All the parsing errors from the most recent parsing . */
public String getErrors ( ) { } }

implementation:
// Return the empty string if there are no errors .
if ( parsingErrors . isEmpty ( ) ) { return "" ; } // Concatenate all the parsing errors together .
String result = "" ; for ( String s : parsingErrors ) { result += s ; } return result ;


signature:
public class CommandLineParser { /** * Lists the properties set from the most recent parsing or an empty string if no parsing has been done yet .
 * @ return The properties set from the most recent parsing or an empty string if no parsing has been done yet . */
public String getOptionsInForce ( ) { } }

implementation:
// Check if there are no properties to report and return and empty string if so .
if ( parsedProperties == null ) { return "" ; } // List all the properties .
String result = "Options in force:\n" ; for ( Map . Entry < Object , Object > property : parsedProperties . entrySet ( ) ) { result += property . getKey ( ) + " = " + property . getValue ( ) + "\n" ; } return result ;


signature:
public class CommandLineParser { /** * Generates a usage string consisting of the name of each option and each options argument description and comment .
 * @ return A usage string for all the options . */
public String getUsage ( ) { } }

implementation:
String result = "Options:\n" ; int optionWidth = 0 ; int argumentWidth = 0 ; // Calculate the column widths required for aligned layout .
for ( CommandLineOption optionInfo : optionMap . values ( ) ) { int oWidth = optionInfo . option . length ( ) ; int aWidth = ( optionInfo . argument != null ) ? ( optionInfo . argument . length ( ) ) : 0 ; optionWidth = ( oWidth > optionWidth ) ? oWidth : optionWidth ; argumentWidth = ( aWidth > argumentWidth ) ? aWidth : argumentWidth ; } // Print usage on each of the command line options .
for ( CommandLineOption optionInfo : optionMap . values ( ) ) { String argString = ( ( optionInfo . argument != null ) ? ( optionInfo . argument ) : "" ) ; String optionString = optionInfo . option ; argString = rightPad ( argString , " " , argumentWidth ) ; optionString = rightPad ( optionString , " " , optionWidth ) ; result += "-" + optionString + " " + argString + " " + optionInfo . comment + "\n" ; } return result ;


signature:
public class CommandLineParser { /** * Parses a set of command line arguments into a set of properties , keyed by the argument flag . The free arguments
 * are keyed by integers as strings starting at " 1 " and then " 2 " , . . . and so on .
 * < p / > See the class level comment for a description of the parsing rules .
 * @ param args The command line arguments .
 * @ return The arguments as a set of properties .
 * @ throws IllegalArgumentException If the command line cannot be parsed against its specification . If this
 * exception is thrown a call to { @ link # getErrors } will provide a diagnostic of
 * the command line errors . */
public Properties parseCommandLine ( String [ ] args ) throws IllegalArgumentException { } }

implementation:
Properties options = new Properties ( ) ; // Used to keep count of the current ' free ' argument .
int free = 1 ; // Used to indicate that the most recently parsed option is expecting arguments .
boolean expectingArgs = false ; // The option that is expecting arguments from the next element of the command line .
String optionExpectingArgs = null ; // Used to indicate that the most recently parsed option is a duplicate and should be ignored .
// boolean ignore = false ;
// Create the regular expression matcher for the command line options .
String regexp = "^(" ; int optionsAdded = 0 ; for ( Iterator < String > i = optionMap . keySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { String nextOption = i . next ( ) ; // Check that the option is not a free argument definition .
boolean notFree = false ; try { Integer . parseInt ( nextOption ) ; } catch ( NumberFormatException e ) { notFree = true ; } // Add the option to the regular expression matcher if it is not a free argument definition .
if ( notFree ) { regexp += nextOption + ( i . hasNext ( ) ? "|" : "" ) ; optionsAdded ++ ; } } // There has to be more that one option in the regular expression or else the compiler complains that the close
// cannot be nullable if the ' ? ' token is used to make the matched option string optional .
regexp += ")" + ( ( optionsAdded > 0 ) ? "?" : "" ) + "(.*)" ; Pattern pattern = Pattern . compile ( regexp ) ; // Loop through all the command line arguments .
for ( String arg1 : args ) { // Check if the next command line argument begins with a ' - ' character and is therefore the start of
// an option .
if ( arg1 . startsWith ( "-" ) ) { // Extract the value of the option without the leading ' - ' .
String arg = arg1 . substring ( 1 ) ; // Match up to the longest matching option .
optionMatcher = pattern . matcher ( arg ) ; optionMatcher . matches ( ) ; String matchedOption = optionMatcher . group ( 1 ) ; // Match any argument directly appended onto the longest matching option .
String matchedArg = optionMatcher . group ( 2 ) ; // Check that a known option was matched .
if ( ( matchedOption != null ) && ! "" . equals ( matchedOption ) ) { // Get the command line option information for the matched option .
CommandLineOption optionInfo = optionMap . get ( matchedOption ) ; // Check if this option is expecting arguments .
if ( optionInfo . expectsArgs ) { // The option is expecting arguments so swallow the next command line argument as an
// argument to this option .
expectingArgs = true ; optionExpectingArgs = matchedOption ; // In the mean time set this options argument to the empty string in case no argument is ever
// supplied .
// options . put ( matchedOption , " " ) ;
} // Check if the option was matched on its own and is a flag in which case set that flag .
if ( "" . equals ( matchedArg ) && ! optionInfo . expectsArgs ) { options . put ( matchedOption , "true" ) ; } // The option was matched as a substring with its argument appended to it or is a flag that is
// condensed together with other flags .
else if ( ! "" . equals ( matchedArg ) ) { // Check if the option is a flag and therefore is allowed to be condensed together
// with other flags .
if ( ! optionInfo . expectsArgs ) { // Set the first matched flag .
options . put ( matchedOption , "true" ) ; // Repeat the longest matching process on the remainder but ensure that the remainder
// consists only of flags as only flags may be condensed together in this fashion .
do { // Match the remainder against the options .
optionMatcher = pattern . matcher ( matchedArg ) ; optionMatcher . matches ( ) ; matchedOption = optionMatcher . group ( 1 ) ; matchedArg = optionMatcher . group ( 2 ) ; // Check that an option was matched .
if ( matchedOption != null ) { // Get the command line option information for the next matched option .
optionInfo = optionMap . get ( matchedOption ) ; // Ensure that the next option is a flag or raise an error if not .
if ( optionInfo . expectsArgs ) { parsingErrors . add ( "Option " + matchedOption + " cannot be combined with flags.\n" ) ; } options . put ( matchedOption , "true" ) ; } // The remainder could not be matched against a flag it is either an unknown flag
// or an illegal argument to a flag .
else { parsingErrors . add ( "Illegal argument to a flag in the option " + arg + "\n" ) ; break ; } } // Continue until the remainder of the argument has all been matched with flags .
while ( ! "" . equals ( matchedArg ) ) ; } // The option is expecting an argument , so store the unmatched portion against it
// as its argument .
else { // Check the arguments format is correct against any specified format .
checkArgumentFormat ( optionInfo , matchedArg ) ; // Store the argument against its option ( regardless of its format ) .
options . put ( matchedOption , matchedArg ) ; // The argument to this flag has already been supplied to it . Do not swallow the
// next command line argument as an argument to this flag .
expectingArgs = false ; } } } else // No matching option was found .
{ // Add this to the list of parsing errors if errors on unkowns is being used .
if ( errorsOnUnknowns ) { parsingErrors . add ( "Option " + matchedOption + " is not a recognized option.\n" ) ; } } } // The command line argument did not being with a ' - ' so it is an argument to the previous flag or it
// is a free argument .
else { // Check if a previous flag is expecting to swallow this next argument as its argument .
if ( expectingArgs ) { // Get the option info for the option waiting for arguments .
CommandLineOption optionInfo = optionMap . get ( optionExpectingArgs ) ; // Check the arguments format is correct against any specified format .
checkArgumentFormat ( optionInfo , arg1 ) ; // Store the argument against its option ( regardless of its format ) .
options . put ( optionExpectingArgs , arg1 ) ; // Clear the expecting args flag now that the argument has been swallowed .
expectingArgs = false ; optionExpectingArgs = null ; } // This command line option is not an argument to any option . Add it to the set of ' free ' options .
else { // Get the option info for the free option , if there is any .
CommandLineOption optionInfo = optionMap . get ( Integer . toString ( free ) ) ; if ( optionInfo != null ) { // Check the arguments format is correct against any specified format .
checkArgumentFormat ( optionInfo , arg1 ) ; } // Add to the list of free options .
options . put ( Integer . toString ( free ) , arg1 ) ; // Move on to the next free argument .
free ++ ; } } } // Scan through all the specified options to check that all mandatory options have been set and that all flags
// that were not set are set to false in the set of properties .
for ( CommandLineOption optionInfo : optionMap . values ( ) ) { // Check if this is a flag .
if ( ! optionInfo . expectsArgs ) { // Check if the flag is not set in the properties and set it to false if so .
if ( ! options . containsKey ( optionInfo . option ) ) { options . put ( optionInfo . option , "false" ) ; } } // Check if this is a mandatory option and was not set .
else if ( optionInfo . mandatory && ! options . containsKey ( optionInfo . option ) ) { // Create an error for the missing option .
parsingErrors . add ( "Option " + optionInfo . option + " is mandatory but not was not specified.\n" ) ; } } // Check if there were any errors .
if ( ! parsingErrors . isEmpty ( ) ) { // Throw an illegal argument exception to signify that there were parsing errors .
throw new IllegalArgumentException ( ) ; } // Convert any name / value pairs in the free arguments into properties in the parsed options .
trailingProperties = takeFreeArgsAsProperties ( options , 1 ) ; parsedProperties = options ; return options ;


signature:
public class CommandLineParser { /** * If a command line has been parsed , calling this method sets all of its free arguments that were name = value pairs
 * on the specified properties .
 * @ param properties The property set to add the name = value pairs to . */
public void addTrailingPairsToProperties ( Properties properties ) { } }

implementation: if ( trailingProperties != null ) { for ( Object propKey : trailingProperties . keySet ( ) ) { String name = ( String ) propKey ; String value = trailingProperties . getProperty ( name ) ; properties . setProperty ( name , value ) ; } }


signature:
public class CommandLineParser { /** * If a command line has been parsed , calling this method sets all of its options that were set to the specified
 * properties .
 * @ param properties The property set to the options to . */
public void addOptionsToProperties ( Properties properties ) { } }

implementation:
if ( parsedProperties != null ) { for ( Object propKey : parsedProperties . keySet ( ) ) { String name = ( String ) propKey ; String value = parsedProperties . getProperty ( name ) ; // This filters out all trailing items .
if ( ! name . matches ( "^[0-9]+$" ) ) { properties . setProperty ( name , value ) ; } } }


signature:
public class CommandLineParser { /** * Adds the option to list of available command line options .
 * @ param option The option to add as an available command line option .
 * @ param comment A comment for the option .
 * @ param argument The text that appears after the option in the usage string .
 * @ param mandatory When true , indicates that this option is mandatory .
 * @ param formatRegexp The format that the argument must take , defined as a regular expression . */
protected void addOption ( String option , String comment , String argument , boolean mandatory , String formatRegexp ) { } }

implementation:
// Check if usage text has been set in which case this option is expecting arguments .
boolean expectsArgs = ( ! ( ( argument == null ) || "" . equals ( argument ) ) ) ; // Add the option to the map of command line options .
CommandLineOption opt = new CommandLineOption ( option , expectsArgs , comment , argument , mandatory , formatRegexp ) ; optionMap . put ( option , opt ) ;


signature:
public class CommandLineParser { /** * Converts the free arguments into property declarations . After parsing the command line the free arguments are
 * numbered from 1 , such that the parsed properties contain values for the keys " 1 " , " 2 " , . . . This method converts
 * any free arguments declared using the ' name = value ' syntax into properties with key ' name ' , value ' value ' .
 * < p / > For example the comand line :
 * < pre >
 * . . . debug = true
 * < / pre >
 * < p / > After parsing has properties :
 * < pre > [ [ 1 , debug = true ] ] < / pre >
 * < p / > After applying this method the properties are :
 * < pre > [ [ 1 , debug = true ] , [ debug , true ] ] < / pre >
 * @ param properties The parsed command line properties .
 * @ param from The free argument index to convert to properties from .
 * @ return The parsed command line properties , with free argument name value pairs too . */
private Properties takeFreeArgsAsProperties ( Properties properties , int from ) { } }

implementation:
Properties result = new Properties ( ) ; for ( int i = from ; true ; i ++ ) { String nextFreeArg = properties . getProperty ( Integer . toString ( i ) ) ; // Terminate the loop once all free arguments have been consumed .
if ( nextFreeArg == null ) { break ; } // Split it on the = , strip any whitespace and set it as a system property .
String [ ] nameValuePair = nextFreeArg . split ( "=" ) ; if ( nameValuePair . length == 2 ) { result . setProperty ( nameValuePair [ 0 ] , nameValuePair [ 1 ] ) ; } } return result ;


signature:
public class CommandLineParser { /** * Checks the format of an argument to an option against its specified regular expression format if one has been
 * set . Any errors are added to the list of parsing errors .
 * @ param optionInfo The command line option information for the option which is havings its argument checked .
 * @ param matchedArg The string argument to the option . */
private void checkArgumentFormat ( CommandLineOption optionInfo , CharSequence matchedArg ) { } }

implementation:
// Check if this option enforces a format for its argument .
if ( optionInfo . argumentFormatRegexp != null ) { Pattern pattern = Pattern . compile ( optionInfo . argumentFormatRegexp ) ; Matcher argumentMatcher = pattern . matcher ( matchedArg ) ; // Check if the argument does not meet its required format .
if ( ! argumentMatcher . matches ( ) ) { // Create an error for this badly formed argument .
parsingErrors . add ( "The argument to option " + optionInfo . option + " does not meet its required format.\n" ) ; } }


signature:
public class Comparisons { /** * Walks down two iterators , comparing them element by element , using the equals method .
 * @ param iterator The first iterator to compare .
 * @ param expectedIterator The second iterator to compare .
 * @ param mapping A mapping between the types of the iterators .
 * @ param < U > The type of the left iterator .
 * @ param < T > The type of the right iterator .
 * @ return Any mismatches encountered in a string , or the empty string if none found . */
public static < T , U > String compareIterators ( Iterator < U > iterator , Iterator < T > expectedIterator , Function < U , T > mapping ) { } }

implementation: String errorMessage = "" ; while ( iterator . hasNext ( ) ) { U next = iterator . next ( ) ; T nextMapped = mapping . apply ( next ) ; T nextExpected = expectedIterator . next ( ) ; if ( ! nextMapped . equals ( nextExpected ) ) { errorMessage += "Expecting " + nextExpected + " but got " + nextMapped ; } } return errorMessage ;


signature:
public class PTStemmer { /** * Returns an enumeration describing the available options .
 * @ return an enumeration of all the available options . */
public Enumeration listOptions ( ) { } }

implementation: Vector < Option > result ; String desc ; SelectedTag tag ; int i ; result = new Vector < Option > ( ) ; desc = "" ; for ( i = 0 ; i < TAGS_STEMMERS . length ; i ++ ) { tag = new SelectedTag ( TAGS_STEMMERS [ i ] . getID ( ) , TAGS_STEMMERS ) ; desc += "\t" + tag . getSelectedTag ( ) . getIDStr ( ) + " = " + tag . getSelectedTag ( ) . getReadable ( ) + "\n" ; } result . addElement ( new Option ( "\tThe type of stemmer algorithm to use:\n" + desc + "\t(default: " + new SelectedTag ( STEMMER_ORENGO , TAGS_STEMMERS ) + ")" , "S" , 1 , "-S " + Tag . toOptionList ( TAGS_STEMMERS ) ) ) ; result . addElement ( new Option ( "\tThe file with the named entities to ignore (optional).\n" + "\tFile format: simple text file with one entity per line.\n" + "\t(default: none)\n" , "N" , 1 , "-N <file>" ) ) ; result . addElement ( new Option ( "\tThe file with the stopwords (optional).\n" + "\tFile format: simple text file with one stopword per line.\n" + "\t(default: none)\n" , "W" , 1 , "-W <file>" ) ) ; result . addElement ( new Option ( "\tThe size of the cache. Disable with 0.\n" + "\t(default: 1000)\n" , "C" , 1 , "-C <int>" ) ) ; return result . elements ( ) ;


signature:
public class PTStemmer { /** * Parses the options . < p / >
 * < ! - - options - start - - >
 * Valid options are : < p / >
 * < pre > - S & lt ; ORENGO | PORTER | SAVOY & gt ;
 * The type of stemmer algorithm to use :
 * ORENGO = Orengo
 * PORTER = Porter
 * SAVOY = Savoy
 * ( default : ORENGO ) < / pre >
 * < pre > - N & lt ; file & gt ;
 * The file with the named entities to ignore ( optional ) .
 * File format : simple text file with one entity per line .
 * ( default : none )
 * < / pre >
 * < pre > - W & lt ; file & gt ;
 * The file with the stopwords ( optional ) .
 * File format : simple text file with one stopword per line .
 * ( default : none )
 * < / pre >
 * < pre > - C & lt ; int & gt ;
 * The size of the cache . Disable with 0.
 * ( default : 1000)
 * < / pre >
 * < ! - - options - end - - >
 * @ param optionsthe options to parse
 * @ throws Exception if parsing fails */
public void setOptions ( String [ ] options ) throws Exception { } }

implementation: String tmpStr ; tmpStr = Utils . getOption ( 'S' , options ) ; if ( tmpStr . length ( ) != 0 ) setStemmer ( new SelectedTag ( tmpStr , TAGS_STEMMERS ) ) ; else setStemmer ( new SelectedTag ( STEMMER_ORENGO , TAGS_STEMMERS ) ) ; tmpStr = Utils . getOption ( 'N' , options ) ; if ( tmpStr . length ( ) != 0 ) setNamedEntities ( new File ( tmpStr ) ) ; else setNamedEntities ( new File ( "." ) ) ; tmpStr = Utils . getOption ( 'W' , options ) ; if ( tmpStr . length ( ) != 0 ) setStopwords ( new File ( tmpStr ) ) ; else setStopwords ( new File ( "." ) ) ; tmpStr = Utils . getOption ( 'C' , options ) ; if ( tmpStr . length ( ) != 0 ) setCache ( Integer . parseInt ( tmpStr ) ) ; else setCache ( 1000 ) ;


signature:
public class PTStemmer { /** * Gets the current settings of the classifier .
 * @ return an array of strings suitable for passing to setOptions */
public String [ ] getOptions ( ) { } }

implementation: Vector < String > result ; result = new Vector < String > ( ) ; result . add ( "-S" ) ; result . add ( "" + getStemmer ( ) ) ; result . add ( "-N" ) ; result . add ( "" + getNamedEntities ( ) ) ; result . add ( "-W" ) ; result . add ( "" + getStopwords ( ) ) ; result . add ( "-C" ) ; result . add ( "" + getCache ( ) ) ; return result . toArray ( new String [ result . size ( ) ] ) ;


signature:
public class PTStemmer { /** * Sets the stemmer type to use
 * @ param value the type */
public void setStemmer ( SelectedTag value ) { } }

implementation: if ( value . getTags ( ) == TAGS_STEMMERS ) { m_Stemmer = value . getSelectedTag ( ) . getID ( ) ; invalidate ( ) ; }


signature:
public class PTStemmer { /** * Returns the stemmer to use .
 * @ returnthe stemmer to use */
protected synchronized ptstemmer . Stemmer getActualStemmer ( ) throws PTStemmerException { } }

implementation:
if ( m_ActualStemmer == null ) { // stemmer algorithm
if ( m_Stemmer == STEMMER_ORENGO ) m_ActualStemmer = new OrengoStemmer ( ) ; else if ( m_Stemmer == STEMMER_PORTER ) m_ActualStemmer = new PorterStemmer ( ) ; else if ( m_Stemmer == STEMMER_SAVOY ) m_ActualStemmer = new SavoyStemmer ( ) ; else throw new IllegalStateException ( "Unhandled stemmer type: " + m_Stemmer ) ; // named entities
if ( ! m_NamedEntities . isDirectory ( ) ) m_ActualStemmer . ignore ( PTStemmerUtilities . fileToSet ( m_NamedEntities . getAbsolutePath ( ) ) ) ; // stopwords
if ( ! m_Stopwords . isDirectory ( ) ) m_ActualStemmer . ignore ( PTStemmerUtilities . fileToSet ( m_Stopwords . getAbsolutePath ( ) ) ) ; // cache
if ( m_Cache > 0 ) m_ActualStemmer . enableCaching ( m_Cache ) ; else m_ActualStemmer . disableCaching ( ) ; } return m_ActualStemmer ;


signature:
public class PTStemmer { /** * Returns the stemmed version of the given word .
 * Word is converted to lower case before stemming .
 * @ param word a string consisting of a single word
 * @ return the stemmed word */
public String stem ( String word ) { } }

implementation: String ret = null ; try { ret = getActualStemmer ( ) . getWordStem ( word ) ; } catch ( PTStemmerException e ) { e . printStackTrace ( ) ; } return ret ;


signature:
public class PTStemmer { /** * Runs the stemmer with the given options .
 * @ param args the options */
public static void main ( String [ ] args ) { } }

implementation: try { Stemming . useStemmer ( new PTStemmer ( ) , args ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; }


signature:
public class BuiltInUtils { /** * Evaluates a term by invoking its { @ link Term # getValue ( ) } method ( which may cause a recursive evaluation , for
 * example , in the case of arithmetic expressions ) , and checks that the result is a fully instantiated numeric
 * value .
 * @ param numeric The term to evaluate as a number .
 * @ return The term as a number . */
static NumericType evaluateAsNumeric ( Term numeric ) { } }

implementation:
// Evaluate the expression .
Term expressionValue = numeric . getValue ( ) ; // Ensure that the result of evaluating the expression is a number .
if ( expressionValue . isVar ( ) ) { throw new IllegalStateException ( "instantiation_error, 'is' expects a fully instantiated term to unify against." ) ; } if ( ! expressionValue . isNumber ( ) ) { throw new IllegalStateException ( "arithmetic_error, 'is' expectes a numeric expression to unify against." ) ; } return ( NumericType ) expressionValue ;


signature:
public class FloatRangeType { /** * Creates a new float range type with the specified name , if it does not already exist .
 * @ param name The name of the float range type to create .
 * @ param min The minimum value that an instance of the type can take .
 * @ param max The maximum value that an instance of teh type can take .
 * @ return A new float range type .
 * @ throws IllegalArgumentException If min is not less than or equal to max , or the named type already exists . */
public static Type createInstance ( String name , float min , float max ) { } }

implementation:
// Ensure that min is less than or equal to max .
if ( min > max ) { throw new IllegalArgumentException ( "'min' must be less than or equal to 'max'." ) ; } synchronized ( FLOAT_RANGE_TYPES ) { // Add the newly created type to the map of all types .
FloatRangeType newType = new FloatRangeType ( name , min , max ) ; // Ensure that the named type does not already exist , unless it has an identical definition already , in which
// case the old definition can be re - used and the new one discarded .
FloatRangeType oldType = FLOAT_RANGE_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( "The type '" + name + "' already exists and cannot be redefined." ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { FLOAT_RANGE_TYPES . put ( name , newType ) ; return newType ; } }


signature:
public class WorkPanelState { /** * Sets the state of the work panel . State must be one of the defined constants : NOT _ INITIALIZED , READY or
 * NOT _ SAVED .
 * < p / > Listneres are notified of the state change if it is a change .
 * @ param state The new state to set . */
public void setState ( String state ) { } }

implementation:
/* log . fine ( " void setState ( String ) : called " ) ; */
/* log . fine ( " state is " + state ) ; */
// Check if the state has changed
if ( ! this . state . equals ( state ) ) { String oldState = this . state ; // Keep the new state
this . state = state ; // Notify any listeners of the change in state
firePropertyChange ( new PropertyChangeEvent ( this , "state" , oldState , state ) ) ; }


signature:
public class WAMResolvingJavaMachine { /** * Resets the machine , to its initial state . This clears any programs from the machine , and clears all of its stacks
 * and heaps . */
public void reset ( ) { } }

implementation:
// Create fresh heaps , code areas and stacks .
data = ByteBuffer . allocateDirect ( TOP << 2 ) . order ( ByteOrder . LITTLE_ENDIAN ) . asIntBuffer ( ) ; codeBuffer = ByteBuffer . allocateDirect ( CODE_SIZE ) ; codeBuffer . order ( ByteOrder . LITTLE_ENDIAN ) ; // Registers are on the top of the data area , the heap comes next .
hp = HEAP_BASE ; hbp = HEAP_BASE ; sp = HEAP_BASE ; // The stack comes after the heap . Pointers are zero initially , since no stack frames exist yet .
ep = 0 ; bp = 0 ; b0 = 0 ; // The trail comes after the stack .
trp = TRAIL_BASE ; // The unification stack ( PDL ) is a push down stack at the end of the data area .
up = TOP ; // Turn off write mode .
writeMode = false ; // Reset the instruction pointer to that start of the code area , ready for fresh code to be loaded there .
ip = 0 ; // Could probably not bother resetting these , but will do it anyway just to be sure .
derefTag = 0 ; derefVal = 0 ; // The machine is initially not suspended .
suspended = false ; // Ensure that the overridden reset method of WAMBaseMachine is run too , to clear the call table .
super . reset ( ) ; // Put the internal functions in the call table .
setInternalCodeAddress ( internFunctorName ( "call" , 1 ) , CALL_1_ID ) ; setInternalCodeAddress ( internFunctorName ( "execute" , 1 ) , EXECUTE_1_ID ) ; // Notify any debug monitor that the machine has been reset .
if ( monitor != null ) { monitor . onReset ( this ) ; }


signature:
public class WAMResolvingJavaMachine { /** * { @ inheritDoc } */
public WAMInternalRegisters getInternalRegisters ( ) { } }

implementation: return new WAMInternalRegisters ( ip , hp , hbp , sp , up , ep , bp , b0 , trp , writeMode ) ;


signature:
public class WAMResolvingJavaMachine { /** * { @ inheritDoc } */
public WAMMemoryLayout getMemoryLayout ( ) { } }

implementation: return new WAMMemoryLayout ( 0 , REG_SIZE , HEAP_BASE , HEAP_SIZE , STACK_BASE , STACK_SIZE , TRAIL_BASE , TRAIL_SIZE , TOP - PDL_SIZE , PDL_SIZE ) ;


signature:
public class WAMResolvingJavaMachine { /** * { @ inheritDoc } */
protected boolean execute ( WAMCallPoint callPoint ) { } }

implementation:
/* log . fine ( " protected boolean execute ( WAMCallPoint callPoint ) : called " ) ; */
boolean failed ; // Check if the machine is being woken up from being suspended , in which case immediately fail in order to
// trigger back - tracking to find more solutions .
if ( suspended ) { failed = true ; suspended = false ; } else { ip = callPoint . entryPoint ; uClear ( ) ; failed = false ; } int numOfArgs = 0 ; // Holds the current continuation point .
cp = codeBuffer . position ( ) ; // Notify any debug monitor that execution is starting .
if ( monitor != null ) { monitor . onExecute ( this ) ; } // while ( ! failed & & ( ip < code . length ) )
while ( true ) { // Attempt to backtrack on failure .
if ( failed ) { failed = backtrack ( ) ; if ( failed ) { break ; } } // Grab next instruction and switch on it .
byte instruction = codeBuffer . get ( ip ) ; switch ( instruction ) { // put _ struc Xi , f / n :
case PUT_STRUC : { // grab addr , f / n
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; int fn = codeBuffer . getInt ( ip + 3 ) ; /* trace . fine ( ip + " : PUT _ STRUC " + printSlot ( xi , mode ) + " , " + fn ) ; */
// heap [ h ] < - STR , h + 1
data . put ( hp , fn ) ; // Xi < - heap [ h ]
data . put ( xi , structureAt ( hp ) ) ; // h < - h + 2
hp += 1 ; // P < - instruction _ size ( P )
ip += 7 ; break ; } // set _ var Xi :
case SET_VAR : { // grab addr
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /* trace . fine ( ip + " : SET _ VAR " + printSlot ( xi , mode ) ) ; */
// heap [ h ] < - REF , h
data . put ( hp , refTo ( hp ) ) ; // Xi < - heap [ h ]
data . put ( xi , data . get ( hp ) ) ; // h < - h + 1
hp ++ ; // P < - instruction _ size ( P )
ip += 3 ; break ; } // set _ val Xi :
case SET_VAL : { // grab addr
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /* trace . fine ( ip + " : SET _ VAL " + printSlot ( xi , mode ) ) ; */
// heap [ h ] < - Xi
data . put ( hp , data . get ( xi ) ) ; // h < - h + 1
hp ++ ; // P < - instruction _ size ( P )
ip += 3 ; break ; } // get _ struc Xi ,
case GET_STRUC : { // grab addr , f / n
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; int fn = codeBuffer . getInt ( ip + 3 ) ; /* trace . fine ( ip + " : GET _ STRUC " + printSlot ( xi , mode ) + " , " + fn ) ; */
// addr < - deref ( Xi ) ;
int addr = deref ( xi ) ; byte tag = derefTag ; int a = derefVal ; // switch STORE [ addr ]
switch ( tag ) { // case REF :
case REF : { // heap [ h ] < - STR , h + 1
data . put ( hp , structureAt ( hp + 1 ) ) ; // heap [ h + 1 ] < - f / n
data . put ( hp + 1 , fn ) ; // bind ( addr , h )
bind ( addr , hp ) ; // h < - h + 2
hp += 2 ; // mode < - write
writeMode = true ; /* trace . fine ( " - > write mode " ) ; */
break ; } // case STR , a :
case STR : { // if heap [ a ] = f / n
if ( data . get ( a ) == fn ) { // s < - a + 1
sp = a + 1 ; // mode < - read
writeMode = false ; /* trace . fine ( " - > read mode " ) ; */
} else { // fail
failed = true ; } break ; } default : { // fail
failed = true ; } } // P < - instruction _ size ( P )
ip += 7 ; break ; } // unify _ var Xi :
case UNIFY_VAR : { // grab addr
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /* trace . fine ( ip + " : UNIFY _ VAR " + printSlot ( xi , mode ) ) ; */
// switch mode
if ( ! writeMode ) { // case read :
// Xi < - heap [ s ]
data . put ( xi , data . get ( sp ) ) ; } else { // case write :
// heap [ h ] < - REF , h
data . put ( hp , refTo ( hp ) ) ; // Xi < - heap [ h ]
data . put ( xi , data . get ( hp ) ) ; // h < - h + 1
hp ++ ; } // s < - s + 1
sp ++ ; // P < - P + instruction _ size ( P )
ip += 3 ; break ; } // unify _ val Xi :
case UNIFY_VAL : { // grab addr
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /* trace . fine ( ip + " : UNIFY _ VAL " + printSlot ( xi , mode ) ) ; */
// switch mode
if ( ! writeMode ) { // case read :
// unify ( Xi , s )
failed = ! unify ( xi , sp ) ; } else { // case write :
// heap [ h ] < - Xi
data . put ( hp , data . get ( xi ) ) ; // h < - h + 1
hp ++ ; } // s < - s + 1
sp ++ ; // P < - P + instruction _ size ( P )
ip += 3 ; break ; } // put _ var Xn , Ai :
case PUT_VAR : { // grab addr , Ai
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; byte ai = codeBuffer . get ( ip + 3 ) ; /* trace . fine ( ip + " : PUT _ VAR " + printSlot ( xi , mode ) + " , A " + ai ) ; */
if ( mode == WAMInstruction . REG_ADDR ) { // heap [ h ] < - REF , H
data . put ( hp , refTo ( hp ) ) ; // Xn < - heap [ h ]
data . put ( xi , data . get ( hp ) ) ; // Ai < - heap [ h ]
data . put ( ai , data . get ( hp ) ) ; } else { // STACK [ addr ] < - REF , addr
data . put ( xi , refTo ( xi ) ) ; // Ai < - STACK [ addr ]
data . put ( ai , data . get ( xi ) ) ; } // h < - h + 1
hp ++ ; // P < - P + instruction _ size ( P )
ip += 4 ; break ; } // put _ val Xn , Ai :
case PUT_VAL : { // grab addr , Ai
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; byte ai = codeBuffer . get ( ip + 3 ) ; /* trace . fine ( ip + " : PUT _ VAL " + printSlot ( xi , mode ) + " , A " + ai ) ; */
// Ai < - Xn
data . put ( ai , data . get ( xi ) ) ; // P < - P + instruction _ size ( P )
ip += 4 ; break ; } // get var Xn , Ai :
case GET_VAR : { // grab addr , Ai
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; byte ai = codeBuffer . get ( ip + 3 ) ; /* trace . fine ( ip + " : GET _ VAR " + printSlot ( xi , mode ) + " , A " + ai ) ; */
// Xn < - Ai
data . put ( xi , data . get ( ai ) ) ; // P < - P + instruction _ size ( P )
ip += 4 ; break ; } // get _ val Xn , Ai :
case GET_VAL : { // grab addr , Ai
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; byte ai = codeBuffer . get ( ip + 3 ) ; /* trace . fine ( ip + " : GET _ VAL " + printSlot ( xi , mode ) + " , A " + ai ) ; */
// unify ( Xn , Ai )
failed = ! unify ( xi , ai ) ; // P < - P + instruction _ size ( P )
ip += 4 ; break ; } case PUT_CONST : { // grab addr , f / n
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; int fn = codeBuffer . getInt ( ip + 3 ) ; /* trace . fine ( ip + " : PUT _ CONST " + printSlot ( xi , mode ) + " , " + fn ) ; */
// Xi < - heap [ h ]
data . put ( xi , constantCell ( fn ) ) ; // P < - instruction _ size ( P )
ip += 7 ; break ; } case GET_CONST : { // grab addr , Ai
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; int fn = codeBuffer . getInt ( ip + 3 ) ; /* trace . fine ( ip + " : GET _ CONST " + printSlot ( xi , mode ) + " , " + fn ) ; */
// addr < - deref ( Xi )
int addr = deref ( xi ) ; int tag = derefTag ; int val = derefVal ; failed = ! unifyConst ( fn , xi ) ; // P < - P + instruction _ size ( P )
ip += 7 ; break ; } case SET_CONST : { int fn = codeBuffer . getInt ( ip + 1 ) ; /* trace . fine ( ip + " : SET _ CONST " + fn ) ; */
// heap [ h ] < - < CON , c >
data . put ( hp , constantCell ( fn ) ) ; // h < - h + 1
hp ++ ; // P < - instruction _ size ( P )
ip += 5 ; break ; } case UNIFY_CONST : { int fn = codeBuffer . getInt ( ip + 1 ) ; /* trace . fine ( ip + " : UNIFY _ CONST " + fn ) ; */
// switch mode
if ( ! writeMode ) { // case read :
// addr < - deref ( S )
// unifyConst ( fn , addr )
failed = ! unifyConst ( fn , sp ) ; } else { // case write :
// heap [ h ] < - < CON , c >
data . put ( hp , constantCell ( fn ) ) ; // h < - h + 1
hp ++ ; } // s < - s + 1
sp ++ ; // P < - P + instruction _ size ( P )
ip += 5 ; break ; } case PUT_LIST : { // grab addr
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /* trace . fine ( ip + " : PUT _ LIST " + printSlot ( xi , mode ) ) ; */
// Xi < - < LIS , H >
data . put ( xi , listCell ( hp ) ) ; // P < - P + instruction _ size ( P )
ip += 3 ; break ; } case GET_LIST : { // grab addr
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /* trace . fine ( ip + " : GET _ LIST " + printSlot ( xi , mode ) ) ; */
int addr = deref ( xi ) ; int tag = derefTag ; int val = derefVal ; // case STORE [ addr ] of
switch ( tag ) { case REF : { // < REF , _ > :
// HEAP [ H ] < - < LIS , H + 1 >
data . put ( hp , listCell ( hp + 1 ) ) ; // bind ( addr , H )
bind ( addr , hp ) ; // H < - H + 1
hp += 1 ; // mode < - write
writeMode = true ; /* trace . fine ( " - > write mode " ) ; */
break ; } case LIS : { // < LIS , a > :
// S < - a
sp = val ; // mode < - read
writeMode = false ; /* trace . fine ( " - > read mode " ) ; */
break ; } default : { // other : fail < - true ;
failed = true ; } } // P < - P + instruction _ size ( P )
ip += 3 ; break ; } case SET_VOID : { // grab N
int n = ( int ) codeBuffer . get ( ip + 1 ) ; /* trace . fine ( ip + " : SET _ VOID " + n ) ; */
// for i < - H to H + n - 1 do
// HEAP [ i ] < - < REF , i >
for ( int addr = hp ; addr < ( hp + n ) ; addr ++ ) { data . put ( addr , refTo ( addr ) ) ; } // H < - H + n
hp += n ; // P < - P + instruction _ size ( P )
ip += 2 ; break ; } case UNIFY_VOID : { // grab N
int n = ( int ) codeBuffer . get ( ip + 1 ) ; /* trace . fine ( ip + " : UNIFY _ VOID " + n ) ; */
// case mode of
if ( ! writeMode ) { // read : S < - S + n
sp += n ; } else { // write :
// for i < - H to H + n - 1 do
// HEAP [ i ] < - < REF , i >
for ( int addr = hp ; addr < ( hp + n ) ; addr ++ ) { data . put ( addr , refTo ( addr ) ) ; } // H < - H + n
hp += n ; } // P < - P + instruction _ size ( P )
ip += 2 ; break ; } // put _ unsafe _ val Yn , Ai :
case PUT_UNSAFE_VAL : { // grab addr , Ai
byte mode = codeBuffer . get ( ip + 1 ) ; int yi = ( int ) codeBuffer . get ( ip + 2 ) + ( ep + 3 ) ; byte ai = codeBuffer . get ( ip + 3 ) ; /* trace . fine ( ip + " : PUT _ UNSAFE _ VAL " + printSlot ( yi , WAMInstruction . STACK _ ADDR ) + " , A " + ai ) ; */
int addr = deref ( yi ) ; if ( addr < ep ) { // Ai < - Xn
data . put ( ai , data . get ( addr ) ) ; } else { data . put ( hp , refTo ( hp ) ) ; bind ( addr , hp ) ; data . put ( ai , data . get ( hp ) ) ; hp ++ ; } // P < - P + instruction _ size ( P )
ip += 4 ; break ; } // set _ local _ val Xi :
case SET_LOCAL_VAL : { // grab addr
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /* trace . fine ( ip + " : SET _ LOCAL _ VAL " + printSlot ( xi , mode ) ) ; */
int addr = deref ( xi ) ; if ( addr < ep ) { data . put ( hp , data . get ( addr ) ) ; } else { data . put ( hp , refTo ( hp ) ) ; bind ( addr , hp ) ; } // h < - h + 1
hp ++ ; // P < - P + instruction _ size ( P )
ip += 3 ; break ; } // unify _ local _ val Xi :
case UNIFY_LOCAL_VAL : { // grab addr
byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /* trace . fine ( ip + " : UNIFY _ LOCAL _ VAL " + printSlot ( xi , mode ) ) ; */
// switch mode
if ( ! writeMode ) { // case read :
// unify ( Xi , s )
failed = ! unify ( xi , sp ) ; } else { // case write :
int addr = deref ( xi ) ; if ( addr < ep ) { data . put ( hp , data . get ( addr ) ) ; } else { data . put ( hp , refTo ( hp ) ) ; bind ( addr , hp ) ; } // h < - h + 1
hp ++ ; } // s < - s + 1
sp ++ ; // P < - P + instruction _ size ( P )
ip += 3 ; break ; } // call @ ( p / n ) , perms :
case CALL : { // grab @ ( p / n ) , perms
int pn = codeBuffer . getInt ( ip + 1 ) ; int n = codeBuffer . get ( ip + 5 ) ; int numPerms = ( int ) codeBuffer . get ( ip + 6 ) ; // num _ of _ args < - n
numOfArgs = n ; // Ensure that the predicate to call is known and linked in , otherwise fail .
if ( pn == - 1 ) { failed = true ; break ; } // STACK [ E + 2 ] < - numPerms
data . put ( ep + 2 , numPerms ) ; // CP < - P + instruction _ size ( P )
cp = ip + 7 ; /* trace . fine ( ip + " : CALL " + pn + " / " + n + " , " + numPerms + " ( cp = " + cp + " ) ] " ) ; */
// B0 < - B
b0 = bp ; // P < - @ ( p / n )
ip = pn ; break ; } // execute @ ( p / n ) :
case EXECUTE : { // grab @ ( p / n )
int pn = codeBuffer . getInt ( ip + 1 ) ; int n = codeBuffer . get ( ip + 5 ) ; // num _ of _ args < - n
numOfArgs = n ; /* trace . fine ( ip + " : EXECUTE " + pn + " / " + n + " ( cp = " + cp + " ) ] " ) ; */
// Ensure that the predicate to call is known and linked in , otherwise fail .
if ( pn == - 1 ) { failed = true ; break ; } // B0 < - B
b0 = bp ; // P < - @ ( p / n )
ip = pn ; break ; } // proceed :
case PROCEED : { /* trace . fine ( ip + " : PROCEED " + " ( cp = " + cp + " ) ] " ) ; */
// P < - CP
ip = cp ; break ; } // allocate :
case ALLOCATE : { // if E > B
// then newB < - E + STACK [ E + 2 ] + 3
// else newB < - B + STACK [ B ] + 7
int esp = nextStackFrame ( ) ; // STACK [ newE ] < - E
data . put ( esp , ep ) ; // STACK [ E + 1 ] < - CP
data . put ( esp + 1 , cp ) ; // STACK [ E + 2 ] < - N
data . put ( esp + 2 , 0 ) ; // E < - newE
// newE < - E + n + 3
ep = esp ; /* trace . fine ( ip + " : ALLOCATE " ) ; */
/* trace . fine ( " - > env @ " + ep + " " + traceEnvFrame ( ) ) ; */
// P < - P + instruction _ size ( P )
ip += 1 ; break ; } // allocate N :
case ALLOCATE_N : { // grab N
int n = ( int ) codeBuffer . get ( ip + 1 ) ; // if E > B
// then newB < - E + STACK [ E + 2 ] + 3
// else newB < - B + STACK [ B ] + 7
int esp = nextStackFrame ( ) ; // STACK [ newE ] < - E
data . put ( esp , ep ) ; // STACK [ E + 1 ] < - CP
data . put ( esp + 1 , cp ) ; // STACK [ E + 2 ] < - N
data . put ( esp + 2 , n ) ; // E < - newE
// newE < - E + n + 3
ep = esp ; /* trace . fine ( ip + " : ALLOCATE _ N " + n ) ; */
/* trace . fine ( " - > env @ " + ep + " " + traceEnvFrame ( ) ) ; */
// P < - P + instruction _ size ( P )
ip += 2 ; break ; } // deallocate :
case DEALLOCATE : { int newip = data . get ( ep + 1 ) ; // E < - STACK [ E ]
ep = data . get ( ep ) ; /* trace . fine ( ip + " : DEALLOCATE " ) ; */
/* trace . fine ( " < - env @ " + ep + " " + traceEnvFrame ( ) ) ; */
// CP < - STACK [ E + 1]
cp = newip ; // P < - P + instruction _ size ( P )
ip += 1 ; break ; } // try me else L :
case TRY_ME_ELSE : { // grab L
int l = codeBuffer . getInt ( ip + 1 ) ; // if E > B
// then newB < - E + STACK [ E + 2 ] + 3
// else newB < - B + STACK [ B ] + 7
int esp = nextStackFrame ( ) ; // STACK [ newB ] < - num _ of _ args
// n < - STACK [ newB ]
int n = numOfArgs ; data . put ( esp , n ) ; // for i < - 1 to n do STACK [ newB + i ] < - Ai
for ( int i = 0 ; i < n ; i ++ ) { data . put ( esp + i + 1 , data . get ( i ) ) ; } // STACK [ newB + n + 1 ] < - E
data . put ( esp + n + 1 , ep ) ; // STACK [ newB + n + 2 ] < - CP
data . put ( esp + n + 2 , cp ) ; // STACK [ newB + n + 3 ] < - B
data . put ( esp + n + 3 , bp ) ; // STACK [ newB + n + 4 ] < - L
data . put ( esp + n + 4 , l ) ; // STACK [ newB + n + 5 ] < - TR
data . put ( esp + n + 5 , trp ) ; // STACK [ newB + n + 6 ] < - H
data . put ( esp + n + 6 , hp ) ; // STACK [ newB + n + 7 ] < - B0
data . put ( esp + n + 7 , b0 ) ; // B < - new B
bp = esp ; // HB < - H
hbp = hp ; /* trace . fine ( ip + " : TRY _ ME _ ELSE " ) ; */
/* trace . fine ( " - > chp @ " + bp + " " + traceChoiceFrame ( ) ) ; */
// P < - P + instruction _ size ( P )
ip += 5 ; break ; } // retry me else L :
case RETRY_ME_ELSE : { // grab L
int l = codeBuffer . getInt ( ip + 1 ) ; // n < - STACK [ B ]
int n = data . get ( bp ) ; // for i < - 1 to n do Ai < - STACK [ B + i ]
for ( int i = 0 ; i < n ; i ++ ) { data . put ( i , data . get ( bp + i + 1 ) ) ; } // E < - STACK [ B + n + 1]
ep = data . get ( bp + n + 1 ) ; // CP < - STACK [ B + n + 2]
cp = data . get ( bp + n + 2 ) ; // STACK [ B + n + 4 ] < - L
data . put ( bp + n + 4 , l ) ; // unwind _ trail ( STACK [ B + n + 5 ] , TR )
unwindTrail ( data . get ( bp + n + 5 ) , trp ) ; // TR < - STACK [ B + n + 5]
trp = data . get ( bp + n + 5 ) ; // H < - STACK [ B + n + 6]
hp = data . get ( bp + n + 6 ) ; // HB < - H
hbp = hp ; /* trace . fine ( ip + " : RETRY _ ME _ ELSE " ) ; */
/* trace . fine ( " - - chp @ " + bp + " " + traceChoiceFrame ( ) ) ; */
// P < - P + instruction _ size ( P )
ip += 5 ; break ; } // trust me ( else fail ) :
case TRUST_ME : { // n < - STACK [ B ]
int n = data . get ( bp ) ; // for i < - 1 to n do Ai < - STACK [ B + i ]
for ( int i = 0 ; i < n ; i ++ ) { data . put ( i , data . get ( bp + i + 1 ) ) ; } // E < - STACK [ B + n + 1]
ep = data . get ( bp + n + 1 ) ; // CP < - STACK [ B + n + 2]
cp = data . get ( bp + n + 2 ) ; // unwind _ trail ( STACK [ B + n + 5 ] , TR )
unwindTrail ( data . get ( bp + n + 5 ) , trp ) ; // TR < - STACK [ B + n + 5]
trp = data . get ( bp + n + 5 ) ; // H < - STACK [ B + n + 6]
hp = data . get ( bp + n + 6 ) ; // HB < - STACK [ B + n + 6]
hbp = hp ; // B < - STACK [ B + n + 3]
bp = data . get ( bp + n + 3 ) ; /* trace . fine ( ip + " : TRUST _ ME " ) ; */
/* trace . fine ( " < - chp @ " + bp + " " + traceChoiceFrame ( ) ) ; */
// P < - P + instruction _ size ( P )
ip += 1 ; break ; } case SWITCH_ON_TERM : { // grab labels
int v = codeBuffer . getInt ( ip + 1 ) ; int c = codeBuffer . getInt ( ip + 5 ) ; int l = codeBuffer . getInt ( ip + 9 ) ; int s = codeBuffer . getInt ( ip + 13 ) ; int addr = deref ( 1 ) ; int tag = derefTag ; // case STORE [ deref ( A1 ) ] of
switch ( tag ) { case REF : // < REF , _ > : P < - V
ip = v ; break ; case CON : // < CON , _ > : P < - C
ip = c ; break ; case LIS : // < LIS , _ > : P < - L
ip = l ; break ; case STR : // < STR , _ > : P < - S
ip = s ; break ; } break ; } case SWITCH_ON_CONST : { // grab labels
int t = codeBuffer . getInt ( ip + 1 ) ; int n = codeBuffer . getInt ( ip + 5 ) ; // < tag , val > < - STORE [ deref ( A1 ) ]
deref ( 1 ) ; int val = derefVal ; // < found , inst > < - get _ hash ( val , T , N )
int inst = getHash ( val , t , n ) ; // if found
if ( inst > 0 ) { // then P < - inst
ip = inst ; } else { // else backtrack
failed = true ; } break ; } case SWITCH_ON_STRUC : { // grab labels
int t = codeBuffer . getInt ( ip + 1 ) ; int n = codeBuffer . getInt ( ip + 5 ) ; // < tag , val > < - STORE [ deref ( A1 ) ]
deref ( 1 ) ; int val = derefVal ; // < found , inst > < - get _ hash ( val , T , N )
int inst = getHash ( val , t , n ) ; // if found
if ( inst > 0 ) { // then P < - inst
ip = inst ; } else { // else backtrack
failed = true ; } break ; } case TRY : { // grab L
int l = codeBuffer . getInt ( ip + 1 ) ; // if E > B
// then newB < - E + STACK [ E + 2 ] + 3
// else newB < - B + STACK [ B ] + 7
int esp = nextStackFrame ( ) ; // STACK [ newB ] < - num _ of _ args
// n < - STACK [ newB ]
int n = numOfArgs ; data . put ( esp , n ) ; // for i < - 1 to n do STACK [ newB + i ] < - Ai
for ( int i = 0 ; i < n ; i ++ ) { data . put ( esp + i + 1 , data . get ( i ) ) ; } // STACK [ newB + n + 1 ] < - E
data . put ( esp + n + 1 , ep ) ; // STACK [ newB + n + 2 ] < - CP
data . put ( esp + n + 2 , cp ) ; // STACK [ newB + n + 3 ] < - B
data . put ( esp + n + 3 , bp ) ; // STACK [ newB + n + 4 ] < - L
data . put ( esp + n + 4 , ip + 5 ) ; // STACK [ newB + n + 5 ] < - TR
data . put ( esp + n + 5 , trp ) ; // STACK [ newB + n + 6 ] < - H
data . put ( esp + n + 6 , hp ) ; // STACK [ newB + n + 7 ] < - B0
data . put ( esp + n + 7 , b0 ) ; // B < - new B
bp = esp ; // HB < - H
hbp = hp ; /* trace . fine ( ip + " : TRY " ) ; */
/* trace . fine ( " - > chp @ " + bp + " " + traceChoiceFrame ( ) ) ; */
// P < - L
ip = l ; break ; } case RETRY : { // grab L
int l = codeBuffer . getInt ( ip + 1 ) ; // n < - STACK [ B ]
int n = data . get ( bp ) ; // for i < - 1 to n do Ai < - STACK [ B + i ]
for ( int i = 0 ; i < n ; i ++ ) { data . put ( i , data . get ( bp + i + 1 ) ) ; } // E < - STACK [ B + n + 1]
ep = data . get ( bp + n + 1 ) ; // CP < - STACK [ B + n + 2]
cp = data . get ( bp + n + 2 ) ; // STACK [ B + n + 4 ] < - L
data . put ( bp + n + 4 , ip + 5 ) ; // unwind _ trail ( STACK [ B + n + 5 ] , TR )
unwindTrail ( data . get ( bp + n + 5 ) , trp ) ; // TR < - STACK [ B + n + 5]
trp = data . get ( bp + n + 5 ) ; // H < - STACK [ B + n + 6]
hp = data . get ( bp + n + 6 ) ; // HB < - H
hbp = hp ; /* trace . fine ( ip + " : RETRY " ) ; */
/* trace . fine ( " - - chp @ " + bp + " " + traceChoiceFrame ( ) ) ; */
// P < - L
ip = l ; break ; } case TRUST : { // grab L
int l = codeBuffer . getInt ( ip + 1 ) ; // n < - STACK [ B ]
int n = data . get ( bp ) ; // for i < - 1 to n do Ai < - STACK [ B + i ]
for ( int i = 0 ; i < n ; i ++ ) { data . put ( i , data . get ( bp + i + 1 ) ) ; } // E < - STACK [ B + n + 1]
ep = data . get ( bp + n + 1 ) ; // CP < - STACK [ B + n + 2]
cp = data . get ( bp + n + 2 ) ; // unwind _ trail ( STACK [ B + n + 5 ] , TR )
unwindTrail ( data . get ( bp + n + 5 ) , trp ) ; // TR < - STACK [ B + n + 5]
trp = data . get ( bp + n + 5 ) ; // H < - STACK [ B + n + 6]
hp = data . get ( bp + n + 6 ) ; // HB < - STACK [ B + n + 6]
hbp = hp ; // B < - STACK [ B + n + 3]
bp = data . get ( bp + n + 3 ) ; /* trace . fine ( ip + " : TRUST " ) ; */
/* trace . fine ( " < - chp @ " + bp + " " + traceChoiceFrame ( ) ) ; */
// P < - L
ip = l ; break ; } case NECK_CUT : { if ( bp > b0 ) { bp = b0 ; tidyTrail ( ) ; } /* trace . fine ( ip + " : NECK _ CUT " ) ; */
/* trace . fine ( " < - chp @ " + bp + " " + traceChoiceFrame ( ) ) ; */
ip += 1 ; break ; } case GET_LEVEL : { int yn = ( int ) codeBuffer . get ( ip + 1 ) + ( ep + 3 ) ; data . put ( yn , b0 ) ; /* trace . fine ( ip + " : GET _ LEVEL " + codeBuffer . get ( ip + 1 ) ) ; */
ip += 2 ; break ; } case CUT : { int yn = ( int ) codeBuffer . get ( ip + 1 ) + ( ep + 3 ) ; int cbp = data . get ( yn ) ; if ( bp > cbp ) { bp = cbp ; tidyTrail ( ) ; } /* trace . fine ( ip + " : CUT " + codeBuffer . get ( ip + 1 ) ) ; */
/* trace . fine ( " < - chp @ " + bp + " " + traceChoiceFrame ( ) ) ; */
ip += 2 ; break ; } case CONTINUE : { // grab L
int l = codeBuffer . getInt ( ip + 1 ) ; /* trace . fine ( ip + " : CONTINUE " + l ) ; */
ip = l ; break ; } case NO_OP : { /* trace . fine ( ip + " : NO _ OP " ) ; */
ip += 1 ; break ; } // call _ internal @ ( p / n ) , perms :
case CALL_INTERNAL : { // grab @ ( p / n ) , perms
int pn = codeBuffer . getInt ( ip + 1 ) ; int n = codeBuffer . get ( ip + 5 ) ; int numPerms = ( int ) codeBuffer . get ( ip + 6 ) ; // num _ of _ args < - n
numOfArgs = n ; /* trace . fine ( ip + " : CALL _ INTERNAL " + pn + " / " + n + " , " + numPerms + " ( cp = " + cp + " ) ] " ) ; */
boolean callOk = callInternal ( pn , n , numPerms ) ; failed = ! callOk ; break ; } // suspend on success :
case SUSPEND : { /* trace . fine ( ip + " : SUSPEND " ) ; */
ip += 1 ; suspended = true ; return true ; } } // Notify any debug monitor that the machine has been stepped .
if ( monitor != null ) { monitor . onStep ( this ) ; } } return ! failed ;


signature:
public class WAMResolvingJavaMachine { /** * Pretty prints the current environment frame , for debugging purposes .
 * @ return The current environment frame , pretty printed . */
protected String traceEnvFrame ( ) { } }

implementation: return "env: [ ep = " + data . get ( ep ) + ", cp = " + data . get ( ep + 1 ) + ", n = " + data . get ( ep + 2 ) + "]" ;


signature:
public class WAMResolvingJavaMachine { /** * Pretty prints the current choice point frame , for debugging purposes .
 * @ return The current choice point frame , pretty printed . */
protected String traceChoiceFrame ( ) { } }

implementation: if ( bp == 0 ) { return "" ; } int n = data . get ( bp ) ; return "choice: [ n = " + data . get ( bp ) + ", ep = " + data . get ( bp + n + 1 ) + ", cp = " + data . get ( bp + n + 2 ) + ", bp = " + data . get ( bp + n + 3 ) + ", l = " + data . get ( bp + n + 4 ) + ", trp = " + data . get ( bp + n + 5 ) + ", hp = " + data . get ( bp + n + 6 ) + ", b0 = " + data . get ( bp + n + 7 ) ;


signature:
public class WAMResolvingJavaMachine { /** * { @ inheritDoc } */
protected int deref ( int a ) { } }

implementation:
// tag , value < - STORE [ a ]
int addr = a ; int tmp = data . get ( a ) ; derefTag = ( byte ) ( tmp >>> TSHIFT ) ; derefVal = tmp & AMASK ; // while tag = REF and value ! = a
while ( ( derefTag == WAMInstruction . REF ) ) { // tag , value < - STORE [ a ]
addr = derefVal ; tmp = data . get ( derefVal ) ; derefTag = ( byte ) ( tmp >>> TSHIFT ) ; tmp = tmp & AMASK ; // Break on free var .
if ( derefVal == tmp ) { break ; } derefVal = tmp ; } return addr ;


signature:
public class WAMResolvingJavaMachine { /** * Invokes an internal function .
 * @ param function The id of the internal function to call .
 * @ param arity The arity of the function to call .
 * @ param numPerms The number of permanent variables remaining in the environment .
 * @ return < tt > true < / tt > if the call succeeded , and < tt > false < / tt > if it failed . */
private boolean callInternal ( int function , int arity , int numPerms ) { } }

implementation: switch ( function ) { case CALL_1_ID : return internalCall_1 ( numPerms ) ; case EXECUTE_1_ID : return internalExecute_1 ( ) ; default : throw new IllegalStateException ( "Unknown internal function id: " + function ) ; }


signature:
public class WAMResolvingJavaMachine { /** * Implements the ' call / 1 ' predicate .
 * @ param numPerms The number of permanent variables remaining in the environment .
 * @ return < tt > true < / tt > if the call succeeded , and < tt > false < / tt > if it failed . */
private boolean internalCall_1 ( int numPerms ) { } }

implementation:
int pn = setupCall_1 ( ) ; if ( pn == - 1 ) { return false ; } // Make the call .
// STACK [ E + 2 ] < - numPerms
data . put ( ep + 2 , numPerms ) ; // CP < - P + instruction _ size ( P )
cp = ip + 7 ; /* trace . fine ( ip + " : ( CALL ) " + pn + " , " + numPerms + " ( cp = " + cp + " ) ] " ) ; */
// B0 < - B
b0 = bp ; // P < - @ ( p / n )
ip = pn ; return true ;


signature:
public class WAMResolvingJavaMachine { /** * Implements the execute variant of the ' call / 1 ' predicate .
 * @ return < tt > true < / tt > if the call succeeded , and < tt > false < / tt > if it failed . */
private boolean internalExecute_1 ( ) { } }

implementation:
int pn = setupCall_1 ( ) ; if ( pn == - 1 ) { return false ; } // Make the call .
/* trace . fine ( ip + " : ( EXECUTE ) " + pn + " ( cp = " + cp + " ) ] " ) ; */
// B0 < - B
b0 = bp ; // P < - @ ( p / n )
ip = pn ; return true ;


signature:
public class WAMResolvingJavaMachine { /** * Sets up the registers to make a call , for implementing call / 1 . The first register should reference a structure to
 * be turned into a predicate call . The arguments of this structure will be set up in the registers , and the entry
 * point of the predicate to call will be returned .
 * @ return The entry address of the predicate to call , or < tt > - 1 < / tt > if the call cannot be resolved to a known
 * predicate . */
private int setupCall_1 ( ) { } }

implementation:
// Get X0.
int addr = deref ( 0 ) ; byte tag = derefTag ; int val = derefVal ; // Check it points to a structure .
int fn ; if ( tag == STR ) { fn = getHeap ( val ) ; } else if ( tag == CON ) { fn = val ; } else { /* trace . fine ( " call / 1 not invoked against structure . " ) ; */
return - 1 ; } // Look up the call point of the matching functor .
int f = fn & 0x00ffffff ; WAMCallPoint callPoint = resolveCallPoint ( f ) ; if ( callPoint . entryPoint == - 1 ) { /* trace . fine ( " call / 1 to unknown call point . " ) ; */
return - 1 ; } int pn = callPoint . entryPoint ; // Set registers X0 . . . to ref to args . . .
FunctorName functorName = getDeinternedFunctorName ( f ) ; int arity = functorName . getArity ( ) ; for ( int i = 0 ; i < arity ; i ++ ) { data . put ( i , refTo ( val + 1 + i ) ) ; } return pn ;


signature:
public class WAMResolvingJavaMachine { /** * Computes the start of the next stack frame . This depends on whether the most recent stack frame is an environment
 * frame or a choice point frame , as these have different sizes . The size of the most recent type of frame is
 * computed and added to the current frame pointer to give the start of the next frame .
 * @ return The start of the next stack frame . */
private int nextStackFrame ( ) { } }

implementation:
// if E > B
// then newB < - E + STACK [ E + 2 ] + 3
// else newB < - B + STACK [ B ] + 7
if ( ep == bp ) { return STACK_BASE ; } else if ( ep > bp ) { return ep + data . get ( ep + 2 ) + 3 ; } else { return bp + data . get ( bp ) + 8 ; }


signature:
public class WAMResolvingJavaMachine { /** * Backtracks to the continuation label stored in the current choice point frame , if there is one . Otherwise returns
 * a fail to indicate that there are no more choice points , so no backtracking can be done .
 * @ return < tt > true < / tt > iff this is the final failure , and there are no more choice points . */
private boolean backtrack ( ) { } }

implementation:
// if B = bottom _ of _ stack
if ( bp == 0 ) { // then fail _ and _ exit _ program
return true ; } else { // B0 < - STACK [ B + STACK [ B } + 7]
b0 = data . get ( bp + data . get ( bp ) + 7 ) ; // P < - STACK [ B + STACK [ B ] + 4]
ip = data . get ( bp + data . get ( bp ) + 4 ) ; return false ; }


signature:
public class WAMResolvingJavaMachine { /** * Creates a binding of one variable onto another . One of the supplied addresses must be an unbound variable . If
 * both are unbound variables , the higher ( newer ) address is bound to the lower ( older ) one .
 * @ param a1 The address of the first potential unbound variable to bind .
 * @ param a2 The address of the second potential unbound variable to bind . */
private void bind ( int a1 , int a2 ) { } }

implementation:
// < t1 , _ > < - STORE [ a1]
int t1 = ( byte ) ( data . get ( a1 ) >>> TSHIFT ) ; // < t2 , _ > < - STORE [ a2]
int t2 = ( byte ) ( data . get ( a2 ) >>> TSHIFT ) ; // if ( t1 = REF ) / \ ( ( t2 ! = REF ) \ / ( a2 < a1 ) )
if ( ( t1 == WAMInstruction . REF ) && ( ( t2 != WAMInstruction . REF ) || ( a2 < a1 ) ) ) { // STORE [ a1 ] < - STORE [ a2]
// data . put ( a1 , refTo ( a2 ) ) ;
data . put ( a1 , data . get ( a2 ) ) ; // trail ( a1)
trail ( a1 ) ; } else if ( t2 == WAMInstruction . REF ) { // STORE [ a2 ] < - STORE [ a1]
// data . put ( a2 , refTo ( a1 ) ) ;
data . put ( a2 , data . get ( a1 ) ) ; // tail ( a2)
trail ( a2 ) ; }


signature:
public class WAMResolvingJavaMachine { /** * Records the address of a binding onto the ' trail ' . The trail pointer is advanced by one as part of this
 * operation .
 * @ param addr The binding address to add to the trail . */
private void trail ( int addr ) { } }

implementation:
// if ( a < HB ) \ / ( ( H < a ) / \ ( a < B ) )
if ( ( addr < hbp ) || ( ( hp < addr ) && ( addr < bp ) ) ) { // TRAIL [ TR ] < - a
data . put ( trp , addr ) ; // TR < - TR + 1
trp ++ ; }


signature:
public class WAMResolvingJavaMachine { /** * Undoes variable bindings that have been recorded on the ' trail ' . Addresses recorded on the trail are reset to REF
 * to self .
 * @ param a1 The start address within the trail to get the first binding address to clear .
 * @ param a2 The end address within the trail , this is one higher than the last address to clear . */
private void unwindTrail ( int a1 , int a2 ) { } }

implementation:
// for i < - a1 to a2 - 1 do
for ( int addr = a1 ; addr < a2 ; addr ++ ) { // STORE [ TRAIL [ i ] ] < - < REF , TRAIL [ i ] >
int tmp = data . get ( addr ) ; data . put ( tmp , refTo ( tmp ) ) ; }


signature:
public class WAMResolvingJavaMachine { /** * Tidies trail when a choice point is being discarded , and a previous choice point it being made the current one .
 * < p / > Copies trail bindings created since the choice point , into the trail as known to the previous choice point .
 * That is bindings on the heap created during the choice point ( between HB and H ) . */
private void tidyTrail ( ) { } }

implementation:
int i ; // Check that there is a current choice point to tidy down to , otherwise tidy down to the root of the trail .
if ( bp == 0 ) { i = TRAIL_BASE ; } else { i = data . get ( bp + data . get ( bp ) + 5 ) ; } while ( i < trp ) { int addr = data . get ( i ) ; if ( ( addr < hbp ) || ( ( hp < addr ) && ( addr < bp ) ) ) { i ++ ; } else { data . put ( i , data . get ( trp - 1 ) ) ; trp -- ; } }


signature:
public class WAMResolvingJavaMachine { /** * Attempts to unify structures or references on the heap , given two references to them . Structures are matched
 * element by element , free references become bound .
 * @ param a1 The address of the first structure or reference .
 * @ param a2 The address of the second structure or reference .
 * @ return < tt > true < / tt > if the two structures unify , < tt > false < / tt > otherwise . */
private boolean unify ( int a1 , int a2 ) { } }

implementation:
// pdl . push ( a1)
// pdl . push ( a2)
uPush ( a1 ) ; uPush ( a2 ) ; // fail < - false
boolean fail = false ; // while ! empty ( PDL ) and not failed
while ( ! uEmpty ( ) && ! fail ) { // d1 < - deref ( pdl . pop ( ) )
// d2 < - deref ( pdl . pop ( ) )
// t1 , v1 < - STORE [ d1]
// t2 , v2 < - STORE [ d2]
int d1 = deref ( uPop ( ) ) ; int t1 = derefTag ; int v1 = derefVal ; int d2 = deref ( uPop ( ) ) ; int t2 = derefTag ; int v2 = derefVal ; // if ( d1 ! = d2)
if ( d1 != d2 ) { // if ( t1 = REF or t2 = REF )
// bind ( d1 , d2)
if ( ( t1 == WAMInstruction . REF ) ) { bind ( d1 , d2 ) ; } else if ( t2 == WAMInstruction . REF ) { bind ( d1 , d2 ) ; } else if ( t2 == WAMInstruction . STR ) { // f1 / n1 < - STORE [ v1]
// f2 / n2 < - STORE [ v2]
int fn1 = data . get ( v1 ) ; int fn2 = data . get ( v2 ) ; byte n1 = ( byte ) ( fn1 >>> 24 ) ; // if f1 = f2 and n1 = n2
if ( fn1 == fn2 ) { // for i < - 1 to n1
for ( int i = 1 ; i <= n1 ; i ++ ) { // pdl . push ( v1 + i )
// pdl . push ( v2 + i )
uPush ( v1 + i ) ; uPush ( v2 + i ) ; } } else { // fail < - true
fail = true ; } } else if ( t2 == WAMInstruction . CON ) { if ( ( t1 != WAMInstruction . CON ) || ( v1 != v2 ) ) { fail = true ; } } else if ( t2 == WAMInstruction . LIS ) { if ( t1 != WAMInstruction . LIS ) { fail = true ; } else { uPush ( v1 ) ; uPush ( v2 ) ; uPush ( v1 + 1 ) ; uPush ( v2 + 1 ) ; } } } } return ! fail ;


signature:
public class WAMResolvingJavaMachine { /** * A simplified unification algorithm , for unifying against a constant .
 * < p / > Attempts to unify a constant or references on the heap , with a constant . If the address leads to a free
 * variable on dereferencing , the variable is bound to the constant . If the address leads to a constant it is
 * compared with the passed in constant for equality , and unification succeeds when they are equal .
 * @ param fn The constant to unify with .
 * @ param addr The address of the first constant or reference .
 * @ return < tt > true < / tt > if the two constant unify , < tt > false < / tt > otherwise . */
private boolean unifyConst ( int fn , int addr ) { } }

implementation:
boolean success ; int deref = deref ( addr ) ; int tag = derefTag ; int val = derefVal ; // case STORE [ addr ] of
switch ( tag ) { case REF : { // < REF , _ > :
// STORE [ addr ] < - < CON , c >
data . put ( deref , constantCell ( fn ) ) ; // trail ( addr )
trail ( deref ) ; success = true ; break ; } case CON : { // < CON , c ' > :
// fail < - ( c ! = c ' ) ;
success = val == fn ; break ; } default : { // other : fail < - true ;
success = false ; } } return success ;


signature:
public class WAMResolvingJavaMachine { /** * Pretty prints a variable allocation slot for tracing purposes .
 * @ param xi The allocation slot to print .
 * @ param mode The addressing mode , stack or register .
 * @ return The pretty printed slot . */
private String printSlot ( int xi , int mode ) { } }

implementation: return ( ( mode == STACK_ADDR ) ? "Y" : "X" ) + ( ( mode == STACK_ADDR ) ? ( xi - ep - 3 ) : xi ) ;


signature:
public class EightPuzzleState { /** * Generates a random starting position .
 * @ return A random board state . */
public static EightPuzzleState getRandomStartState ( ) { } }

implementation:
EightPuzzleState newState ; // Turn the goal string into a list of characters .
List < Character > charList = stringToCharList ( GOAL_STRING ) ; // Generate random puzzles until a solvable one is found .
do { // Shuffle the list .
Collections . shuffle ( charList ) ; // Turn the shuffled list into a proper eight puzzle state object .
newState = charListToState ( charList ) ; // Check that the puzzle is solvable and if not then repeat the shuffling process .
} while ( ! isSolvable ( newState ) ) ; return newState ;


signature:
public class EightPuzzleState { /** * To check for solvability the empty tile is moved to its goal position and then the number of swaps needed to put
 * the other tiles in position is counted . For an odd number of rows on a square puzzle there must be an even number
 * of swaps , for an even number of rows an odd number of swaps .
 * @ param state A puzzle state to test for solvability .
 * @ return True if the puzzle is solvable , false if it is not . */
public static boolean isSolvable ( EightPuzzleState state ) { } }

implementation:
// Take a copy of the puzzle to check . This is done because this puzzle will be updated in - place and the
// original is to be preserved .
EightPuzzleState checkState ; try { checkState = ( EightPuzzleState ) state . clone ( ) ; } catch ( CloneNotSupportedException e ) { throw new IllegalStateException ( "Puzzle state could not be cloned." , e ) ; } // Create the goal state to check against when swapping tiles into position .
EightPuzzleState goalState = getGoalState ( ) ; // Count the number of illegal swaps needed to put the puzzle in order .
int illegalSwaps = 0 ; // Loop over the whole board , left to right , to to bottom
for ( int j = 0 ; j < 3 ; j ++ ) { for ( int i = 0 ; i < 3 ; i ++ ) { // Find out from the goal state what tile should be at this position .
char t = goalState . getTileAt ( i , j ) ; // Swap the tile into its goal position keeping count of the total number of illegal swaps .
illegalSwaps += checkState . swapTileToLocationCountingIllegal ( t , i , j ) ; } } // Check if the number of illegal swaps is even in which case the puzzle is solvable , or odd in which case it
// is not solvable .
return ( illegalSwaps % 2 ) == 0 ;


signature:
public class EightPuzzleState { /** * Applies a move to generate a new board position . This creates a new state object and updates its board position .
 * The board position in this object is not changed .
 * @ param op The move to apply to this board ; " U " for up , " D " for down , " L " for left and " R " for right .
 * @ return A new instance of EightPuzzleState with the operator applied to it . */
public EightPuzzleState getChildStateForOperator ( Operator op ) { } }

implementation:
// Create a copy of the existing board state
EightPuzzleState newState ; try { newState = ( EightPuzzleState ) clone ( ) ; } catch ( CloneNotSupportedException e ) { throw new IllegalStateException ( "Puzzle state could not be cloned." , e ) ; } // Update the new board state using the in - place operator application
newState . updateWithOperator ( op ) ; return newState ;


signature:
public class EightPuzzleState { /** * Supplies the valid moves for a board position .
 * @ param reverse Don ' t care about reverse orderings . Ignored .
 * @ return An iterator over all the moves which are valid for this board position . This can be all 4 , 3 or just 2
 * moves , depending if the empty tile is in the middle , edge or corner positions . */
public Iterator < Operator < String > > validOperators ( boolean reverse ) { } }

implementation:
// Used to hold a list of valid moves
List < Operator < String > > moves = new ArrayList < Operator < String > > ( 4 ) ; // Check if the up move is valid
if ( emptyY != 0 ) { moves . add ( new OperatorImpl < String > ( "U" ) ) ; } // Check if the down move is valid
if ( emptyY != 2 ) { moves . add ( new OperatorImpl < String > ( "D" ) ) ; } // Check if the left move is valid
if ( emptyX != 0 ) { moves . add ( new OperatorImpl < String > ( "L" ) ) ; } // Check if the right move is valid
if ( emptyX != 2 ) { moves . add ( new OperatorImpl < String > ( "R" ) ) ; } return moves . iterator ( ) ;


signature:
public class EightPuzzleState { /** * Pretty prints the board as 3 lines of characters with a space for the empty square .
 * @ return A pretty printed string representation of this board position . */
public String prettyPrint ( ) { } }

implementation: String result = "" ; for ( int j = 0 ; j < 3 ; j ++ ) { result += new String ( board [ j ] ) + "\n" ; } result = result . replace ( 'E' , ' ' ) ; return result ;


signature:
public class EightPuzzleState { /** * Repeatedly swaps a tile with its neighbours until it reaches the specified location . If the tile is swapped with
 * the empty tile then this is a legal move . If the tile is swapped with another non - empty tile then this is an
 * illegal move and the total number of illegal moves is counted .
 * < p > This method updates the board position array in - place , rather than generating a new state .
 * @ param t the tile to move .
 * @ param x the X position to move the tile to .
 * @ param y the Y position to move the tile to .
 * @ return the number of illegal swaps performed . */
protected int swapTileToLocationCountingIllegal ( char t , int x , int y ) { } }

implementation:
// Used to hold the count of illegal swaps
int illegal = 0 ; // Find out where the tile to move is
int tileX = getXForTile ( t ) ; int tileY = getYForTile ( t ) ; // Shift the tile into the correct column by repeatedly moving it left or right .
while ( tileX != x ) { if ( ( tileX - x ) > 0 ) { if ( swapTiles ( tileX , tileY , tileX - 1 , tileY ) ) { illegal ++ ; } tileX -- ; } else { if ( swapTiles ( tileX , tileY , tileX + 1 , tileY ) ) { illegal ++ ; } tileX ++ ; } } // Shift the tile into the correct row by repeatedly moving it up or down .
while ( tileY != y ) { // Commented out because tiles never swap down the board during the solvability test because tiles are
// swapped into place left to right , top to bottom . The top row is always filled first so tiles cannot be
// swapped down into it . Then the next row is filled but ones from the row above are never swapped down
// into it because they are alrady in place and never move again and so on .
/* if ( tileY - y > 0) */
if ( swapTiles ( tileX , tileY , tileX , tileY - 1 ) ) { illegal ++ ; } tileY -- ; /* * else { if ( swapTiles ( tileX , tileY , tileX , tileY + 1 ) ) illegal + + ; tileY + + ; } */
} return illegal ;


signature:
public class EightPuzzleState { /** * Applies a move to the board position . This changes the board position stored in this object . This is different
 * from the { @ link # getChildStateForOperator } method which updates the board position in a new object .
 * @ param op The move to apply to this board ; " U " for up , " D " for down , " L " for left and " R " for right . */
protected void updateWithOperator ( Operator op ) { } }

implementation:
// Get the operator as a character by taking the first character of the operator string
char opc = ( ( String ) op . getOp ( ) ) . charAt ( 0 ) ; // Move the empty tile according to the specified operation
switch ( opc ) { // Swap the empty tile with the one above it .
case 'U' : { swapTiles ( emptyX , emptyY , emptyX , emptyY - 1 ) ; break ; } // Swap the empty tile with the one below it .
case 'D' : { swapTiles ( emptyX , emptyY , emptyX , emptyY + 1 ) ; break ; } // Swap the empty tile with the one to the left of it .
case 'L' : { swapTiles ( emptyX , emptyY , emptyX - 1 , emptyY ) ; break ; } // Swap the empty tile with the one to the right of it .
case 'R' : { swapTiles ( emptyX , emptyY , emptyX + 1 , emptyY ) ; break ; } default : { throw new IllegalStateException ( "Unkown operator: " + opc + "." ) ; } }


signature:
public class EightPuzzleState { /** * Swaps the two tiles at the specified coordinates . One of the tiles may be the empty tile and the empty tile
 * position will be correctly updated . If neither of the tiles is empty then this is an illegal swap in which case
 * the method returns true .
 * @ param x1 the X position of tile 1
 * @ param y1 the Y position of tile 1
 * @ param x2 the X position of tile 2
 * @ param y2 the Y position of tile 2
 * @ return True if it is an illegal swap . */
protected boolean swapTiles ( int x1 , int y1 , int x2 , int y2 ) { } }

implementation:
// Used to indicate that one of the swapped tiles was the empty tile
boolean swappedEmpty = false ; // Get the tile at the first position
char tile1 = board [ y1 ] [ x1 ] ; // Store the tile from the second position at the first position
char tile2 = board [ y2 ] [ x2 ] ; board [ y1 ] [ x1 ] = tile2 ; // Store the first tile in the second position
board [ y2 ] [ x2 ] = tile1 ; // Check if the first tile was the empty tile and update the empty tile coordinates if so
if ( tile1 == 'E' ) { emptyX = x2 ; emptyY = y2 ; swappedEmpty = true ; } // Else check if the second tile was the empty tile and update the empty tile coordinates if so
else if ( tile2 == 'E' ) { emptyX = x1 ; emptyY = y1 ; swappedEmpty = true ; } return ! swappedEmpty ;


signature:
public class EightPuzzleState { /** * Turns a string representation of the board into a list of characters .
 * @ param boardString The board as a string of nine characters .
 * @ return The board as a List of characters . */
private static List < Character > stringToCharList ( String boardString ) { } }

implementation:
// Turn the goal state into a list of characters
char [ ] chars = new char [ 9 ] ; boardString . getChars ( 0 , 9 , chars , 0 ) ; List < Character > charList = new ArrayList < Character > ( ) ; for ( int l = 0 ; l < 9 ; l ++ ) { charList . add ( chars [ l ] ) ; } return charList ;


signature:
public class EightPuzzleState { /** * Turns a list of characters representation of the board into a proper state .
 * @ param charList The board as a list of 9 characters .
 * @ return The board as an EightPuzzleState . */
private static EightPuzzleState charListToState ( List < Character > charList ) { } }

implementation:
// Create a new empty puzzle state
EightPuzzleState newState = new EightPuzzleState ( ) ; // Loop over the board inserting the characters into it from the character list
Iterator < Character > k = charList . iterator ( ) ; for ( int j = 0 ; j < 3 ; j ++ ) { for ( int i = 0 ; i < 3 ; i ++ ) { char nextChar = k . next ( ) ; // Check if this is the empty tile and if so then take note of its position
if ( nextChar == 'E' ) { newState . emptyX = i ; newState . emptyY = j ; } newState . board [ j ] [ i ] = nextChar ; } } return newState ;


signature:
public class LoggingToLog4JHandler { /** * { @ inheritDoc } */
public void publish ( LogRecord record ) { } }

implementation: org . apache . log4j . Logger log4j = getTargetLogger ( record . getLoggerName ( ) ) ; Priority priority = toLog4j ( record . getLevel ( ) ) ; if ( ! priority . equals ( org . apache . log4j . Level . OFF ) ) { log4j . log ( priority , toLog4jMessage ( record ) , record . getThrown ( ) ) ; }


signature:
public class LoggingToLog4JHandler { /** * Transforms a java . util . logging . LogRecord to a message printable on Log4J .
 * @ param record The log record .
 * @ return The log4j message . */
private String toLog4jMessage ( LogRecord record ) { } }

implementation:
String message = record . getMessage ( ) ; // Format message
Object [ ] parameters = record . getParameters ( ) ; if ( ( parameters != null ) && ( parameters . length != 0 ) ) { // Check for the first few parameters ?
if ( ( message . indexOf ( "{0}" ) >= 0 ) || ( message . indexOf ( "{1}" ) >= 0 ) || ( message . indexOf ( "{2}" ) >= 0 ) || ( message . indexOf ( "{3}" ) >= 0 ) ) { message = MessageFormat . format ( message , parameters ) ; } } return message ;


signature:
public class LoggingToLog4JHandler { /** * Converts java . util . logging levels to Log4J logging levels .
 * @ param level The java . util . logging level to convert .
 * @ return The corresponding Log4J level . */
private org . apache . log4j . Level toLog4j ( Level level ) { } }

implementation: if ( Level . SEVERE == level ) { return org . apache . log4j . Level . ERROR ; } else if ( Level . WARNING == level ) { return org . apache . log4j . Level . WARN ; } else if ( Level . INFO == level ) { return org . apache . log4j . Level . INFO ; } else if ( Level . FINE == level ) { return org . apache . log4j . Level . DEBUG ; } else if ( Level . FINER == level ) { return org . apache . log4j . Level . TRACE ; } else if ( Level . OFF == level ) { return org . apache . log4j . Level . OFF ; } return org . apache . log4j . Level . OFF ;


signature:
public class WrapperQueue { /** * { @ inheritDoc } */
public boolean offer ( E o ) { } }

implementation:
if ( transactional ) { // Delegate the offer operation to the wrapped queue .
txMethod . requestWriteOperation ( new EnqueueRecord ( o ) ) ; // return success ;
return true ; } else { boolean success = queue . offer ( o ) ; // Update the queue size if the offer was succesfull .
if ( success ) { incrementSizeAndCount ( o ) ; } return success ; }


signature:
public class WrapperQueue { /** * { @ inheritDoc } */
public E poll ( ) { } }

implementation:
Object owner ; if ( transactional ) { owner = TxManager . getCurrentSession ( ) ; } else { owner = null ; } // Attempt to acquire an available element from the queue for the current transaction .
return pollAccept ( owner ) ;


signature:
public class WrapperQueue { /** * { @ inheritDoc } */
public E pollAccept ( Object owner ) { } }

implementation:
if ( transactional ) { E element = null ; RequeueElementWrapper < E > record = null ; // Find an element on the requeue that is free , or has already been acquired by the owner but not accepted .
// Mark the element as acquired by the owner as necessary .
if ( ! requeue . isEmpty ( ) ) { for ( RequeueElementWrapper < E > nextRecord : requeue ) { if ( AcquireState . Free . equals ( nextRecord . state ) ) { record = nextRecord ; record . state = AcquireState . Acquired ; record . owner = owner ; element = record . element ; break ; } else if ( AcquireState . Acquired . equals ( nextRecord . state ) && owner . equals ( nextRecord . owner ) ) { record = nextRecord ; element = record . element ; break ; } } } // If an element cannot be found on the requeue , poll an element from the main queue , and place it onto the
// requeue .
if ( record == null ) { element = queue . poll ( ) ; } // If no element at all can be found return null .
if ( element == null ) { return element ; } // Check that an element was actually available on the queue before creating a new acquired record for it
// on the requeue .
if ( record == null ) { record = requeue ( element , owner , AcquireState . Acquired ) ; } // Accept the element and create a transaction operation to remove it upon commit or unnaccept it upon
// rollback .
record . state = AcquireState . Accepted ; txMethod . requestWriteOperation ( new AcceptRecord ( record ) ) ; return record . element ; } else { E element ; // Find an element on the requeue that is free . Remove it and return it .
if ( ! requeue . isEmpty ( ) ) { for ( RequeueElementWrapper < E > nextRecord : requeue ) { if ( AcquireState . Free . equals ( nextRecord . state ) ) { requeue . remove ( nextRecord ) ; requeuedElementMap . remove ( nextRecord . element ) ; return nextRecord . element ; } } } // Or poll an element from the main queue and return it .
element = queue . poll ( ) ; if ( element != null ) { decrementSizeAndCount ( element ) ; } return element ; }


signature:
public class WrapperQueue { /** * { @ inheritDoc } */
public E pollAcquire ( Object owner ) { } }

implementation:
E element ; // Find an element on the requeue that is free and return it .
if ( ! requeue . isEmpty ( ) ) { for ( RequeueElementWrapper < E > nextRecord : requeue ) { if ( AcquireState . Free . equals ( nextRecord . state ) ) { nextRecord . state = AcquireState . Acquired ; nextRecord . owner = owner ; return nextRecord . element ; } } } // Nothing could be found on the requeue , so attempt to poll an element off the main queue and acquire
// it on the requeue .
element = queue . poll ( ) ; if ( element != null ) { requeue ( element , owner , AcquireState . Acquired ) ; } return element ;


signature:
public class WrapperQueue { /** * { @ inheritDoc } */
public boolean acquire ( Object owner , Object o ) { } }

implementation:
// Look up the element wrapper record for the element to be accepted .
RequeueElementWrapper < E > record = requeuedElementMap . get ( o ) ; // Check if the element is currently free , and acquire it if so .
if ( AcquireState . Free . equals ( record . state ) ) { record . state = AcquireState . Acquired ; record . owner = owner ; return true ; } return false ;


signature:
public class WrapperQueue { /** * { @ inheritDoc } */
public void release ( Object owner , Object o ) { } }

implementation:
// Look up the element wrapper record for the element to be released , and release it .
RequeueElementWrapper < E > record = requeuedElementMap . get ( o ) ; if ( record != null ) { record . state = AcquireState . Free ; record . owner = null ; }