Input: { [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor functor , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { SizeableLinkedList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; SizeableLinkedList < WAMInstruction > instructions ; Term [ ] expressions = functor . getArguments ( ) ; for ( int i = 0 ; i < expressions . length ; i ++ ) { Functor expression = ( Functor ) expressions [ i ] ; Integer permVarsRemaining = ( Integer ) defaultBuiltIn . getSymbolTable ( ) . get ( expression . getSymbolKey ( ) , SYMKEY_PERM_VARS_REMAINING ) ; // Select a non-default built-in implementation to compile the functor with, if it is a built-in. BuiltIn builtIn ; if ( expression instanceof BuiltIn ) { builtIn = ( BuiltIn ) expression ; } else { builtIn = defaultBuiltIn ; } // The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule. instructions = builtIn . compileBodyArguments ( expression , false , clauseName , bodyNumber ) ; result . addAll ( instructions ) ; // Call the body. The number of permanent variables remaining is specified for environment trimming. instructions = builtIn . compileBodyCall ( expression , false , false , false , 0 /*permVarsRemaining*/ ) ; result . addAll ( instructions ) ; } return result ; }


Input: { [CODESPLIT] public void actionPerformed ( ActionEvent e ) { String groupName = e . getActionCommand ( ) ; FadeState fadeState = timers . get ( groupName ) ; if ( fadeState . interpolator . hasNext ( ) ) { Color color = fadeState . interpolator . next ( ) ; fadeState . target . changeColor ( color ) ; fadeState . timer . setInitialDelay ( 0 ) ; fadeState . timer . restart ( ) ; } }


Input: Requests a color fade against the specified target under a group name . [CODESPLIT] public void doFade ( ColorDelta target , String groupName ) { FadeState fadeState = timers . get ( groupName ) ; // Set up the color interpolator. Iterator < Color > interpolator = new ColorInterpolator ( startColor , endColor , 8 ) . iterator ( ) ; if ( fadeState == null ) { // Create a new fade state for the target group, and a timer to run it. Timer timer = new Timer ( 20 , this ) ; fadeState = new FadeState ( timer , target , interpolator ) ; timers . put ( groupName , fadeState ) ; } else { // Kill any previous fade and replace the target with the new one. fadeState . timer . stop ( ) ; fadeState . target = target ; fadeState . interpolator = interpolator ; } // Iterate to the initial color. Color firstColor = fadeState . interpolator . next ( ) ; fadeState . target . changeColor ( firstColor ) ; // Kick off the fade timer. fadeState . timer . setActionCommand ( groupName ) ; fadeState . timer . setInitialDelay ( 400 ) ; fadeState . timer . start ( ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] private static CombinableMatcher < RecordedRequest > recordedRequest ( String expectedMethod , String expectedPath ) { return Matchers . < RecordedRequest > both ( hasProperty ( "method" , is ( expectedMethod ) ) ) . and ( hasProperty ( "path" , is ( expectedPath ) ) ) ; }


Input: { [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof NumericTypeVisitor ) { ( ( NumericTypeVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }


Input: { [CODESPLIT] public void showMainWindow ( ) { frame = new JFrame ( ) ; frame . setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; frame . setMinimumSize ( new Dimension ( 800 , 600 ) ) ; frame . setPreferredSize ( new Dimension ( 1000 , 800 ) ) ; layout = new DesktopAppLayout ( ) ; frame . getContentPane ( ) . setLayout ( layout ) ; frame . setVisible ( true ) ; JRootPane rootPane = frame . getRootPane ( ) ; rootPane . getInputMap ( ) . put ( KeyStroke . getKeyStroke ( "SPACE" ) , "pressed" ) ; }


Input: { [CODESPLIT] public void showCentrePane ( JComponent component ) { frame . getContentPane ( ) . add ( component , DesktopAppLayout . CENTER ) ; frame . pack ( ) ; centreComponent = component ; }


Input: { [CODESPLIT] public void showConsole ( JComponent component ) { showHorizontalBar ( ) ; frame . getContentPane ( ) . add ( component , DesktopAppLayout . CONSOLE ) ; frame . pack ( ) ; consoleComponent = component ; }


Input: { [CODESPLIT] public void showLeftPane ( JComponent component ) { showLeftBar ( ) ; frame . getContentPane ( ) . add ( component , DesktopAppLayout . LEFT_PANE ) ; frame . pack ( ) ; leftComponent = component ; }


Input: { [CODESPLIT] public void showRightPane ( JComponent component ) { showRightBar ( ) ; frame . getContentPane ( ) . add ( component , DesktopAppLayout . RIGHT_PANE ) ; frame . pack ( ) ; rightComponent = component ; }


Input: { [CODESPLIT] public void setKeyShortcut ( KeyStroke keyCombination , String actionName , Runnable action ) { frame . getRootPane ( ) . getInputMap ( JComponent . WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ) . put ( keyCombination , actionName ) ; frame . getRootPane ( ) . getActionMap ( ) . put ( actionName , new RunnableAction ( action ) ) ; }


Input: Creates a horizontal grip - able bar for adjusting the console height . [CODESPLIT] private void showHorizontalBar ( ) { // Left vertical bar. Component bar = factory . createGripPanel ( layout . getConsoleHeightResizer ( ) , false ) ; frame . getContentPane ( ) . add ( bar , DesktopAppLayout . STATUS_BAR ) ; }


Input: Creates a vertical grip - able bar for adjusting the left panel width . [CODESPLIT] private void showLeftBar ( ) { // Left vertical bar. Component bar = factory . createGripPanel ( layout . getLeftPaneWidthResizer ( ) , true ) ; frame . getContentPane ( ) . add ( bar , DesktopAppLayout . LEFT_VERTICAL_BAR ) ; }


Input: Creates a vertical grip - able bar for adjusting the right panel width . [CODESPLIT] private void showRightBar ( ) { // Right vertical bar. Component bar = factory . createGripPanel ( layout . getRightPaneWidthResizer ( ) , true ) ; frame . getContentPane ( ) . add ( bar , DesktopAppLayout . RIGHT_VERTICAL_BAR ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public List < MicrodataItem > getItems ( String type ) { Elements elements = document . select ( byItemType ( newUrl ( type ) ) ) ; return Lists . transform ( elements , new Function < Element , MicrodataItem > ( ) { public MicrodataItem apply ( Element element ) { return new JsoupMicrodataItem ( JsoupMicrodataDocument . this , element ) ; } } ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public List < Link > getLinks ( String rel ) { Elements elements = document . select ( byLink ( rel ) ) ; return Lists . transform ( elements , new Function < Element , Link > ( ) { public Link apply ( Element element ) { return new JsoupLink ( JsoupMicrodataDocument . this , element ) ; } } ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public < T > T unwrap ( Class < T > type ) { checkArgument ( Document . class . equals ( type ) , "Cannot unwrap to: %s" , type ) ; return type . cast ( document ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] private static Document sanitize ( Document document ) { for ( FormElement form : document . getAllElements ( ) . forms ( ) ) { sanitizeRadioControls ( form ) ; } return document ; }


Input: Ensures that radio controls are mutually exclusive within control groups . [CODESPLIT] private static void sanitizeRadioControls ( FormElement form ) { Map < String , Element > controlsByName = new HashMap < String , Element > ( ) ; for ( Element control : form . elements ( ) ) { // cannot use Element.select since Element.hashCode collapses like elements if ( "radio" . equals ( control . attr ( "type" ) ) && control . hasAttr ( "checked" ) ) { String name = control . attr ( "name" ) ; if ( controlsByName . containsKey ( name ) ) { controlsByName . get ( name ) . attr ( "checked" , false ) ; } controlsByName . put ( name , control ) ; } } }


Input: Wait for the predicate to become true on the specified object . [CODESPLIT] public void await ( T t ) throws InterruptedException { synchronized ( monitor ) { long waitNanos = evaluateWithWaitTimeNanos ( t ) ; // Loop forever until all conditions pass or the thread is interrupted. while ( waitNanos > 0 ) { // If some conditions failed, then wait for the shortest wait time, or until the thread is woken up by // a signal, before re-evaluating conditions. long milliPause = waitNanos / 1000000 ; int nanoPause = ( int ) ( waitNanos % 1000000 ) ; monitor . wait ( milliPause , nanoPause ) ; waitNanos = evaluateWithWaitTimeNanos ( t ) ; } } }


Input: Wait for up to a timeout limit for the predicate to become true on the specified object . [CODESPLIT] public boolean await ( T t , long timeout , TimeUnit unit ) throws InterruptedException { synchronized ( monitor ) { // Holds the absolute time when the timeout expires. long expiryTimeNanos = System . nanoTime ( ) + unit . toNanos ( timeout ) ; // Used to hold the estimated wait time until the condition may pass. long waitNanos = evaluateWithWaitTimeNanos ( t ) ; // Loop forever until all conditions pass, the timeout expires, or the thread is interrupted. while ( waitNanos > 0 ) { // Check how much time remains until the timeout expires. long remainingTimeNanos = expiryTimeNanos - System . nanoTime ( ) ; // Check if the timeout has expired. if ( remainingTimeNanos <= 0 ) { return false ; } // If some conditions failed, then wait for the shortest of the wait time or the remaining time until the // timout expires, or until the thread is woken up by a signal, before re-evaluating conditions. long timeToPauseNanos = ( waitNanos < remainingTimeNanos ) ? waitNanos : remainingTimeNanos ; long milliPause = timeToPauseNanos / 1000000 ; int nanoPause = ( int ) ( timeToPauseNanos % 1000000 ) ; monitor . wait ( milliPause , nanoPause ) ; // Re-evelaute the condition and obtain a new estimate of how long until it may pass. waitNanos = evaluateWithWaitTimeNanos ( t ) ; } } // All conditions have passed when the above loop terminates. return true ; }


Input: Implementation of the script goal . [CODESPLIT] public void execute ( ) throws MojoExecutionException , MojoFailureException { //log.debug("public void execute() throws MojoExecutionException: called"); // Turn each of the test runner command lines into a script. for ( String commandName : commands . keySet ( ) ) { if ( scriptOutDirectory != null ) { writeUnixScript ( commandName , scriptOutDirectory ) ; writeWindowsScript ( commandName , scriptOutDirectory ) ; } } }


Input: Appends the classpath onto the command line . [CODESPLIT] protected String appendClasspath ( String commandLine , boolean unix ) { String pathSeperator ; String seperator ; if ( unix ) { pathSeperator = "/" ; seperator = ":" ; } else { pathSeperator = "\\" ; seperator = ";" ; } for ( Iterator i = classpathElements . iterator ( ) ; i . hasNext ( ) ; ) { String cpPath = ( String ) i . next ( ) ; cpPath = cpPath . replace ( "/" , pathSeperator ) ; commandLine += cpPath + ( i . hasNext ( ) ? seperator : "" ) ; } return commandLine ; }


Input: Creates a new date range type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , DateOnly from , DateOnly to ) { // Ensure that min is less than or equal to max. if ( ( from != null ) && ( to != null ) && ( from . compareTo ( to ) > 0 ) ) { throw new IllegalArgumentException ( "'min' must be less than or equal to 'max'." ) ; } synchronized ( DATE_RANGE_TYPES ) { // Add the newly created type to the map of all types. DateRangeType newType = new DateRangeType ( name , from , to ) ; // 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. DateRangeType oldType = DATE_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 { DATE_RANGE_TYPES . put ( name , newType ) ; return newType ; } } }


Input: { [CODESPLIT] public void acceptVisitor ( TypeVisitor visitor ) { if ( visitor instanceof DateRangeTypeVisitor ) { ( ( DateRangeTypeVisitor ) visitor ) . visit ( this ) ; } else { super . acceptVisitor ( visitor ) ; } }


Input: Frees all variables held in this stack frame and sets all the stack slots to <tt > null< / tt > . Note that as the stack slots are <tt > null< / tt > the { [CODESPLIT] public void free ( ) { for ( int i = 0 ; i < bindings . length ; i ++ ) { if ( bindings [ i ] != null ) { bindings [ i ] . free ( ) ; bindings [ i ] = null ; } } }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public List < Link > getLinks ( String rel ) { List < WebElement > elements = element . findElements ( byLink ( rel ) ) ; return Lists . transform ( elements , new Function < WebElement , Link > ( ) { public Link apply ( WebElement element ) { return new SeleniumLink ( driver , element ) ; } } ) ; }


Input: Implements the top - level interpreter loop . This will parse and evaluate sentences until it encounters an CTRL - D in query mode at which point the interpreter will terminate . [CODESPLIT] public void interpreterLoop ( ) throws IOException { // Display the welcome message. printIntroduction ( ) ; // Initialize the JLine console. consoleReader = initializeCommandLineReader ( ) ; // Used to buffer input, and only feed it to the parser when a PERIOD is encountered. TokenBuffer tokenBuffer = new TokenBuffer ( ) ; // Used to hold the currently buffered lines of input, for the purpose of presenting this back to the user // in the event of a syntax or other error in the input. ArrayList < String > inputLines = new ArrayList < String > ( ) ; // Used to count the number of lines entered. int lineNo = 0 ; while ( true ) { String line = null ; try { line = consoleReader . readLine ( mode . prompt ) ; inputLines . add ( line ) ; // JLine returns null if CTRL-D is pressed. Exit program mode back to query mode, or exit the // interpreter completely from query mode. if ( ( line == null ) && ( ( mode == Mode . Query ) || ( mode == Mode . QueryMultiLine ) ) ) { /*log.fine("CTRL-D in query mode, exiting.");*/ System . out . println ( ) ; break ; } else if ( ( line == null ) && ( ( mode == Mode . Program ) || ( mode == Mode . ProgramMultiLine ) ) ) { /*log.fine("CTRL-D in program mode, returning to query mode.");*/ System . out . println ( ) ; mode = Mode . Query ; continue ; } // Check the input to see if a system directive was input. This is only allowed in query mode, and is // handled differently to normal queries. if ( mode == Mode . Query ) { Source < Token > tokenSource = new OffsettingTokenSource ( TokenSource . getTokenSourceForString ( line ) , lineNo ) ; parser . setTokenSource ( tokenSource ) ; PrologParser . Directive directive = parser . peekAndConsumeDirective ( ) ; if ( directive != null ) { switch ( directive ) { case Trace : /*log.fine("Got trace directive.");*/ break ; case Info : /*log.fine("Got info directive.");*/ break ; case User : /*log.fine("Got user directive, entering program mode.");*/ mode = Mode . Program ; break ; } inputLines . clear ( ) ; continue ; } } // For normal queries, the query functor '?-' begins every statement, this is not passed back from // JLine even though it is used as the command prompt. if ( mode == Mode . Query ) { line = QUERY_PROMPT + line ; inputLines . set ( inputLines . size ( ) - 1 , line ) ; } // Buffer input tokens until EOL is reached, of the input is terminated with a PERIOD. Source < Token > tokenSource = new OffsettingTokenSource ( TokenSource . getTokenSourceForString ( line ) , lineNo ) ; Token nextToken ; while ( true ) { nextToken = tokenSource . poll ( ) ; if ( nextToken == null ) { break ; } if ( nextToken . kind == PrologParserConstants . PERIOD ) { /*log.fine("Token was PERIOD.");*/ mode = ( mode == Mode . QueryMultiLine ) ? Mode . Query : mode ; mode = ( mode == Mode . ProgramMultiLine ) ? Mode . Program : mode ; tokenBuffer . offer ( nextToken ) ; break ; } else if ( nextToken . kind == PrologParserConstants . EOF ) { /*log.fine("Token was EOF.");*/ mode = ( mode == Mode . Query ) ? Mode . QueryMultiLine : mode ; mode = ( mode == Mode . Program ) ? Mode . ProgramMultiLine : mode ; lineNo ++ ; break ; } tokenBuffer . offer ( nextToken ) ; } // Evaluate the current token buffer, whenever the input is terminated with a PERIOD. if ( ( nextToken != null ) && ( nextToken . kind == PrologParserConstants . PERIOD ) ) { parser . setTokenSource ( tokenBuffer ) ; // Parse the next clause. Sentence < Clause > nextParsing = parser . parse ( ) ; /*log.fine(nextParsing.toString());*/ evaluate ( nextParsing ) ; inputLines . clear ( ) ; } } catch ( SourceCodeException e ) { SourceCodePosition sourceCodePosition = e . getSourceCodePosition ( ) . asZeroOffsetPosition ( ) ; int startLine = sourceCodePosition . getStartLine ( ) ; int endLine = sourceCodePosition . getEndLine ( ) ; int startColumn = sourceCodePosition . getStartColumn ( ) ; int endColumn = sourceCodePosition . getEndColumn ( ) ; System . out . println ( "[(" + startLine + ", " + startColumn + "), (" + endLine + ", " + endColumn + ")]" ) ; for ( int i = 0 ; i < inputLines . size ( ) ; i ++ ) { String errorLine = inputLines . get ( i ) ; System . out . println ( errorLine ) ; // Check if the line has the error somewhere in it, and mark the part of it that contains the error. int pos = 0 ; if ( i == startLine ) { for ( ; pos < startColumn ; pos ++ ) { System . out . print ( " " ) ; } } if ( i == endLine ) { for ( ; pos <= endColumn ; pos ++ ) { System . out . print ( "^" ) ; } System . out . println ( ) ; } if ( ( i > startLine ) && ( i < endLine ) ) { for ( ; pos < errorLine . length ( ) ; pos ++ ) { System . out . print ( "^" ) ; } System . out . println ( ) ; } } System . out . println ( ) ; System . out . println ( e . getMessage ( ) ) ; System . out . println ( ) ; inputLines . clear ( ) ; tokenBuffer . clear ( ) ; } } }


Input: Prints a welcome message . [CODESPLIT] private void printIntroduction ( ) { System . out . println ( "| LoJiX Prolog." ) ; System . out . println ( "| Copyright The Sett Ltd." ) ; System . out . println ( "| Licensed under the Apache License, Version 2.0." ) ; System . out . println ( "| //www.apache.org/licenses/LICENSE-2.0" ) ; System . out . println ( ) ; }


Input: Sets up the JLine console reader . [CODESPLIT] private ConsoleReader initializeCommandLineReader ( ) throws IOException { ConsoleReader reader = new ConsoleReader ( ) ; reader . setBellEnabled ( false ) ; return reader ; }


Input: Evaluates a query against the resolver or adds a clause to the resolvers domain . [CODESPLIT] private void evaluate ( Sentence < Clause > sentence ) throws SourceCodeException { Clause clause = sentence . getT ( ) ; if ( clause . isQuery ( ) ) { engine . endScope ( ) ; engine . compile ( sentence ) ; evaluateQuery ( ) ; } else { // Check if the program clause is new, or a continuation of the current predicate. int name = clause . getHead ( ) . getName ( ) ; if ( ( currentPredicateName == null ) || ( currentPredicateName != name ) ) { engine . endScope ( ) ; currentPredicateName = name ; } addProgramClause ( sentence ) ; } }


Input: Evaluates a query . In the case of queries the interner is used to recover textual names for the resulting variable bindings . The user is queried through the parser to if more than one solution is required . [CODESPLIT] private void evaluateQuery ( ) { /*log.fine("Read query from input.");*/ // Create an iterator to generate all solutions on demand with. Iteration will stop if the request to // the parser for the more ';' token fails. Iterator < Set < Variable >> i = engine . iterator ( ) ; if ( ! i . hasNext ( ) ) { System . out . println ( "false. " ) ; return ; } for ( ; i . hasNext ( ) ; ) { Set < Variable > solution = i . next ( ) ; if ( solution . isEmpty ( ) ) { System . out . print ( "true" ) ; } else { for ( Iterator < Variable > j = solution . iterator ( ) ; j . hasNext ( ) ; ) { Variable nextVar = j . next ( ) ; String varName = engine . getVariableName ( nextVar . getName ( ) ) ; System . out . print ( varName + " = " + nextVar . getValue ( ) . toString ( engine , true , false ) ) ; if ( j . hasNext ( ) ) { System . out . println ( ) ; } } } // Finish automatically if there are no more solutions. if ( ! i . hasNext ( ) ) { System . out . println ( "." ) ; break ; } // Check if the user wants more solutions. try { int key = consoleReader . readVirtualKey ( ) ; if ( key == SEMICOLON ) { System . out . println ( " ;" ) ; } else { System . out . println ( ) ; break ; } } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } }


Input: Converts a boolean into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( boolean b ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Boolean . toString ( b ) ) ; result . nativeType = BOOLEAN ; return result ; }


Input: Converts a byte into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( byte b ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Byte . toString ( b ) ) ; result . nativeType = BYTE ; return result ; }


Input: Converts a char into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( char c ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Character . toString ( c ) ) ; result . nativeType = CHAR ; return result ; }


Input: Converts a short into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( short s ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Short . toString ( s ) ) ; result . nativeType = SHORT ; return result ; }


Input: Converts a int into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( int i ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Integer . toString ( i ) ) ; result . nativeType = INT ; return result ; }


Input: Converts a long into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( long l ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Long . toString ( l ) ) ; result . nativeType = LONG ; return result ; }


Input: Converts a float into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( float f ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Float . toString ( f ) ) ; result . nativeType = FLOAT ; return result ; }


Input: Converts a double into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( double d ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Double . toString ( d ) ) ; result . nativeType = DOUBLE ; return result ; }


Input: Converts a String into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( String s ) { MultiTypeData result = new MultiTypeData ( ) ; // Start by assuming that the String can only be converted to a String. result . typeFlags = STRING ; result . stringValue = s ; // Assume that the native type is String. It is up to methods that call this one to override this if this is // not the case. result . nativeType = STRING ; // Check if the string can be converted to a boolean. if ( "true" . equals ( s ) ) { result . booleanValue = true ; result . typeFlags |= BOOLEAN ; } else if ( "false" . equals ( s ) ) { result . booleanValue = false ; result . typeFlags |= BOOLEAN ; } // Check if the string can be converted to an int. try { result . intValue = Integer . parseInt ( s ) ; result . typeFlags |= INT ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags &= ( Integer . MAX_VALUE - INT ) ; } // Check if the string can be converted to a byte. try { result . byteValue = Byte . parseByte ( s ) ; result . typeFlags |= BYTE ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags = ( Integer . MAX_VALUE - BYTE ) ; } // Check if the string can be converted to a char. if ( s . length ( ) == 1 ) { result . charValue = s . charAt ( 0 ) ; result . typeFlags |= CHAR ; } // Check if the string can be converted to a short. try { result . shortValue = Short . parseShort ( s ) ; result . typeFlags |= SHORT ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags = ( Integer . MAX_VALUE - SHORT ) ; } // Check if the string can be converted to a long. try { result . longValue = Long . parseLong ( s ) ; result . typeFlags |= LONG ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags = ( Integer . MAX_VALUE - LONG ) ; } // Check if the string can be converted to a float. try { result . floatValue = Float . parseFloat ( s ) ; result . typeFlags |= FLOAT ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags = ( Integer . MAX_VALUE - FLOAT ) ; } // Check if the string can be converted to a double. try { result . doubleValue = Double . parseDouble ( s ) ; result . typeFlags |= DOUBLE ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags = ( Integer . MAX_VALUE - DOUBLE ) ; } // Assume the string can never be converted to an object. return result ; }


Input: Converts a Object into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( Object o ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( o . toString ( ) ) ; result . nativeType = OBJECT ; return result ; }


Input: Given a multi type data object and a class representing a type this method attemps to return an object of that class created from the multi type data . The exception to this rule is if the specified data type is a primtive type such as int . clas then the returned object will be of the equivalent wrapper class type Integer . class in this case . This is because a primitive cannot be returned under an Object return type . [CODESPLIT] public static Object convert ( MultiTypeData d , Class c ) { // Check if it is an boolean convertion. if ( ( ( d . typeFlags & BOOLEAN ) != 0 ) && ( Boolean . TYPE . equals ( c ) || Boolean . class . equals ( c ) ) ) { return d . booleanValue ; } // Check if it is an int convertion. else if ( ( ( d . typeFlags & INT ) != 0 ) && ( Integer . TYPE . equals ( c ) || Integer . class . equals ( c ) ) ) { return d . intValue ; } // Check if it is an char convertion. else if ( ( ( d . typeFlags & CHAR ) != 0 ) && ( Character . TYPE . equals ( c ) || Character . class . equals ( c ) ) ) { return d . charValue ; } // Check if it is an byte convertion. else if ( ( ( d . typeFlags & BYTE ) != 0 ) && ( Byte . TYPE . equals ( c ) || Byte . class . equals ( c ) ) ) { return d . byteValue ; } // Check if it is an short convertion. else if ( ( ( d . typeFlags & SHORT ) != 0 ) && ( Short . TYPE . equals ( c ) || Short . class . equals ( c ) ) ) { return d . shortValue ; } // Check if it is an long convertion. else if ( ( ( d . typeFlags & LONG ) != 0 ) && ( Long . TYPE . equals ( c ) || Long . class . equals ( c ) ) ) { return d . longValue ; } // Check if it is an float convertion. else if ( ( ( d . typeFlags & FLOAT ) != 0 ) && ( Float . TYPE . equals ( c ) || Float . class . equals ( c ) ) ) { return d . floatValue ; } // Check if it is an double convertion. else if ( ( ( d . typeFlags & DOUBLE ) != 0 ) && ( Double . TYPE . equals ( c ) || Double . class . equals ( c ) ) ) { return d . doubleValue ; } // Check if it is a string convertion. else if ( ( ( d . typeFlags & STRING ) != 0 ) && String . class . equals ( c ) ) { return d . stringValue ; } // Check if it is an object convertion and th object types match. else if ( ( ( d . typeFlags & OBJECT ) != 0 ) && d . objectValue . getClass ( ) . equals ( c ) ) { return d . objectValue ; } // Throw a class cast exception if the multi data type cannot be converted to the specified class. else { throw new ClassCastException ( "The multi data type, " + d + ", cannot be converted to the class, " + c + "." ) ; } }


Input: For a set of types this method selects the best type to convert a given multi type data object into . This method can be usefull when deciding which of several setter methods on a bean is the best one to convert the multi type data obejct into before calling the beans setter method . [CODESPLIT] public static Class bestMatchingConversion ( MultiTypeData d , Collection < Class > types ) { /*log.fine("public static Class bestMatchingConvertion(MultiTypeData d, Set<Class> types): called");*/ /*log.fine("d = " + d);*/ /*log.fine("types = " + types);*/ // Try to match the native type first before trying the convertions. switch ( d . nativeType ) { case OBJECT : { // Check if the matching Object class can be found in the set of possible classes. if ( types . contains ( d . objectValue . getClass ( ) ) ) { return d . objectValue . getClass ( ) ; } break ; } case BOOLEAN : { // Check if boolean is in the set of possible classes to match. if ( types . contains ( boolean . class ) ) { return boolean . class ; } else if ( types . contains ( Boolean . class ) ) { return Boolean . class ; } break ; } case CHAR : { // Check if char is in the set of possible classes to match. if ( types . contains ( char . class ) ) { return char . class ; } else if ( types . contains ( Character . class ) ) { return Character . class ; } break ; } case BYTE : { // Check if byte is in the set of possible classes to match. if ( types . contains ( byte . class ) ) { return byte . class ; } else if ( types . contains ( Byte . class ) ) { return Byte . class ; } break ; } case SHORT : { // Check if short is in the set of possible classes to match. if ( types . contains ( short . class ) ) { return short . class ; } else if ( types . contains ( Short . class ) ) { return Short . class ; } break ; } case INT : { // Check if int is in the set of possible classes to match. if ( types . contains ( int . class ) ) { return int . class ; } else if ( types . contains ( Integer . class ) ) { return Integer . class ; } break ; } case LONG : { // Check if long is in the set of possible classes to match. if ( types . contains ( long . class ) ) { return long . class ; } else if ( types . contains ( Long . class ) ) { return Long . class ; } break ; } case FLOAT : { // Check if float is in the set of possible classes to match. if ( types . contains ( float . class ) ) { return float . class ; } else if ( types . contains ( Float . class ) ) { return Float . class ; } break ; } case DOUBLE : { // Check if double is in the set of possible classes to match. if ( types . contains ( double . class ) ) { return double . class ; } else if ( types . contains ( Double . class ) ) { return Double . class ; } break ; } case STRING : { // Check if String is in the set of possible classes to match. if ( types . contains ( String . class ) ) { return String . class ; } break ; } default : { throw new IllegalStateException ( "Unknown MultiTypeData type." ) ; } } // Check if the multi type can be converted to a boolean and boolean is in the set of possible convertions. if ( ( ( d . typeFlags & BOOLEAN ) != 0 ) && types . contains ( boolean . class ) ) { return boolean . class ; } else if ( ( ( d . typeFlags & BOOLEAN ) != 0 ) && types . contains ( Boolean . class ) ) { return Boolean . class ; } // Check if the multi type can be converted to a byte and byte is in the set of possible convertions. else if ( ( ( d . typeFlags & BYTE ) != 0 ) && types . contains ( byte . class ) ) { return byte . class ; } else if ( ( ( d . typeFlags & BYTE ) != 0 ) && types . contains ( Byte . class ) ) { return Byte . class ; } // Check if the multi type can be converted to a char and char is in the set of possible convertions. else if ( ( ( d . typeFlags & CHAR ) != 0 ) && types . contains ( char . class ) ) { return char . class ; } else if ( ( ( d . typeFlags & CHAR ) != 0 ) && types . contains ( Character . class ) ) { return Character . class ; } // Check if the multi type can be converted to a short and short is in the set of possible convertions. else if ( ( ( d . typeFlags & SHORT ) != 0 ) && types . contains ( short . class ) ) { return short . class ; } else if ( ( ( d . typeFlags & SHORT ) != 0 ) && types . contains ( Short . class ) ) { return Short . class ; } // Check if the multi type can be converted to a int and int is in the set of possible convertions. else if ( ( ( d . typeFlags & INT ) != 0 ) && types . contains ( int . class ) ) { return int . class ; } else if ( ( ( d . typeFlags & INT ) != 0 ) && types . contains ( Integer . class ) ) { return Integer . class ; } // Check if the multi type can be converted to a long and long is in the set of possible convertions. else if ( ( ( d . typeFlags & LONG ) != 0 ) && types . contains ( long . class ) ) { return long . class ; } else if ( ( ( d . typeFlags & LONG ) != 0 ) && types . contains ( Long . class ) ) { return Long . class ; } // Check if the multi type can be converted to a float and float is in the set of possible convertions. else if ( ( ( d . typeFlags & FLOAT ) != 0 ) && types . contains ( float . class ) ) { return float . class ; } else if ( ( ( d . typeFlags & FLOAT ) != 0 ) && types . contains ( Float . class ) ) { return Float . class ; } // Check if the multi type can be converted to a double and double is in the set of possible convertions. else if ( ( ( d . typeFlags & DOUBLE ) != 0 ) && types . contains ( double . class ) ) { return double . class ; } else if ( ( ( d . typeFlags & DOUBLE ) != 0 ) && types . contains ( Double . class ) ) { return Double . class ; } // Check if the multi type can be converted to a String and String is in the set of possible convertions. else if ( ( ( d . typeFlags & STRING ) != 0 ) && types . contains ( String . class ) ) { return String . class ; } // No matching type convertion found so return null. else { return null ; } }


Input: Inserts an object into the scope . [CODESPLIT] public void put ( String name , Object value ) { pageContext . setAttribute ( name , value , scope ) ; }


Input: Checks is the specified dimension is equivalent . Equivalent means same informations ( including type ) same defaults same links [CODESPLIT] public boolean isEquivalent ( DimensionTable otherDim , Collection < Error > errors ) { if ( this . informationNameToColumn . size ( ) != otherDim . informationNameToColumn . size ( ) ) { errors . add ( new Error ( "[" + this . getDimensionName ( ) + "-" + otherDim . getDimensionName ( ) + "] - Not the same number of informations." ) ) ; return false ; } for ( Entry < String , AbstractSqlColumn > entry : this . informationNameToColumn . entrySet ( ) ) { AbstractSqlColumn otherCol = otherDim . informationNameToColumn . get ( entry . getKey ( ) ) ; if ( otherCol == null ) { errors . add ( new Error ( "[" + this . getDimensionName ( ) + "-" + otherDim . getDimensionName ( ) + "] - Information named " + entry . getKey ( ) + " not found in " + otherDim . getDimensionName ( ) + "." ) ) ; return false ; } if ( ! otherCol . getBusinessName ( ) . equals ( entry . getValue ( ) . getBusinessName ( ) ) ) { errors . add ( new Error ( "[" + this . getDimensionName ( ) + "-" + otherDim . getDimensionName ( ) + "] - Information named " + entry . getKey ( ) + " have not the same name." ) ) ; return false ; } if ( otherCol . getColumnType ( ) != entry . getValue ( ) . getColumnType ( ) ) { errors . add ( new Error ( "[" + this . getDimensionName ( ) + "-" + otherDim . getDimensionName ( ) + "] - Information named " + entry . getKey ( ) + " are not the same type." ) ) ; return false ; } } if ( ! otherDim . getDefaultSearchColumn ( ) . getBusinessName ( ) . equals ( this . getDefaultSearchColumn ( ) . getBusinessName ( ) ) ) { errors . add ( new Error ( "[" + this . getDimensionName ( ) + "-" + otherDim . getDimensionName ( ) + "] - \"default search\" are not the same." ) ) ; return false ; } if ( ! otherDim . getDefaultGroupByColumn ( ) . getBusinessName ( ) . equals ( this . getDefaultGroupByColumn ( ) . getBusinessName ( ) ) ) { errors . add ( new Error ( "[" + this . getDimensionName ( ) + "-" + otherDim . getDimensionName ( ) + "] - \"default group by\" are not the same." ) ) ; return false ; } if ( ! otherDim . getLinkedTables ( ) . equals ( this . getLinkedTables ( ) ) ) { errors . add ( new Error ( "[" + this . getDimensionName ( ) + "-" + otherDim . getDimensionName ( ) + "] - Have not the same linked tables." ) ) ; return false ; } return true ; }


Input: { [CODESPLIT] protected void enterFunctor ( Functor functor ) { String head = traverser . isInHead ( ) ? "/head" : "" ; String last = traverser . isLastBodyFunctor ( ) ? "/last" : "" ; String symKey = functor . getSymbolKey ( ) . toString ( ) ; if ( traverser . isTopLevel ( ) ) { addLineToRow ( "functor(" + symKey + ")" + head + last ) ; } else { addLineToRow ( "arg(" + symKey + ")" ) ; } nextRow ( ) ; }


Input: { [CODESPLIT] protected void enterVariable ( Variable variable ) { Integer allocation = ( Integer ) symbolTable . get ( variable . getSymbolKey ( ) , "allocation" ) ; String symKey = variable . getSymbolKey ( ) . toString ( ) ; String allocString = "" ; if ( allocation != null ) { int slot = ( allocation & ( 0xff ) ) ; int mode = allocation >> 8 ; allocString = ( ( mode == STACK_ADDR ) ? "Y" : "X" ) + slot ; } addLineToRow ( "arg/var(" + symKey + ") " + allocString ) ; nextRow ( ) ; }


Input: { @inheritDoc } [CODESPLIT] public boolean containsKey ( Object objectKey ) { int key = ( Integer ) objectKey ; return keyInRange ( key ) && ( data [ offset ( key ) ] != null ) ; }


Input: { @inheritDoc } [CODESPLIT] public V get ( Object objectKey ) { int key = ( Integer ) objectKey ; if ( keyInRange ( key ) ) { return ( V ) data [ offset ( key ) ] ; } return null ; }


Input: { [CODESPLIT] public V put ( Integer key , V value ) { if ( keyTooLarge ( key ) ) { expand ( key ) ; } int offset = offset ( key ) ; V oldValue = ( V ) data [ offset ] ; data [ offset ] = value ; // If the key is beyond the current end of the array, then move the end up. if ( key >= end ) { end = key + 1 ; } // Increment the count only if a new value was inserted. if ( oldValue == null ) { count ++ ; } return oldValue ; }


Input: Clears entries up to and including the specified key from the map . This is a simple garbage collection operation to clear consumed data from the circular buffer . [CODESPLIT] public void clearUpTo ( int key ) { if ( ( ( start <= key ) && ( key < ( end - 1 ) ) ) ) { // Loop from the start of the data, up to the key to clear up to, clearing all data encountered in-between. int newStart ; for ( newStart = start ; ( newStart <= end ) && ( newStart <= key ) ; newStart ++ ) { int offset = offset ( newStart ) ; if ( data [ offset ] != null ) { data [ offset ] = null ; count -- ; } } // Continue on after the clear up to point, until the first non-null entry or end of array is encountered, // and make that the new start. for ( ; newStart <= end ; newStart ++ ) { if ( data [ offset ( newStart ) ] != null ) { break ; } } start = newStart ; } else { // The key does not lie between the start and end markers, so clear the entire map up to the end int newStart ; for ( newStart = start ; ( newStart <= end ) ; newStart ++ ) { int offset = offset ( newStart ) ; if ( data [ offset ] != null ) { data [ offset ] = null ; count -- ; } } start = newStart ; offset = - start ; } }


Input: { [CODESPLIT] public V remove ( Object objectKey ) { int key = ( Integer ) objectKey ; if ( keyInRange ( key ) ) { // Check if the key is the first element in the list, and walk forward to find the next non-empty element // in order to advance the start to. if ( key == start ) { int newStart = start + 1 ; while ( ( data [ offset ( newStart ) ] == null ) && ( newStart <= end ) ) { newStart ++ ; } start = newStart ; } int offset = offset ( key ) ; V result = ( V ) data [ offset ] ; data [ offset ] = null ; // Decrement the count only if a value was removed. if ( result != null ) { count -- ; } return result ; } return null ; }


Input: { [CODESPLIT] public void clear ( ) { data = new Object [ data . length ] ; length = data . length ; lowMark = - 1 ; start = 0 ; end = 0 ; count = 0 ; offset = 0 ; }


Input: { [CODESPLIT] public Iterator < V > iterator ( ) { return new Iterator < V > ( ) { /** Holds the current offset into the data. */ int current = start ; /** {@inheritDoc} */ public boolean hasNext ( ) { return current < end ; } /** {@inheritDoc} */ public V next ( ) { return ( V ) data [ current ++ ] ; } /** {@inheritDoc} */ public void remove ( ) { throw new UnsupportedOperationException ( "'remove' not supported on this iterator." ) ; } } ; }


Input: 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 . [CODESPLIT] private void expand ( int key ) { // 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 ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Override public void setValue ( String value ) { checkArgument ( ! UNCHECKED_VALUE . equals ( value ) , "Cannot uncheck radio control" ) ; super . setValue ( value ) ; }


Input: { [CODESPLIT] public void insert ( String string , int c , int r ) { for ( char character : string . toCharArray ( ) ) { internalInsert ( character , c ++ , r ) ; } updateListeners ( ) ; }


Input: { [CODESPLIT] public char getCharAt ( int c , int r ) { Character character = data . get ( ( long ) c , ( long ) r ) ; if ( character == null ) { return ' ' ; } else { return character ; } }


Input: { [CODESPLIT] public TextGridModel createInnerGrid ( int c , int r , int w , int h ) { return new NestedTextGridImpl ( c , r , w , h , this ) ; }


Input: { [CODESPLIT] public TextTableModel createTable ( int c , int r , int w , int h ) { // 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 ; }


Input: Notifies all interested listeners of an update to this model . [CODESPLIT] protected void updateListeners ( ) { TextGridEvent event = new TextGridEvent ( this ) ; for ( TextGridListener listener : listeners ) { listener . changedUpdate ( event ) ; } }


Input: 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 . [CODESPLIT] private void internalInsert ( char character , int c , int r ) { maxColumn = ( c > maxColumn ) ? c : maxColumn ; maxRow = ( r > maxRow ) ? r : maxRow ; data . put ( ( long ) c , ( long ) r , character ) ; }


Input: Parses the next sentence from the current token source . [CODESPLIT] public Sentence < Clause > parse ( ) throws SourceCodeException { if ( parser . peekAndConsumeEof ( ) ) { return null ; } else { return new SentenceImpl < Clause > ( parser . sentence ( ) ) ; } }


Input: { [CODESPLIT] public boolean proofStep ( ResolutionState state ) { 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 ; }


Input: Compares two search nodes by their path cost . [CODESPLIT] public int compare ( SearchNode object1 , SearchNode object2 ) { float cost1 = object1 . getPathCost ( ) ; float cost2 = object2 . getPathCost ( ) ; return ( cost1 > cost2 ) ? 1 : ( ( cost1 < cost2 ) ? - 1 : 0 ) ; }


Input: { [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof IntegerTypeVisitor ) { ( ( IntegerTypeVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }


Input: 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 . [CODESPLIT] public Term parseOperators ( Term [ ] terms ) throws SourceCodeException { // 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 ( ) ; }


Input: 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 . [CODESPLIT] public void setOperator ( int name , String textName , int priority , OpSymbol . Associativity associativity ) { // 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 ) ; } } }


Input: Checks the operator table for all possible operators matching a given name . [CODESPLIT] public EnumMap < OpSymbol . Fixity , OpSymbol > getOperatorsMatchingNameByFixity ( String name ) { return operators . get ( name ) ; }


Input: 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 . [CODESPLIT] protected static OpSymbol checkAndResolveToFixity ( CandidateOpSymbol candidate , OpSymbol . Fixity ... fixities ) throws SourceCodeException { 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 ; }


Input: 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 . [CODESPLIT] public int expandSuccessors ( Queue < SearchNode < O , T > > expandInto , boolean reverse ) throws SearchNotExhaustiveException { // 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 ; }


Input: Makes a new node of the same type as this one from a Successor state . [CODESPLIT] public SearchNode < O , T > makeNode ( Successor successor ) throws SearchNotExhaustiveException { 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 ) ; } }


Input: Writes the specified byte <code > b< / code > to this output stream . [CODESPLIT] public void write ( int b ) throws IOException { try { sink . write ( b ) ; } catch ( RemoteException e ) { throw new IOException ( "There was a Remote Exception." , e ) ; } }


Input: 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 . [CODESPLIT] public void write ( byte [ ] b , int off , int len ) throws IOException { try { sink . write ( b , off , len ) ; } catch ( RemoteException e ) { throw new IOException ( "There was a Remote Exception." , e ) ; } }


Input: 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 . [CODESPLIT] public static String rightPad ( String stringToPad , String padder , int size ) { 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 ( ) ; }


Input: Lists all the parsing errors from the most recent parsing in a string . [CODESPLIT] public String getErrors ( ) { // 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 ; }


Input: Lists the properties set from the most recent parsing or an empty string if no parsing has been done yet . [CODESPLIT] public String getOptionsInForce ( ) { // 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 ; }


Input: Generates a usage string consisting of the name of each option and each options argument description and comment . [CODESPLIT] public String getUsage ( ) { 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 ; }


Input: 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 . [CODESPLIT] public Properties parseCommandLine ( String [ ] args ) throws IllegalArgumentException { 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 ; }


Input: 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 . [CODESPLIT] public void addTrailingPairsToProperties ( Properties properties ) { if ( trailingProperties != null ) { for ( Object propKey : trailingProperties . keySet ( ) ) { String name = ( String ) propKey ; String value = trailingProperties . getProperty ( name ) ; properties . setProperty ( name , value ) ; } } }


Input: If a command line has been parsed calling this method sets all of its options that were set to the specified properties . [CODESPLIT] public void addOptionsToProperties ( Properties properties ) { 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 ) ; } } } }


Input: Adds the option to list of available command line options . [CODESPLIT] protected void addOption ( String option , String comment , String argument , boolean mandatory , String formatRegexp ) { // 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 ) ; }


Input: 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 . [CODESPLIT] private Properties takeFreeArgsAsProperties ( Properties properties , int from ) { 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 ; }


Input: 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 . [CODESPLIT] private void checkArgumentFormat ( CommandLineOption optionInfo , CharSequence matchedArg ) { // 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" ) ; } } }


Input: Walks down two iterators comparing them element by element using the equals method . [CODESPLIT] public static < T , U > String compareIterators ( Iterator < U > iterator , Iterator < T > expectedIterator , Function < U , T > mapping ) { 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 ; }


Input: Returns an enumeration describing the available options . [CODESPLIT] public Enumeration listOptions ( ) { 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 ( ) ; }


Input: Parses the options . <p / > [CODESPLIT] public void setOptions ( String [ ] options ) throws Exception { String tmpStr ; tmpStr = Utils . getOption ( ' ' , options ) ; if ( tmpStr . length ( ) != 0 ) setStemmer ( new SelectedTag ( tmpStr , TAGS_STEMMERS ) ) ; else setStemmer ( new SelectedTag ( STEMMER_ORENGO , TAGS_STEMMERS ) ) ; tmpStr = Utils . getOption ( ' ' , options ) ; if ( tmpStr . length ( ) != 0 ) setNamedEntities ( new File ( tmpStr ) ) ; else setNamedEntities ( new File ( "." ) ) ; tmpStr = Utils . getOption ( ' ' , options ) ; if ( tmpStr . length ( ) != 0 ) setStopwords ( new File ( tmpStr ) ) ; else setStopwords ( new File ( "." ) ) ; tmpStr = Utils . getOption ( ' ' , options ) ; if ( tmpStr . length ( ) != 0 ) setCache ( Integer . parseInt ( tmpStr ) ) ; else setCache ( 1000 ) ; }


Input: Gets the current settings of the classifier . [CODESPLIT] public String [ ] getOptions ( ) { 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 ( ) ] ) ; }


Input: Sets the stemmer type to use [CODESPLIT] public void setStemmer ( SelectedTag value ) { if ( value . getTags ( ) == TAGS_STEMMERS ) { m_Stemmer = value . getSelectedTag ( ) . getID ( ) ; invalidate ( ) ; } }


Input: Returns the stemmer to use . [CODESPLIT] protected synchronized ptstemmer . Stemmer getActualStemmer ( ) throws PTStemmerException { 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 ; }


Input: Returns the stemmed version of the given word . Word is converted to lower case before stemming . [CODESPLIT] public String stem ( String word ) { String ret = null ; try { ret = getActualStemmer ( ) . getWordStem ( word ) ; } catch ( PTStemmerException e ) { e . printStackTrace ( ) ; } return ret ; }


Input: Runs the stemmer with the given options . [CODESPLIT] public static void main ( String [ ] args ) { try { Stemming . useStemmer ( new PTStemmer ( ) , args ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }


Input: 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 . [CODESPLIT] static NumericType evaluateAsNumeric ( Term numeric ) { // 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 ; }


Input: Creates a new float range type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , float min , float max ) { // 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 ; } } }


Input: Sets the state of the work panel . State must be one of the defined constants : NOT_INITIALIZED READY or NOT_SAVED . [CODESPLIT] public void setState ( String state ) { /*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 ) ) ; } }


Input: Resets the machine to its initial state . This clears any programs from the machine and clears all of its stacks and heaps . [CODESPLIT] public void reset ( ) { // 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 ) ; } }


Input: { [CODESPLIT] public WAMInternalRegisters getInternalRegisters ( ) { return new WAMInternalRegisters ( ip , hp , hbp , sp , up , ep , bp , b0 , trp , writeMode ) ; }


Input: { [CODESPLIT] public WAMMemoryLayout getMemoryLayout ( ) { return new WAMMemoryLayout ( 0 , REG_SIZE , HEAP_BASE , HEAP_SIZE , STACK_BASE , STACK_SIZE , TRAIL_BASE , TRAIL_SIZE , TOP - PDL_SIZE , PDL_SIZE ) ; }


Input: { [CODESPLIT] protected boolean execute ( WAMCallPoint callPoint ) { /*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 ; }