jenkins-htmlunit-core-js-2.6-hudson-1/0000755000175000017500000000000011537630013021571 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/lib/0000755000175000017500000000000011537630012022336 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/MPL-1.1.html0000644000175000017500000006550611314263504023420 0ustar jamespagejamespage00000000000000 Mozilla Public License version 1.1

(Plain text version)

Mozilla Public License Version 1.1

1. Definitions.

1.0.1. "Commercial Use"
means distribution or otherwise making the Covered Code available to a third party.
1.1. "Contributor"
means each entity that creates or contributes to the creation of Modifications.
1.2. "Contributor Version"
means the combination of the Original Code, prior Modifications used by a Contributor, and the Modifications made by that particular Contributor.
1.3. "Covered Code"
means the Original Code or Modifications or the combination of the Original Code and Modifications, in each case including portions thereof.
1.4. "Electronic Distribution Mechanism"
means a mechanism generally accepted in the software development community for the electronic transfer of data.
1.5. "Executable"
means Covered Code in any form other than Source Code.
1.6. "Initial Developer"
means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A.
1.7. "Larger Work"
means a work which combines Covered Code or portions thereof with code not governed by the terms of this License.
1.8. "License"
means this document.
1.8.1. "Licensable"
means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
1.9. "Modifications"

means any addition to or deletion from the substance or structure of either the Original Code or any previous Modifications. When Covered Code is released as a series of files, a Modification is:

  1. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications.
  2. Any new file that contains any part of the Original Code or previous Modifications.
1.10. "Original Code"
means Source Code of computer software code which is described in the Source Code notice required by Exhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License.
1.10.1. "Patent Claims"
means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
1.11. "Source Code"
means the preferred form of the Covered Code for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an Executable, or source code differential comparisons against either the Original Code or another well known, available Covered Code of the Contributor's choice. The Source Code can be in a compressed or archival form, provided the appropriate decompression or de-archiving software is widely available for no charge.
1.12. "You" (or "Your")
means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License or a future version of this License issued under Section 6.1. For legal entities, "You" includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.

2. Source Code License.

2.1. The Initial Developer Grant.

The Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims:

  1. under intellectual property rights (other than patent or trademark) Licensable by Initial Developer to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, and/or as part of a Larger Work; and
  2. under Patents Claims infringed by the making, using or selling of Original Code, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Code (or portions thereof).
  3. the licenses granted in this Section 2.1 (a) and (b) are effective on the date Initial Developer first distributes Original Code under the terms of this License.
  4. Notwithstanding Section 2.1 (b) above, no patent license is granted: 1) for code that You delete from the Original Code; 2) separate from the Original Code; or 3) for infringements caused by: i) the modification of the Original Code or ii) the combination of the Original Code with other software or devices.

2.2. Contributor Grant.

Subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license

  1. under intellectual property rights (other than patent or trademark) Licensable by Contributor, to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof) either on an unmodified basis, with other Modifications, as Covered Code and/or as part of a Larger Work; and
  2. under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: 1) Modifications made by that Contributor (or portions thereof); and 2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
  3. the licenses granted in Sections 2.2 (a) and 2.2 (b) are effective on the date Contributor first makes Commercial Use of the Covered Code.
  4. Notwithstanding Section 2.2 (b) above, no patent license is granted: 1) for any code that Contributor has deleted from the Contributor Version; 2) separate from the Contributor Version; 3) for infringements caused by: i) third party modifications of Contributor Version or ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or 4) under Patent Claims infringed by Covered Code in the absence of Modifications made by that Contributor.

3. Distribution Obligations.

3.1. Application of License.

The Modifications which You create or to which You contribute are governed by the terms of this License, including without limitation Section 2.2. The Source Code version of Covered Code may be distributed only under the terms of this License or a future version of this License released under Section 6.1, and You must include a copy of this License with every copy of the Source Code You distribute. You may not offer or impose any terms on any Source Code version that alters or restricts the applicable version of this License or the recipients' rights hereunder. However, You may include an additional document offering the additional rights described in Section 3.5.

3.2. Availability of Source Code.

Any Modification which You create or to which You contribute must be made available in Source Code form under the terms of this License either on the same media as an Executable version or via an accepted Electronic Distribution Mechanism to anyone to whom you made an Executable version available; and if made available via Electronic Distribution Mechanism, must remain available for at least twelve (12) months after the date it initially became available, or at least six (6) months after a subsequent version of that particular Modification has been made available to such recipients. You are responsible for ensuring that the Source Code version remains available even if the Electronic Distribution Mechanism is maintained by a third party.

3.3. Description of Modifications.

You must cause all Covered Code to which You contribute to contain a file documenting the changes You made to create that Covered Code and the date of any change. You must include a prominent statement that the Modification is derived, directly or indirectly, from Original Code provided by the Initial Developer and including the name of the Initial Developer in (a) the Source Code, and (b) in any notice in an Executable version or related documentation in which You describe the origin or ownership of the Covered Code.

3.4. Intellectual Property Matters

(a) Third Party Claims

If Contributor has knowledge that a license under a third party's intellectual property rights is required to exercise the rights granted by such Contributor under Sections 2.1 or 2.2, Contributor must include a text file with the Source Code distribution titled "LEGAL" which describes the claim and the party making the claim in sufficient detail that a recipient will know whom to contact. If Contributor obtains such knowledge after the Modification is made available as described in Section 3.2, Contributor shall promptly modify the LEGAL file in all copies Contributor makes available thereafter and shall take other steps (such as notifying appropriate mailing lists or newsgroups) reasonably calculated to inform those who received the Covered Code that new knowledge has been obtained.

(b) Contributor APIs

If Contributor's Modifications include an application programming interface and Contributor has knowledge of patent licenses which are reasonably necessary to implement that API, Contributor must also include this information in the legal file.

(c) Representations.

Contributor represents that, except as disclosed pursuant to Section 3.4 (a) above, Contributor believes that Contributor's Modifications are Contributor's original creation(s) and/or Contributor has sufficient rights to grant the rights conveyed by this License.

3.5. Required Notices.

You must duplicate the notice in Exhibit A in each file of the Source Code. If it is not possible to put such notice in a particular Source Code file due to its structure, then You must include such notice in a location (such as a relevant directory) where a user would be likely to look for such a notice. If You created one or more Modification(s) You may add your name as a Contributor to the notice described in Exhibit A. You must also duplicate this License in any documentation for the Source Code where You describe recipients' rights or ownership rights relating to Covered Code. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear than any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.

3.6. Distribution of Executable Versions.

You may distribute Covered Code in Executable form only if the requirements of Sections 3.1, 3.2, 3.3, 3.4 and 3.5 have been met for that Covered Code, and if You include a notice stating that the Source Code version of the Covered Code is available under the terms of this License, including a description of how and where You have fulfilled the obligations of Section 3.2. The notice must be conspicuously included in any notice in an Executable version, related documentation or collateral in which You describe recipients' rights relating to the Covered Code. You may distribute the Executable version of Covered Code or ownership rights under a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable version does not attempt to limit or alter the recipient's rights in the Source Code version from the rights set forth in this License. If You distribute the Executable version under a different license You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or any Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer.

3.7. Larger Works.

You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Code.

4. Inability to Comply Due to Statute or Regulation.

If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Code due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be included in the legal file described in Section 3.4 and must be included with all distributions of the Source Code. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.

5. Application of this License.

This License applies to code to which the Initial Developer has attached the notice in Exhibit A and to related Covered Code.

6. Versions of the License.

6.1. New Versions

Netscape Communications Corporation ("Netscape") may publish revised and/or new versions of the License from time to time. Each version will be given a distinguishing version number.

6.2. Effect of New Versions

Once Covered Code has been published under a particular version of the License, You may always continue to use it under the terms of that version. You may also choose to use such Covered Code under the terms of any subsequent version of the License published by Netscape. No one other than Netscape has the right to modify the terms applicable to Covered Code created under this License.

6.3. Derivative Works

If You create or use a modified version of this License (which you may only do in order to apply it to code which is not already Covered Code governed by this License), You must (a) rename Your license so that the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape", "MPL", "NPL" or any confusingly similar phrase do not appear in your license (except to note that your license differs from this License) and (b) otherwise make it clear that Your version of the license contains terms which differ from the Mozilla Public License and Netscape Public License. (Filling in the name of the Initial Developer, Original Code or Contributor in the notice described in Exhibit A shall not of themselves be deemed to be modifications of this License.)

7. Disclaimer of warranty

Covered code is provided under this license on an "as is" basis, without warranty of any kind, either expressed or implied, including, without limitation, warranties that the covered code is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the covered code is with you. Should any covered code prove defective in any respect, you (not the initial developer or any other contributor) assume the cost of any necessary servicing, repair or correction. This disclaimer of warranty constitutes an essential part of this license. No use of any covered code is authorized hereunder except under this disclaimer.

8. Termination

8.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. All sublicenses to the Covered Code which are properly granted shall survive any termination of this License. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.

8.2. If You initiate litigation by asserting a patent infringement claim (excluding declatory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You file such action is referred to as "Participant") alleging that:

  1. such Participant's Contributor Version directly or indirectly infringes any patent, then any and all rights granted by such Participant to You under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively, unless if within 60 days after receipt of notice You either: (i) agree in writing to pay Participant a mutually agreeable reasonable royalty for Your past and future use of Modifications made by such Participant, or (ii) withdraw Your litigation claim with respect to the Contributor Version against such Participant. If within 60 days of notice, a reasonable royalty and payment arrangement are not mutually agreed upon in writing by the parties or the litigation claim is not withdrawn, the rights granted by Participant to You under Sections 2.1 and/or 2.2 automatically terminate at the expiration of the 60 day notice period specified above.
  2. any software, hardware, or device, other than such Participant's Contributor Version, directly or indirectly infringes any patent, then any rights granted to You by such Participant under Sections 2.1(b) and 2.2(b) are revoked effective as of the date You first made, used, sold, distributed, or had made, Modifications made by that Participant.

8.3. If You assert a patent infringement claim against Participant alleging that such Participant's Contributor Version directly or indirectly infringes any patent where such claim is resolved (such as by license or settlement) prior to the initiation of patent infringement litigation, then the reasonable value of the licenses granted by such Participant under Sections 2.1 or 2.2 shall be taken into account in determining the amount or value of any payment or license.

8.4. In the event of termination under Sections 8.1 or 8.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or any distributor hereunder prior to termination shall survive termination.

9. Limitation of liability

Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall you, the initial developer, any other contributor, or any distributor of covered code, or any supplier of any of such parties, be liable to any person for any indirect, special, incidental, or consequential damages of any character including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to you.

10. U.S. government end users

The Covered Code is a "commercial item," as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer software" and "commercial computer software documentation," as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Code with only those rights set forth herein.

11. Miscellaneous

This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by California law provisions (except to the extent applicable law, if any, provides otherwise), excluding its conflict-of-law provisions. With respect to disputes in which at least one party is a citizen of, or an entity chartered or registered to do business in the United States of America, any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California, with venue lying in Santa Clara County, California, with the losing party responsible for costs, including without limitation, court costs and reasonable attorneys' fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License.

12. Responsibility for claims

As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.

13. Multiple-licensed code

Initial Developer may designate portions of the Covered Code as "Multiple-Licensed". "Multiple-Licensed" means that the Initial Developer permits you to utilize portions of the Covered Code under Your choice of the MPL or the alternative licenses, if any, specified by the Initial Developer in the file described in Exhibit A.

Exhibit A - Mozilla Public License.

"The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.

The Original Code is ______________________________________.

The Initial Developer of the Original Code is ________________________.
Portions created by ______________________ are Copyright (C) ______
_______________________. All Rights Reserved.

Contributor(s): ______________________________________.

Alternatively, the contents of this file may be used under the terms
of the _____ license (the  "[___] License"), in which case the
provisions of [______] License are applicable instead of those
above. If you wish to allow use of your version of this file only
under the terms of the [____] License and not to allow others to use
your version of this file under the MPL, indicate your decision by
deleting the provisions above and replace them with the notice and
other provisions required by the [___] License. If you do not delete
the provisions above, a recipient may use your version of this file
under either the MPL or the [___] License."

NOTE: The text of this Exhibit A may differ slightly from the text of the notices in the Source Code files of the Original Code. You should use the text of this Exhibit A rather than the text found in the Original Code Source Code for Your Modifications. jenkins-htmlunit-core-js-2.6-hudson-1/build.xml0000644000175000017500000001553011537625433023430 0ustar jamespagejamespage00000000000000 jenkins-htmlunit-core-js-2.6-hudson-1/.hgignore0000644000175000017500000000003611314263504023373 0ustar jamespagejamespage00000000000000syntax: glob out target *.iws jenkins-htmlunit-core-js-2.6-hudson-1/Patched.iml0000644000175000017500000000216711314263504023652 0ustar jamespagejamespage00000000000000 jenkins-htmlunit-core-js-2.6-hudson-1/pom.xml0000644000175000017500000000525211537625341023122 0ustar jamespagejamespage00000000000000 4.0.0 org.jvnet.hudson htmlunit-core-js 2.6-hudson-1 jar HtmlUnit Core JS http://htmlunit.sourceforge.net HtmlUnit adaptation of Mozilla Rhino Javascript engine for Java. Changes are documented by a diff (rhinoDiff.txt) contained in the generated jar files. Mozilla Public License version 1.1 http://www.mozilla.org/MPL/MPL-1.1.html repo org.jvnet.maven-antrun-extended-plugin maven-antrun-extended-plugin package run maven-surefire-plugin true org.jvnet.wagon-svn wagon-svn 1.8 java.net-m2-repository java-net:/maven2-repository/trunk/repository/ maven2-repository.dev.java.net Java.net Repository for Maven http://download.java.net/maven/2/ maven2-repository.dev.java.net Java.net Repository for Maven http://download.java.net/maven/2/ jenkins-htmlunit-core-js-2.6-hudson-1/LICENSE.txt0000644000175000017500000000064311314263504023417 0ustar jamespagejamespage00000000000000htmlunit-core-js.jar is a modified version of Mozilla Rhino (http://www.mozilla.org/rhino/) which was initially developed by Netscape Communications Corporation. The changes to the source code are provided in the file rhinoDiff.txt (and can be generated by calling cvs diff in the rhino folder). This software is provided by the HtmlUnit team "as is" under the MPL 1.1 license, available at http://www.mozilla.org/MPLjenkins-htmlunit-core-js-2.6-hudson-1/src/0000755000175000017500000000000011537630013022360 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/src/net/0000755000175000017500000000000011537630013023146 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/0000755000175000017500000000000011537630013025471 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/0000755000175000017500000000000011537630013027335 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/WriteReadOnlyPropertyTest.java0000644000175000017500000000457111314263504035344 0ustar jamespagejamespage00000000000000package net.sourceforge.htmlunit; import java.lang.reflect.Method; import org.junit.Assert; import org.junit.Test; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.EcmaError; import org.mozilla.javascript.ScriptableObject; /** * Test that read-only properties can be... set when needed. * This was the standard behavior in Rhino until 1.7R2 but has changed then. * It is needed to simulate IE as well as FF2 (but not FF3). * @author Marc Guillemot */ public class WriteReadOnlyPropertyTest { /** * @throws Exception if the test fails */ @Test public void testWriteReadOnly_accepted() throws Exception { testWriteReadOnly(true); } /** * @throws Exception if the test fails */ @Test public void testWriteReadOnly_throws() throws Exception { try { testWriteReadOnly(false); Assert.fail(); } catch (EcmaError e) { Assert.assertTrue(e.getMessage(), e.getMessage().contains("Cannot set property myProp that has only a getter")); } } void testWriteReadOnly(final boolean acceptWriteReadOnly) throws Exception { final Method readMethod = Foo.class.getMethod("getMyProp", null); final Foo foo = new Foo("hello"); foo.defineProperty("myProp", null, readMethod, null, ScriptableObject.EMPTY); final String script = "foo.myProp = 123; foo.myProp"; final ContextAction action = new ContextAction() { public Object run(final Context cx) { final ScriptableObject top = cx.initStandardObjects(); ScriptableObject.putProperty(top, "foo", foo); System.out.println(cx.evaluateString(top, script, "script", 0, null)); return null; } }; final ContextFactory contextFactory = new ContextFactory() { @Override protected boolean hasFeature(final Context cx, final int featureIndex) { if (Context.FEATURE_HTMLUNIT_WRITE_READONLY_PROPERTIES == featureIndex) { return acceptWriteReadOnly; } return super.hasFeature(cx, featureIndex); } }; contextFactory.call(action); } /** * Simple utility allowing to better see the concerned scope while debugging */ static class Foo extends ScriptableObject { final String prop_; Foo(final String label) { prop_ = label; } @Override public String getClassName() { return "Foo"; } public String getMyProp() { return prop_; } }; } jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/Utils.java0000644000175000017500000000164711314263504031310 0ustar jamespagejamespage00000000000000package net.sourceforge.htmlunit; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ContextFactory; /** * Misc utilities to make test code easier. * @author Marc Guillemot */ public class Utils { /** * Runs the action successively with all available optimization levels */ public static void runWithAllOptimizationLevels(final ContextAction action) { runWithOptimizationLevel(action, -1); runWithOptimizationLevel(action, 0); runWithOptimizationLevel(action, 1); } /** * Runs the provided action at the given optimization level */ public static void runWithOptimizationLevel(final ContextAction action, final int optimizationLevel) { final Context cx = new ContextFactory().enterContext(); try { cx.setOptimizationLevel(optimizationLevel); action.run(cx); } finally { Context.exit(); } } } jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/RegExpUnescapedSlashTest.java0000644000175000017500000000074411314263504035062 0ustar jamespagejamespage00000000000000package net.sourceforge.htmlunit; import org.junit.Test; /** * Test that regexp like "[/]" are parsed correctly. * https://bugzilla.mozilla.org/show_bug.cgi?id=368019 * (now fixed in Rhino itself) * @author Marc Guillemot */ public class RegExpUnescapedSlashTest { /** * @throws Exception if the test fails */ @Test public void testUnescapedSlashInSquareBrackets() throws Exception { final String script = "var o = /[/]/;"; Utilities.executeScript(script); } } jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/ContextMethodsTest.java0000644000175000017500000000360611314263504034015 0ustar jamespagejamespage00000000000000package net.sourceforge.htmlunit; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.ErrorReporter; import org.mozilla.javascript.Evaluator; import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; /** * Unit tests for Bug 481152 - * Open Context class for extension * @author Marc Guillemot */ public class ContextMethodsTest { /** * When {@link Context#compileString(String, String, int, Object)} is protected and not final, * we can capture code passed to eval. * @throws Exception if the test fails */ @Test public void captureEvalScript() throws Exception { final List compiled = new ArrayList(); final ContextFactory cf = new ContextFactory() { @Override protected Context makeContext() { return new Context(this) { @Override protected Script compileString(String source, Evaluator compiler, ErrorReporter compilationErrorReporter, String sourceName, int lineno, Object securityDomain) { compiled.add(source); return super.compileString(source, compiler, compilationErrorReporter, sourceName, lineno, securityDomain); } }; } }; final String source = "eval('1 + 2')"; final ContextAction action = new ContextAction() { public Object run(Context cx) { final Scriptable scope = cx.initStandardObjects(); final Script script = cx.compileString(source, "", 1, (Object) null); return script.exec(cx, scope); }; }; cf.call(action); final String[] expected = { "eval('1 + 2')", "1 + 2" }; Assert.assertEquals(Arrays.asList(expected), compiled); } } ././@LongLink0000000000000000000000000000015100000000000011212 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/PrimitiveTypeScopeResolutionTest.javajenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/PrimitiveTypeScopeResolutionTest.0000644000175000017500000000502411314263504036067 0ustar jamespagejamespage00000000000000package net.sourceforge.htmlunit; import net.sourceforge.htmlunit.Utils; import org.junit.Test; import org.junit.runner.RunWith; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; /** * Unit tests for Bug 374918 - * String primitive prototype wrongly resolved when used with many top scopes * @author Marc Guillemot */ @RunWith(RhinoPatchedRunner.class) public class PrimitiveTypeScopeResolutionTest { /** */ @Test public void functionCall() { String str2 = "function f() { String.prototype.foo = function() { return 'from 2' }; \n" + "var s2 = 's2';\n" + "var s2Foo = s2.foo();\n" + "if (s2Foo != 'from 2') throw 's2 got: ' + s2Foo;\n" // fails + "}"; String str1 = "String.prototype.foo = function() { return 'from 1'}; scope2.f()"; testWithTwoScopes(str1, str2); } /** */ @Test public void propertyAccess() { String str2 = "function f() { String.prototype.foo = 'from 2'; \n" + "var s2 = 's2';\n" + "var s2Foo = s2.foo;\n" + "if (s2Foo != 'from 2') throw 's2 got: ' + s2Foo;\n" // fails + "}"; String str1 = "String.prototype.foo = 'from 1'; scope2.f()"; testWithTwoScopes(str1, str2); } private void testWithTwoScopes(final String scriptScope1, final String scriptScope2) { final ContextAction action = new ContextAction() { public Object run(final Context cx) { final Scriptable scope1 = cx.initStandardObjects(new MySimpleScriptableObject("scope1")); final Scriptable scope2 = cx.initStandardObjects(new MySimpleScriptableObject("scope2")); cx.evaluateString(scope2, scriptScope2, "source2", 1, null); scope1.put("scope2", scope1, scope2); return cx.evaluateString(scope1, scriptScope1, "source1", 1, null); } }; Utils.runWithAllOptimizationLevels(action); } /** * Simple utility allowing to better see the concerned scope while debugging */ static class MySimpleScriptableObject extends ScriptableObject { private String label_; MySimpleScriptableObject(String label) { label_ = label; } @Override public String getClassName() { return "MySimpleScriptableObject"; } @Override public String toString() { return label_; } }; } jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/PropertiesOrderTest.java0000644000175000017500000000134511314263504034173 0ustar jamespagejamespage00000000000000package net.sourceforge.htmlunit; import org.junit.Test; /** * Test that Object properties are returned in the creation order. * (now fixed in Rhino itself) * @author Marc Guillemot */ public class PropertiesOrderTest { /** * Test for properties order as exposed in issues * https://bugzilla.mozilla.org/show_bug.cgi?id=419090 * and * https://bugzilla.mozilla.org/show_bug.cgi?id=383592 * @throws Exception if the test fails */ @Test public void testPropertiesOrder() throws Exception { final String script = "var o = {a: 1, b: 1, c: 1, d: 1};\n" + "var str = '';\n" + "for (var i in o) str += i + ' ';\n" + "if (str != 'a b c d ')\n" + " throw 'Got: ' + str"; Utilities.executeScript(script); } } jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/ArrayConcatTest.java0000644000175000017500000000111111314263504033240 0ustar jamespagejamespage00000000000000package net.sourceforge.htmlunit; import org.junit.Test; /** * Unit tests for Bug 477604 - * Array.concat causes ArrayIndexOutOfBoundException with non dense array * @author Marc Guillemot */ public class ArrayConcatTest { /** * @throws Exception if the test fails */ @Test public void concat() throws Exception { final String script = "var a = [1, 2, 3];\n" + "for (var i=10; i<20; ++i) a[i] = 't' + i;\n" + "var b = [1, 2, 3];\n" + "b.concat(a)"; Utilities.executeScript(script); } } jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/Utilities.java0000644000175000017500000000126411314263504032156 0ustar jamespagejamespage00000000000000package net.sourceforge.htmlunit; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Scriptable; /** * Misc utilities. * @author Marc Guillemot */ public class Utilities { /** * Execute the provided script in a fresh context * @param script the script */ static void executeScript(final String script) { final ContextAction action = new ContextAction() { public Object run(Context cx) { final Scriptable scope = cx.initStandardObjects(); return cx.evaluateString(scope, script, "test", 0, null); } }; ContextFactory.getGlobal().call(action); } } jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/RhinoPatchedRunner.java0000644000175000017500000000230511314263504033742 0ustar jamespagejamespage00000000000000package net.sourceforge.htmlunit; import java.lang.reflect.Method; import org.junit.internal.runners.InitializationError; import org.junit.internal.runners.JUnit4ClassRunner; import org.junit.internal.runners.TestMethod; /** * Runs the unit test, expecting them to fail when run with unpatched Rhino version * (in fact when system property {@link #PROPERTY_RHINO} is set to {@link #PROPERTY_RHINO_VALUE_ORIGINAL}). * @author Marc Guillemot */ public class RhinoPatchedRunner extends JUnit4ClassRunner { private boolean runWithOriginalRhino; public static final String PROPERTY_RHINO = "rhino"; public static final String PROPERTY_RHINO_VALUE_ORIGINAL = "original"; public RhinoPatchedRunner(final Class klass) throws InitializationError { super(klass); runWithOriginalRhino = PROPERTY_RHINO_VALUE_ORIGINAL.equalsIgnoreCase(System.getProperty(PROPERTY_RHINO)); } @Override protected TestMethod wrapMethod(final Method method) { if (runWithOriginalRhino) { return new TestMethod(method, getTestClass()) { @Override protected Class getExpectedException() { return Throwable.class; } }; } else { return super.wrapMethod(method); } } } jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/UpperCaseHexTest.java0000644000175000017500000000106111314263504033372 0ustar jamespagejamespage00000000000000package net.sourceforge.htmlunit; import org.junit.Test; /** * Test that encodeURIComponent uses upper case letters for hex encoding. * https://bugzilla.mozilla.org/show_bug.cgi?id=429121 * (now fixed in Rhino itself) * @author Marc Guillemot */ public class UpperCaseHexTest { /** * @throws Exception if the test fails */ @Test public void testUpperCaseHex() throws Exception { final String script = "var a = encodeURIComponent('$ a ;');\n" + "if (a != '%24%20a%20%3B') throw 'got: >' + a + '<'"; Utilities.executeScript(script); } } jenkins-htmlunit-core-js-2.6-hudson-1/src/net/sourceforge/htmlunit/StackTraceTest.java0000644000175000017500000000317511314263504033072 0ustar jamespagejamespage00000000000000package net.sourceforge.htmlunit; import org.junit.Assert; import org.junit.Test; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.Scriptable; /** * In certain cases stacktrace if lost in case of exception * https://bugzilla.mozilla.org/show_bug.cgi?id=376717 * @author Marc Guillemot */ public class StackTraceTest { /** * As of CVS head on May, 11. 2009, stacktrace information is lost when a call to some * native function has been made. */ @Test public void testFailureStackTrace() { final String source1 = "function f2() { throw 'hello'; }; f2();"; final String source2 = "function f2() { 'H'.toLowerCase(); throw 'hello'; }; f2();"; runWithExpectedStackTrace(source1, " at test.js (f2)\n\tat test.js\n"); // works runWithExpectedStackTrace(source2, " at test.js (f2)\n\tat test.js\n"); // fails } private void runWithExpectedStackTrace(final String _source, final String _expectedStackTrace) { final ContextAction action = new ContextAction() { public Object run(final Context cx) { final Scriptable scope = cx.initStandardObjects(); try { cx.evaluateString(scope, _source, "test.js", 0, null); } catch (final JavaScriptException e) { Assert.assertEquals(_expectedStackTrace, e.getScriptStackTrace()); return null; } throw new RuntimeException("Exception expected!"); } }; Utils.runWithOptimizationLevel(action, -1); } } jenkins-htmlunit-core-js-2.6-hudson-1/core-js.ipr0000644000175000017500000004405711314263504023661 0ustar jamespagejamespage00000000000000 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/0000755000175000017500000000000011537630013022710 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/README.html0000644000175000017500000000356211314263504024541 0ustar jamespagejamespage00000000000000

Rhino: JavaScript in Java

Rhino is an implementation of JavaScript in Java. Documentation can be found here. jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/0000755000175000017500000000000011537630013024377 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/0000755000175000017500000000000011537630013026227 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/util.js0000644000175000017500000000026611314263504027546 0ustar jamespagejamespage00000000000000function expectTypeError(code) { try { code(); throw (code.toSource() + ' should have thrown a TypeError'); } catch (e if e instanceof TypeError) { // all good } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/368019.doctest0000644000175000017500000000033111314263504030365 0ustar jamespagejamespage00000000000000// Regression test for bug https://bugzilla.mozilla.org/show_bug.cgi?id=368019 // - regular expression (regex) parses /[/]/ incorrectly js> var re; js> re = /[^/]*/; /[^/]*/ js> re = /[/]/; /[/]/ js> re = /\[/; /\[/ jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.isfrozen.doctest0000644000175000017500000000204611314263504032724 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.isFrozen function isFrozen() { [native code for Object.isFrozen, arity=1] } js> expectTypeError(function() { Object.isFrozen() }); js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.isFrozen(value) }) > }) js> Object.isFrozen({}) false js> var obj = Object.preventExtensions({}); js> Object.isFrozen(obj); true js> var obj = Object.defineProperty({}, 'a', {configurable:true, writable:false}) js> var _ = Object.preventExtensions(obj); js> Object.isFrozen(obj); false js> var obj = Object.defineProperty({}, 'a', {configurable:false, writable:true}) js> var _ = Object.preventExtensions(obj); js> Object.isFrozen(obj); false js> var obj = Object.defineProperty({}, 'a', {configurable:false, writable:false}) js> var _ = Object.preventExtensions(obj); js> Object.isFrozen(obj); true js> var obj = Object.defineProperty({}, 'a', {configurable:false, set: function(){} }) js> var _ = Object.preventExtensions(obj); js> Object.isFrozen(obj); true jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.create.doctest0000644000175000017500000000157111314263504032332 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.create; function create() { [native code for Object.create, arity=2] } js> expectTypeError(function() { Object.create() }); js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.create(value) }) > }) js> expectTypeError(function() { Object.create({}, null) }) js> var obj = Object.create({}); js> var obj = Object.create({}, {}); js> var obj = Object.create({}, undefined); js> var orig = {} js> var next = Object.create(orig); js> Object.getPrototypeOf(next) === orig; true js> var obj = Object.create({}, {a: {value:1}, b: {value:2}}); js> [obj.a, obj.b].toSource(); [1, 2] js> var orig = {a:1}; js> var obj = Object.create(orig, {a:{value:2}, b:{value:3}}); js> [obj.a, obj.b].toSource() [2, 3] js> expectTypeError(function() { Object.create({}, {b: {value:1}, c:1}) }); jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/441417.doctest0000644000175000017500000000115111314263504030360 0ustar jamespagejamespage00000000000000js> var friendInfo = xmlns="http://ode.apache.org/simpel/1.0/definition/XmlData"> xmlns=""/>; js> var msgIn = xmlns:xd="http://ode.apache.org/simpel/1.0/definition/XmlData"> > > John > Doe > (999)999-9999 > > ; js> friendInfo.name = msgIn.person.firstName.text() + " " + > msgIn.person.lastName.text(); John Doe jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/434041.doctest0000644000175000017500000000042511314263504030356 0ustar jamespagejamespage00000000000000// Regression test for bug https://bugzilla.mozilla.org/show_bug.cgi?id=434041 js> function add(_object, _key, _value) { > _object[_key] = _value; > } js> var o = {}; js> add(o, 'a', 'b'); js> o.toSource(); ({a:"b"}) js> add(o, 3, 'c'); js> o.toSource(); ({a:"b", 3:"c"})jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/467396.doctest0000755000175000017500000000046011314263504030403 0ustar jamespagejamespage00000000000000js> var a = java.lang.reflect.Array.newInstance(java.lang.Integer, [17,4]); js> a [[Ljava.lang.Integer;@1543c88 js> a.length 17 js> a[0].length 4 js> var a = java.lang.reflect.Array.newInstance(java.lang.Integer, 17, 4); js> a [[Ljava.lang.Integer;@f11404 js> a.length 17 js> a[0].length 4 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/iteratorKeys.doctest0000755000175000017500000000033311314263504032305 0ustar jamespagejamespage00000000000000js> version(170) 0 js> var foo = { > __iterator__ : function(onlyKeys) { > print(onlyKeys); > yield [0, "a"]; > } > }; js> for each (let f in foo) {} false js> for (let f in foo) {} truejenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/477233.doctest0000644000175000017500000000066411314263504030375 0ustar jamespagejamespage00000000000000js> var xml = > > One > > > Two > > ; js> var atom = new Namespace("http://www.w3.org/2005/Atom"); js> print(xml.atom::entry.(atom::title == "One")); One jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/iterable.doctest0000644000175000017500000000053211314263504031405 0ustar jamespagejamespage00000000000000// Test of Creating a JavaScript Iterator from a Java Iterable or Iterator // See http://developer.mozilla.org/en/docs/New_in_Rhino_1.7R1 js> m = new java.util.LinkedHashMap() {} js> m.put("a",1); m.put("b",2); m {a=1.0, b=2.0} js> for (i in Iterator(m.values())) print(i) 1.0 2.0 js> for (i in Iterator(m.values().iterator())) print(i) 1.0 2.0 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/serialize.doctest0000644000175000017500000000043711314263504031611 0ustar jamespagejamespage00000000000000js> var obj = { a:3, b:"hi", 9:"nine", 12:1200 }; js> serialize(obj, "foo.bin"); js> obj2 = deserialize("foo.bin"); [object Object] js> uneval(obj) ({a:3, b:"hi", 9:"nine", 12:1200}) js> uneval(obj2) ({a:3, b:"hi", 9:"nine", 12:1200}) js> (new java.io.File("foo.bin"))["delete"](); true jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.extensible.doctest0000644000175000017500000000157411314263504033234 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.isExtensible; function isExtensible() { [native code for Object.isExtensible, arity=1] } js> expectTypeError(function() { Object.isExtensible() }); js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.isExtensible(value) }) > }) js> Object.preventExtensions; function preventExtensions() { [native code for Object.preventExtensions, arity=1] } js> expectTypeError(function() { Object.preventExtensions() }); js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.preventExtensions(value) }) > }) js> var x = {}; js> Object.isExtensible(x); true js> var y = Object.preventExtensions(x); js> y === x; true js> Object.isExtensible(x); false js> x.a = 1; x.a js> js> x.__defineGetter__('b', function() { return 1 }); x.b js> jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/Matrix.doctest0000644000175000017500000000106211314263504031061 0ustar jamespagejamespage00000000000000Test of Matrix example. js> defineClass("Matrix") js> var m = new Matrix(2); // A constructor call, see "Matrix(int dimension)" js> m // Object.toString will call "Matrix.getClassName()" [object Matrix] js> m[0][0] = 3; 3 js> uneval(m[0]); // an array was created automatically! [3] js> uneval(m[1]); // array is created even if we don't set a value [] js> m.dim; // we can access the "dim" property 2 js> m.dim = 3; 3 js> m.dim; // but not modify the "dim" property 2 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/429121.doctest0000644000175000017500000000005611314263504030361 0ustar jamespagejamespage00000000000000js> encodeURIComponent('$ a ;') %24%20a%20%3B jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.freeze.doctest0000644000175000017500000000121211314263504032337 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.freeze; function freeze() { [native code for Object.freeze, arity=1] } js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.freeze(value) }) > }) js> expectTypeError(function() { Object.freeze() }) js> var x = {} js> var y = Object.freeze(x) js> x === y true js> var obj = Object.defineProperty({}, 'a', {configurable:true, writable:true}) js> var _ = Object.freeze(obj) js> var a = Object.getOwnPropertyDescriptor(obj, 'a'); js> a.configurable false js> a.writable false js> Object.isExtensible(obj) false js> Object.isFrozen(obj) true jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/433878.doctest0000644000175000017500000000054611314263504030403 0ustar jamespagejamespage00000000000000js> version(170) 0 js> function f(a,b,c) { > let sum = a + b + c; > return sum / 3; > } js> f.toString() function f(a, b, c) { let sum = a + b + c; return sum / 3; } js> try { > eval("function f() { for (;;) let a=3; return 3; }"); > } catch (e) { > e; > } SyntaxError: SyntaxError: let declaration not directly within block jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/canonicalize.doctest0000644000175000017500000000052411314263504032256 0ustar jamespagejamespage00000000000000js> var obj = new java.lang.Object(); js> obj java.lang.Object@97a560 js> obj + "%%" java.lang.Object@97a560%% js> var obj = new java.lang.Object(); js> obj java.lang.Object@1d15445 js> "foo" + obj + "bar" foojava.lang.Object@1d15445bar js> var obj2 = new java.lang.Object(); js> obj + obj2 java.lang.Object@1d15445java.lang.Object@1f3aa07 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.getownpropertynames.doctest0000644000175000017500000000302511314263504035217 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.getOwnPropertyNames; function getOwnPropertyNames() { [native code for Object.getOwnPropertyNames, arity=1] } js> expectTypeError(function() { Object.getOwnPropertyNames() }) js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.getOwnPropertyNames(value) }) > }) js> Object.getOwnPropertyNames({}).toSource(); [] js> Object.getOwnPropertyNames({a:2}).toSource(); ["a"] js> Object.getOwnPropertyNames({a:1, b:2}).toSource(); ["a", "b"] js> Object.getOwnPropertyNames({'a.b':1, 'c d':2}).toSource(); ["a.b", "c d"] js> Object.getOwnPropertyNames([]).toSource(); ["length"] js> Object.getOwnPropertyNames(['a', 'b', 'c']).toSource(); ["0", "1", "2", "length"] js> function UserDefined() { this.a = 1; this.b = 2 }; js> var obj = new UserDefined() js> Object.getOwnPropertyNames(obj).toSource() ["a", "b"] js> UserDefined.prototype.c = 3; 3 js> Object.getOwnPropertyNames(obj).toSource() ["a", "b"] js> // test properties of result are enumerable js> for (var p in Object.getOwnPropertyNames({a:2, b:3})) print(p) 0 1 js> // test that properties of result are writable js> var k = Object.getOwnPropertyNames({a:2, b:3}); js> k[1] = 'c'; k.toSource(); ["a", "c"] js> // test that properties of result are configurable js> var k = Object.getOwnPropertyNames({a:2, b:3}) js> delete k[1]; true js> k a, js> // TODO test that the attributes of the properties can be changed js> var k = Object.getOwnPropertyNames({a:2, 5:6}) js> typeof k[1] string jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.keys.doctest0000644000175000017500000000241011314263504032033 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.keys; function keys() { [native code for Object.keys, arity=1] } js> expectTypeError(function() { Object.keys() }) js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.keys(value) }) > }) js> Object.keys({}).toSource(); [] js> Object.keys({a:2}).toSource(); ["a"] js> Object.keys({a:1, b:2}).toSource(); ["a", "b"] js> Object.keys({'a.b':1, 'c d':2}).toSource(); ["a.b", "c d"] js> Object.keys([]).toSource(); [] js> Object.keys(['a', 'b', 'c']).toSource(); ["0", "1", "2"] js> function UserDefined() { this.a = 1; this.b = 2 }; js> var obj = new UserDefined() js> Object.keys(obj).toSource() ["a", "b"] js> UserDefined.prototype.c = 3; 3 js> Object.keys(obj).toSource() ["a", "b"] js> // test properties of result are enumerable js> for (var p in Object.keys({a:2, b:3})) print(p) 0 1 js> // test that properties of result are writable js> var k = Object.keys({a:2, b:3}); js> k[1] = 'c'; k.toSource(); ["a", "c"] js> // test that properties of result are configurable js> var k = Object.keys({a:2, b:3}) js> delete k[1]; true js> k a, js> // TODO test that the attributes of the properties can be changed js> var k = Object.keys({ a:1, 3:2 }); js> typeof k[1]; string jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/393794.doctest0000644000175000017500000000011011314263504030370 0ustar jamespagejamespage00000000000000js> var x = { foo: "bar" } js> var y = { __proto__: x }; js> y.foo; bar jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/439530.doctest0000644000175000017500000000014411314263504030364 0ustar jamespagejamespage00000000000000js> var obj = { run: function () { print("\nrunning"); } } js> var r = new java.lang.Runnable(obj); jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/473761.doctest0000644000175000017500000000033511314263504030372 0ustar jamespagejamespage00000000000000js> var xml = ; js> var order = xml.customer.order; js> order.orderid = "1"; 1 js> order.test = "expected_string"; expected_string js> xml.customer.order.test; expected_string jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/xmlOptions.doctest0000755000175000017500000000050611314263504031776 0ustar jamespagejamespage00000000000000js> var x = 1; js> x 1 js> var xmlLib = org.mozilla.javascript.xml.XMLLib.extractFromScope(this); js> xmlLib.isPrettyPrinting(); true js> xmlLib.setPrettyPrinting(false); js> xmlLib.isPrettyPrinting(); false js> x 1jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/tail-call-in-try.doctest0000644000175000017500000000052611314263504032703 0ustar jamespagejamespage00000000000000// Fix bug reported in newsgroup: // Tail call optimization was interfering with catching exceptions. // The following program should print 7, but was resulting in an uncaught // exception. js> function g() { > throw 3; > } js> function f() { > try { > return g(); > } catch (e) { > return 7; > } > } js> f() 7jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/442922.doctest0000644000175000017500000000027711314263504030372 0ustar jamespagejamespage00000000000000js> var x = ; js> serialize(x, "x.ser"); js> deserialize("x.ser"); js> (new java.io.File("x.ser"))["delete"](); truejenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/Counter.doctest0000644000175000017500000000021511314263504031233 0ustar jamespagejamespage00000000000000js> defineClass("Counter") js> c = new Counter(7) [object Counter] js> c.count 7 js> c.count 8 js> c.count 9 js> c.resetCount() js> c.count 0jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.defineproperties.doctest0000644000175000017500000000241511314263504034434 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.defineProperties function defineProperties() { [native code for Object.defineProperties, arity=2] } js> expectTypeError(function() { Object.defineProperties() }); js> expectTypeError(function() { Object.defineProperties({}) }); js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.defineProperties(value, {}) }) > }) js> Object.defineProperties({}, {p: {value:1}}).p 1 js> var obj = Object.defineProperties({}, {a: {value:1}, b: {value:2}}); js> [obj.a, obj.b].toSource(); [1, 2] js> Object.defineProperties({}, {'wierd name': {value:1}})['wierd name'] 1 js> Object.defineProperties({}, {}).toSource() ({}) js> var obj = {a:1}; js> var obj = Object.defineProperties(obj, {a:{value:2}, b:{value:3}}); js> [obj.a, obj.b].toSource() [2, 3] js> expectTypeError(function() { Object.defineProperties({}, {a: null}) }) js> expectTypeError(function() { Object.defineProperties({}, {a: 1}) }) js> expectTypeError(function() { Object.defineProperties({}, {a: {get: 1}}) }) js> var obj = {a:1} js> expectTypeError(function() { > obj = Object.defineProperties(obj, {b: {value:1}, c:1}); > }); js> obj.b js> js> Object.defineProperties({}, {'0.0': {value:1}, 0: {value:2}})['0'] 2 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/480758.doctest0000755000175000017500000000063311314263504030402 0ustar jamespagejamespage00000000000000js> function primBeget(proto) { > if (proto === null) { fail("Cannot beget from null."); } > if (proto === (void 0)) { fail("Cannot beget from undefined."); } > function F() {} > F.prototype = proto; > var result = new F(); > return result; > } js> var x = [1].concat(primBeget(Array.prototype)); js> x 1, js> x[1] js> typeof x[1] object js> x[1] instanceof Array truejenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.getownpropertydescriptor.doctest0000644000175000017500000000273111314263504036275 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.getOwnPropertyDescriptor; function getOwnPropertyDescriptor() { [native code for Object.getOwnPropertyDescriptor, arity=2] } js> expectTypeError(function() { Object.getOwnPropertyDescriptor() }) js> var desc = Object.getOwnPropertyDescriptor({undefined:3}); js> desc.value 3 js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.getOwnPropertyDescriptor(value, 'p') }) > }) js> Object.getOwnPropertyDescriptor({}, 'p') === undefined; true js> var desc = Object.getOwnPropertyDescriptor({p:1}, 'p'); js> desc.value 1 js> desc.writable true js> desc.enumerable true js> desc.configurable true js> var desc = Object.getOwnPropertyDescriptor({ get p() {}, set p() {} }, 'p'); js> desc.value === undefined; true js> desc.writable === undefined; true js> desc.get.toSource() (function () {}) js> desc.set.toSource() (function () {}) js> desc.enumerable true js> desc.configurable true js> desc.__proto__ === Object.prototype true js> desc.__parent__; [object global] js> var func = function(){} js> func.a = 1; Object.getOwnPropertyDescriptor(func, 'a').toSource() ({value:1, writable:true, enumerable:true, configurable:true}) js> Object.getOwnPropertyDescriptor({undefined: 1}, undefined).toSource() ({value:1, writable:true, enumerable:true, configurable:true}) js> Object.getOwnPropertyDescriptor({0:1}, 0).toSource() ({value:1, writable:true, enumerable:true, configurable:true}) jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.getprototypeof.doctest0000644000175000017500000000126211314263504034156 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.getPrototypeOf; function getPrototypeOf() { [native code for Object.getPrototypeOf, arity=1] } js> expectTypeError(function() { Object.getPrototypeOf() }) js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.getPrototypeOf(value) }) > }) js> [(function(){}), [], {}].every(function(obj) { > return Object.getPrototypeOf(obj) === obj.__proto__; > }); true js> function UserDefined() {} js> [Date, UserDefined].every(function(type) { > var instance; > eval('instance = new '+type.name); > return Object.getPrototypeOf(instance) === type.prototype; > }); true jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/test2.doctest0000644000175000017500000000031511314263504030656 0ustar jamespagejamespage00000000000000js> a = [] js> a[0] = 10 10 js> a[1] = 11 11 js> a[3] = 13 13 js> a[4] = 14 14 js> a[5] = 15 15 js> a.reverse() 15,14,13,,11,10 js> a.reverse() 10,11,,13,14,15 js> a.concat([16,17]) 10,11,,13,14,15,16,17 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.issealed.doctest0000644000175000017500000000130711314263504032655 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.isSealed function isSealed() { [native code for Object.isSealed, arity=1] } js> expectTypeError(function() { Object.isSealed() }); js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.isSealed(value) }) > }) js> Object.isSealed({}) false js> var obj = Object.preventExtensions({}); js> Object.isSealed(obj); true js> var obj = Object.defineProperty({}, 'a', {configurable:false}); js> var _ = Object.preventExtensions(obj); js> Object.isSealed(obj); true js> var obj = Object.defineProperty({}, 'a', {configurable:true}); js> var _ = Object.preventExtensions(obj); js> Object.isSealed(obj); false jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/413838.doctest0000644000175000017500000000114411314263504030370 0ustar jamespagejamespage00000000000000js> var map = new java.util.HashMap(); js> map.put("a","hi"); null js> map.put("b","hi"); null js> map.get("a") == map.get("b") true js> map.put("c",1) null js> map.put("c",1) 1.0 js> map.put("d",1) null js> map.get("c") == map.get("d") true js> map.get("a") == map.get("d") false js> map.put("e","1") null js> map.get("d") == map.get("e") true js> map.put("f", true) null js> map.put("g", true) null js> map.get("f") == map.get("g") true js> var obj = {} js> map.put("h", obj) null js> map.put("i", obj) null js> map.get("h") == map.get("i") true js> map.put("j", {}) null js> map.get("i") == map.get("j") falsejenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.defineproperty.doctest0000644000175000017500000001515411314263504034130 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.defineProperty function defineProperty() { [native code for Object.defineProperty, arity=3] } js> expectTypeError(function() { Object.defineProperty() }); js> expectTypeError(function() { Object.defineProperty({}) }); js> expectTypeError(function() { Object.defineProperty({}, 'p') }); js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.defineProperty(value, 'p', {}) }) > }) js> Object.defineProperty({}, 'p', {value:1}).p 1 js> var obj = {} js> Object.defineProperty(obj, 'a', { > value: 1, > enumerable: false, > writable: false, > configurable: false > }) [object Object] js> for (var p in obj) print(p); // check it has no enumerable properties js> obj.a = 2; obj.a; // check that the property is not writable 1 js> delete obj.a; obj.a // check that the property is not deletable 1 js> var define = Object.defineProperty; js> var describe = Object.getOwnPropertyDescriptor; js> // when define new property with empty descriptor then default values are used for the descriptor js> var obj = define({}, 'a', {}); js> describe(obj, 'a').toSource() ({writable:false, enumerable:false, configurable:false}) js> // when define new property with data descriptor then those values are used for the descriptor js> var obj = define({}, 'a', { value: 2, writable: true }); js> var {value:v, writable:w} = describe(obj, 'a'); [v, w].toSource(); [2, true] js> obj.a 2 js> // when define new property with accessor descriptor then those values are used for the descriptor js> var obj = define({}, 'a', { get: function() { return 3; }, set: function(value) {} }); js> var {get:g, set:s} = describe(obj, 'a'); [g, s].toSource(); [(function () {return 3;}), (function (value) {})] js> obj.a 3 js> // when define existing property with empty descriptor then descriptor is left unchanged js> var descriptor = {value:1, writable:true, enumerable:true, configurable:true}; js> var obj = define({}, 'a', descriptor); js> var obj = define(obj, 'a', {}); js> describe(obj, 'a').toSource() ({value:1, writable:true, enumerable:true, configurable:true}) js> // when define existing property with same descriptor then descriptor is left unchanged js> var descriptor = {value:1, writable:true, enumerable:true, configurable:true}; js> var obj = define({}, 'a', descriptor); js> var obj = define(obj, 'a', descriptor); js> describe(obj, 'a').toSource() ({value:1, writable:true, enumerable:true, configurable:true}) js> // may not change configurable from false to true js> expectTypeError(function() { > var obj = define({}, 'a', {configurable : false}); > define(obj, 'a', {configurable : true}); > }); js> // may not change enumerable when configurable is false js> expectTypeError(function() { > var obj = define({}, 'a', {enumerable : true, configurable:false}); > define(obj, 'a', {enumerable : false}); > }); js> // may not change writable from false to true when configurable is false js> expectTypeError(function() { > var obj = define({}, 'a', {writable : false, configurable: false}); > define(obj, 'a', {writable : true}); > }); js> // may not change value when writable is false js> expectTypeError(function() { > var obj = define({}, 'a', {value : 1, writable:false}); > define(obj, 'a', {value : 2}); > }); js> // may not change getter when configurable is false js> expectTypeError(function() { > var obj = define({}, 'a', {get: function() { return 1 }, configurable:false}); > define(obj, 'a', {get: function() { return 1 }}); > }); js> // may not change setter when configurable is false js> expectTypeError(function() { > var obj = define({}, 'a', {set: function(val) {}, configurable:false}); > define(obj, 'a', {set: function(val) {}}); > }); js> // may not change from data property to accessor property when configurable is false js> expectTypeError(function() { > var obj = define({}, 'a', {value : 1, configurable:false}); > define(obj, 'a', {get : function() { return 1 }}); > }); js> // may not change from accessor property to data property when configurable is false js> expectTypeError(function() { > var obj = define({}, 'a', {get : function() { return 1 }, configurable:false}); > define(obj, 'a', {value : 1}); > }); js> // can change writable from true to false when configurable is false js> var obj = define({}, 'a', {writable:true, configurable:false}); js> var obj = define(obj, 'a', {writable:false}); js> // can set enumerable to the same value when configuable is false js> var obj = define({}, 'a', {enumerable:true, configurable:false}); js> var obj = define(obj, 'a', {enumerable:true}); js> // can change from data property to accessor property when configurable is true js> var obj = define({}, 'a', {value : 1, configurable: true}); js> var obj = define(obj, 'a', {get : function() { return 4 }}); js> obj.a 4 js> describe(obj, 'a').toSource() ({enumerable:false, configurable:true, get:(function () {return 4;})}) js> // can change from accessor property to data property when configurable is true js> var obj = define({}, 'a', {get : function() { return 2 }, configurable:true}); js> var obj = define(obj, 'a', {value : 5}); js> obj.a 5 js> describe(obj, 'a').toSource() ({value:5, writable:false, enumerable:false, configurable:true}) js> // can change enumerable and writable to true when configurable is true js> var obj = define({}, 'a', {writable : false, enumerable : false, configurable:true}); js> var obj = define(obj, 'a', {writable : true, enumerable : true, configurable:true}); js> // can change the value if writable is true js> var obj = define({}, 'a', {value:6, writable:true}) js> obj.a 6 js> var obj = define(obj, 'a', {value:7}) js> obj.a 7 js> // defining a new property should fail loudly when object is not extensible js> var obj = Object.preventExtensions({}); js> expectTypeError(function() { define(obj, 'a', {value:1}) }) js> // defining new property should succeed when object is extensible js> var obj = {} js> Object.isExtensible(obj); true js> obj.a = 8; obj.a 8 js> // changing existing property should succeed when object is not extensible js> var obj = define({}, 'a', {value:1, writable:true}); js> var obj = Object.preventExtensions(obj); js> obj.a = 9; obj.a 9 js> // defined getters and setters must be functions js> expectTypeError(function() { define({}, 'a', {get:1}); }) js> expectTypeError(function() { define({}, 'a', {set:1}); }) js> // make sure defineProperty works properly with numbers as ids js> Object.defineProperty({}, 0, {value:1, enumerable:true})['0'] 1 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/doctests/object.seal.doctest0000644000175000017500000000111111314263504032001 0ustar jamespagejamespage00000000000000js> load('testsrc/doctests/util.js'); js> Object.seal; function seal() { [native code for Object.seal, arity=1] } js> [undefined, null, true, 1, 'hello'].forEach(function(value) { > expectTypeError(function() { Object.seal(value) }) > }) js> expectTypeError(function() { Object.seal() }) js> var x = {} js> var y = Object.seal(x) js> x === y true js> var obj = Object.defineProperty({}, 'a', {configurable:true}) js> var _ = Object.seal(obj) js> Object.getOwnPropertyDescriptor(obj, 'a').configurable false js> Object.isExtensible(obj) false js> Object.isSealed(obj) true jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/jstests/0000755000175000017500000000000011537630013026076 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/jstests/437988.jstest0000644000175000017500000000056511314263504030130 0ustar jamespagejamespage00000000000000// Rhino must discover the abstract methods in the interface // of AbstractTableModel var tableModel = new javax.swing.table.AbstractTableModel() { getRowCount: function() { return 2; }, getColumnCount: function() { return 2; }, getValueAt: function(row, column) { return "ABC"; } }; var jTable = new javax.swing.JTable(tableModel); "success"; jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/jstests/420012.jstest0000644000175000017500000000034311314263504030064 0ustar jamespagejamespage00000000000000var o = new Object; o.setX = function (id) { this.oid = id; } function setX(n) { if (n == "" || n == null) n = 0; var s = new Object; s.xyz = n; if (s != null) { o.setX(s.xyz); } } setX('x'); "success"; jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/jstests/destructuringLvalue.jstest0000644000175000017500000000072411314263504033412 0ustar jamespagejamespage00000000000000/* TODO(stevey): fix this test var obj = { p:3 }; var arr = [ 3 ]; [obj.p] = [9]; if (obj.p != 9) throw "obj.p not set by array destructuring assignment"; [arr[0]] = [9]; if (arr[0] != 9) throw "arr[0] not set by array destructuring assignment"; ({prop:obj.p} = {prop:12}); if (obj.p != 12) throw "obj.p not set by object destructuring assignment"; ({prop:arr[0]} = {prop:12}); if (arr[0] != 12) throw "arr[0] not set by object destructuring assignment"; */ "success" jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/benchmarks/0000755000175000017500000000000011537630013026514 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/benchmarks/v8/0000755000175000017500000000000011537630013027051 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/benchmarks/v8/crypto.js0000644000175000017500000013561611314263504030743 0ustar jamespagejamespage00000000000000/* * Copyright (c) 2003-2005 Tom Wu * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ // The code has been adapted for use as a benchmark by Google. var Crypto = new BenchmarkSuite('Crypto', 203037, [ new Benchmark("Encrypt", encrypt), new Benchmark("Decrypt", decrypt) ]); // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; var BI_DB; var BI_DM; var BI_DV; var BI_FP; var BI_FV; var BI_F1; var BI_F2; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { this.array = new Array(); if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { var this_array = this.array; var w_array = w.array; while(--n >= 0) { var v = x*this_array[i++]+w_array[j]+c; c = Math.floor(v/0x4000000); w_array[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var this_array = this.array; var w_array = w.array; var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this_array[i]&0x7fff; var h = this_array[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w_array[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w_array[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var this_array = this.array; var w_array = w.array; var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this_array[i]&0x3fff; var h = this_array[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w_array[j]+c; c = (l>>28)+(m>>14)+xh*h; w_array[j++] = l&0xfffffff; } return c; } // This is tailored to VMs with 2-bit tagging. It makes sure // that all the computations stay within the 29 bits available. function am4(i,x,w,j,c,n) { var this_array = this.array; var w_array = w.array; var xl = x&0x1fff, xh = x>>13; while(--n >= 0) { var l = this_array[i]&0x1fff; var h = this_array[i++]>>13; var m = xh*l+h*xl; l = xl*l+((m&0x1fff)<<13)+w_array[j]+c; c = (l>>26)+(m>>13)+xh*h; w_array[j++] = l&0x3ffffff; } return c; } // am3/28 is best for SM, Rhino, but am4/26 is best for v8. // Kestrel (Opera 9.5) gets its best result with am4/26. // IE7 does 9% better with am3/28 than with am4/26. // Firefox (SM) gets 10% faster with am3/28 than with am4/26. setupEngine = function(fn, bits) { BigInteger.prototype.am = fn; dbits = bits; BI_DB = dbits; BI_DM = ((1<= 0; --i) r_array[i] = this_array[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { var this_array = this.array; this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this_array[0] = x; else if(x < -1) this_array[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var this_array = this.array; var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this_array[this.t++] = x; else if(sh+k > BI_DB) { this_array[this.t-1] |= (x&((1<<(BI_DB-sh))-1))<>(BI_DB-sh)); } else this_array[this.t-1] |= x<= BI_DB) sh -= BI_DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this_array[this.t-1] |= ((1<<(BI_DB-sh))-1)< 0 && this_array[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { var this_array = this.array; if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1< 0) { if(p < BI_DB && (d = this_array[i]>>p) > 0) { m = true; r = int2char(d); } while(i >= 0) { if(p < k) { d = (this_array[i]&((1<>(p+=BI_DB-k); } else { d = (this_array[i]>>(p-=k))&km; if(p <= 0) { p += BI_DB; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var this_array = this.array; var a_array = a.array; var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return r; while(--i >= 0) if((r=this_array[i]-a_array[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { var this_array = this.array; if(this.t <= 0) return 0; return BI_DB*(this.t-1)+nbits(this_array[this.t-1]^(this.s&BI_DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var this_array = this.array; var r_array = r.array; var i; for(i = this.t-1; i >= 0; --i) r_array[i+n] = this_array[i]; for(i = n-1; i >= 0; --i) r_array[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { var this_array = this.array; var r_array = r.array; for(var i = n; i < this.t; ++i) r_array[i-n] = this_array[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var this_array = this.array; var r_array = r.array; var bs = n%BI_DB; var cbs = BI_DB-bs; var bm = (1<= 0; --i) { r_array[i+ds+1] = (this_array[i]>>cbs)|c; c = (this_array[i]&bm)<= 0; --i) r_array[i] = 0; r_array[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { var this_array = this.array; var r_array = r.array; r.s = this.s; var ds = Math.floor(n/BI_DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%BI_DB; var cbs = BI_DB-bs; var bm = (1<>bs; for(var i = ds+1; i < this.t; ++i) { r_array[i-ds-1] |= (this_array[i]&bm)<>bs; } if(bs > 0) r_array[this.t-ds-1] |= (this.s&bm)<>= BI_DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this_array[i]; r_array[i++] = c&BI_DM; c >>= BI_DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a_array[i]; r_array[i++] = c&BI_DM; c >>= BI_DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r_array[i++] = BI_DV+c; else if(c > 0) r_array[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var this_array = this.array; var r_array = r.array; var x = this.abs(), y = a.abs(); var y_array = y.array; var i = x.t; r.t = i+y.t; while(--i >= 0) r_array[i] = 0; for(i = 0; i < y.t; ++i) r_array[i+x.t] = x.am(0,y_array[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var x_array = x.array; var r_array = r.array; var i = r.t = 2*x.t; while(--i >= 0) r_array[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x_array[i],r,2*i,0,1); if((r_array[i+x.t]+=x.am(i+1,2*x_array[i],r,2*i+1,c,x.t-i-1)) >= BI_DV) { r_array[i+x.t] -= BI_DV; r_array[i+x.t+1] = 1; } } if(r.t > 0) r_array[r.t-1] += x.am(i,x_array[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var pm_array = pm.array; var nsh = BI_DB-nbits(pm_array[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y_array = y.array; var y0 = y_array[ys-1]; if(y0 == 0) return; var yt = y0*(1<1)?y_array[ys-2]>>BI_F2:0); var d1 = BI_FV/yt, d2 = (1<= 0) { r_array[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y_array[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r_array[--i]==y0)?BI_DM:Math.floor(r_array[i]*d1+(r_array[i-1]+e)*d2); if((r_array[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r_array[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { var this_array = this.array; if(this.t < 1) return 0; var x = this_array[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%BI_DV))%BI_DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?BI_DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(BI_DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { var x_array = x.array; while(x.t <= this.mt2) // pad x so am has enough room later x_array[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x_array[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x_array[i]>>15)*this.mpl)&this.um)<<15))&BI_DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x_array[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x_array[j] >= BI_DV) { x_array[j] -= BI_DV; x_array[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { var this_array = this.array; return ((this.t>0)?(this_array[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1< 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // (public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } // (public) return value as integer function bnIntValue() { var this_array = this.array; if(this.s < 0) { if(this.t == 1) return this_array[0]-BI_DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this_array[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this_array[1]&((1<<(32-BI_DB))-1))<>24; } // (public) return value as short (assumes DB>=16) function bnShortValue() { var this_array = this.array; return (this.t==0)?this.s:(this_array[0]<<16)>>16; } // (protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2*BI_DB/Math.log(r)); } // (public) 0 if this == 0, 1 if this > 0 function bnSigNum() { var this_array = this.array; if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this_array[0] <= 0)) return 0; else return 1; } // (protected) convert to radix string function bnpToRadix(b) { if(b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b,cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d,y,z); while(y.signum() > 0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } // (protected) convert from radix string function bnpFromRadix(s,b) { this.fromInt(0); if(b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b,cs), mi = false, j = 0, w = 0; for(var i = 0; i < s.length; ++i) { var x = intAt(s,i); if(x < 0) { if(s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; } w = b*w+x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(Math.pow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) alternate constructor function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = new Array(), t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1< 0) { if(p < BI_DB && (d = this_array[i]>>p) != (this.s&BI_DM)>>p) r[k++] = d|(this.s<<(BI_DB-p)); while(i >= 0) { if(p < 8) { d = (this_array[i]&((1<>(p+=BI_DB-8); } else { d = (this_array[i]>>(p-=8))&0xff; if(p <= 0) { p += BI_DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } // (protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var this_array = this.array; var a_array = a.array; var r_array = r.array; var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r_array[i] = op(this_array[i],a_array[i]); if(a.t < this.t) { f = a.s&BI_DM; for(i = m; i < this.t; ++i) r_array[i] = op(this_array[i],f); r.t = this.t; } else { f = this.s&BI_DM; for(i = m; i < a.t; ++i) r_array[i] = op(f,a_array[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } // (public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } // (public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } // (public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } // (public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } // (public) ~this function bnNot() { var this_array = this.array; var r = nbi(); var r_array = r.array; for(var i = 0; i < this.t; ++i) r_array[i] = BI_DM&~this_array[i]; r.t = this.t; r.s = ~this.s; return r; } // (public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } // (public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { var this_array = this.array; for(var i = 0; i < this.t; ++i) if(this_array[i] != 0) return i*BI_DB+lbit(this_array[i]); if(this.s < 0) return this.t*BI_DB; return -1; } // return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } // (public) return number of set bits function bnBitCount() { var r = 0, x = this.s&BI_DM; for(var i = 0; i < this.t; ++i) r += cbit(this_array[i]^x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { var this_array = this.array; var j = Math.floor(n/BI_DB); if(j >= this.t) return(this.s!=0); return((this_array[j]&(1<<(n%BI_DB)))!=0); } // (protected) this op (1<>= BI_DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this_array[i]; r_array[i++] = c&BI_DM; c >>= BI_DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a_array[i]; r_array[i++] = c&BI_DM; c >>= BI_DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r_array[i++] = c; else if(c < -1) r_array[i++] = BI_DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return new Array(q,r); } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { var this_array = this.array; this_array[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { var this_array = this.array; while(this.t <= w) this_array[this.t++] = 0; this_array[w] += n; while(this_array[w] >= BI_DV) { this_array[w] -= BI_DV; if(++w >= this.t) this_array[this.t++] = 0; ++this_array[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var r_array = r.array; var a_array = a.array; var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r_array[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r_array[i+this.t] = this.am(0,a_array[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a_array[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { var r_array = r.array; var a_array = a.array; --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r_array[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r_array[this.t+i-n] = this.am(n-i,a_array[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var e_array = e.array; var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e_array[j])-1; while(j >= 0) { if(i >= k1) w = (e_array[j]>>(i-k1))&km; else { w = (e_array[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e_array[j-1]>>(BI_DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += BI_DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e_array[j]&(1< 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { var this_array = this.array; if(n <= 0) return 0; var d = BI_DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this_array[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this_array[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); var x_array = x.array; if(x.t == 1 && x_array[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x_array[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) // prng4.js - uses Arcfour as a PRNG function Arcfour() { this.i = 0; this.j = 0; this.S = new Array(); } // Initialize arcfour context from key, an array of ints, each from [0..255] function ARC4init(key) { var i, j, t; for(i = 0; i < 256; ++i) this.S[i] = i; j = 0; for(i = 0; i < 256; ++i) { j = (j + this.S[i] + key[i % key.length]) & 255; t = this.S[i]; this.S[i] = this.S[j]; this.S[j] = t; } this.i = 0; this.j = 0; } function ARC4next() { var t; this.i = (this.i + 1) & 255; this.j = (this.j + this.S[this.i]) & 255; t = this.S[this.i]; this.S[this.i] = this.S[this.j]; this.S[this.j] = t; return this.S[(t + this.S[this.i]) & 255]; } Arcfour.prototype.init = ARC4init; Arcfour.prototype.next = ARC4next; // Plug in your RNG constructor here function prng_newstate() { return new Arcfour(); } // Pool size must be a multiple of 4 and greater than 32. // An array of bytes the size of the pool will be passed to init() var rng_psize = 256; // Random number generator - requires a PRNG backend, e.g. prng4.js // For best results, put code like // // in your main HTML document. var rng_state; var rng_pool; var rng_pptr; // Mix in a 32-bit integer into the pool function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; } // Mix in the current time (w/milliseconds) into the pool function rng_seed_time() { // Use pre-computed date to avoid making the benchmark // results dependent on the current date. rng_seed_int(1122926989487); } // Initialize the pool with junk if needed. if(rng_pool == null) { rng_pool = new Array(); rng_pptr = 0; var t; while(rng_pptr < rng_psize) { // extract some randomness from Math.random() t = Math.floor(65536 * Math.random()); rng_pool[rng_pptr++] = t >>> 8; rng_pool[rng_pptr++] = t & 255; } rng_pptr = 0; rng_seed_time(); //rng_seed_int(window.screenX); //rng_seed_int(window.screenY); } function rng_get_byte() { if(rng_state == null) { rng_seed_time(); rng_state = prng_newstate(); rng_state.init(rng_pool); for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) rng_pool[rng_pptr] = 0; rng_pptr = 0; //rng_pool = null; } // TODO: allow reseeding after first request return rng_state.next(); } function rng_get_bytes(ba) { var i; for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); } function SecureRandom() {} SecureRandom.prototype.nextBytes = rng_get_bytes; // Depends on jsbn.js and rng.js // convert a (hex) string to a bignum object function parseBigInt(str,r) { return new BigInteger(str,r); } function linebrk(s,n) { var ret = ""; var i = 0; while(i + n < s.length) { ret += s.substring(i,i+n) + "\n"; i += n; } return ret + s.substring(i,s.length); } function byte2Hex(b) { if(b < 0x10) return "0" + b.toString(16); else return b.toString(16); } // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint function pkcs1pad2(s,n) { if(n < s.length + 11) { alert("Message too long for RSA"); return null; } var ba = new Array(); var i = s.length - 1; while(i >= 0 && n > 0) ba[--n] = s.charCodeAt(i--); ba[--n] = 0; var rng = new SecureRandom(); var x = new Array(); while(n > 2) { // random non-zero pad x[0] = 0; while(x[0] == 0) rng.nextBytes(x); ba[--n] = x[0]; } ba[--n] = 2; ba[--n] = 0; return new BigInteger(ba); } // "empty" RSA key constructor function RSAKey() { this.n = null; this.e = 0; this.d = null; this.p = null; this.q = null; this.dmp1 = null; this.dmq1 = null; this.coeff = null; } // Set the public key fields N and e from hex strings function RSASetPublic(N,E) { if(N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N,16); this.e = parseInt(E,16); } else alert("Invalid RSA public key"); } // Perform raw public operation on "x": return x^e (mod n) function RSADoPublic(x) { return x.modPowInt(this.e, this.n); } // Return the PKCS#1 RSA encryption of "text" as an even-length hex string function RSAEncrypt(text) { var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); if(m == null) return null; var c = this.doPublic(m); if(c == null) return null; var h = c.toString(16); if((h.length & 1) == 0) return h; else return "0" + h; } // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string //function RSAEncryptB64(text) { // var h = this.encrypt(text); // if(h) return hex2b64(h); else return null; //} // protected RSAKey.prototype.doPublic = RSADoPublic; // public RSAKey.prototype.setPublic = RSASetPublic; RSAKey.prototype.encrypt = RSAEncrypt; //RSAKey.prototype.encrypt_b64 = RSAEncryptB64; // Depends on rsa.js and jsbn2.js // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext function pkcs1unpad2(d,n) { var b = d.toByteArray(); var i = 0; while(i < b.length && b[i] == 0) ++i; if(b.length-i != n-1 || b[i] != 2) return null; ++i; while(b[i] != 0) if(++i >= b.length) return null; var ret = ""; while(++i < b.length) ret += String.fromCharCode(b[i]); return ret; } // Set the private key fields N, e, and d from hex strings function RSASetPrivate(N,E,D) { if(N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N,16); this.e = parseInt(E,16); this.d = parseBigInt(D,16); } else alert("Invalid RSA private key"); } // Set the private key fields N, e, d and CRT params from hex strings function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) { if(N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N,16); this.e = parseInt(E,16); this.d = parseBigInt(D,16); this.p = parseBigInt(P,16); this.q = parseBigInt(Q,16); this.dmp1 = parseBigInt(DP,16); this.dmq1 = parseBigInt(DQ,16); this.coeff = parseBigInt(C,16); } else alert("Invalid RSA private key"); } // Generate a new random private key B bits long, using public expt E function RSAGenerate(B,E) { var rng = new SecureRandom(); var qs = B>>1; this.e = parseInt(E,16); var ee = new BigInteger(E,16); for(;;) { for(;;) { this.p = new BigInteger(B-qs,1,rng); if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break; } for(;;) { this.q = new BigInteger(qs,1,rng); if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break; } if(this.p.compareTo(this.q) <= 0) { var t = this.p; this.p = this.q; this.q = t; } var p1 = this.p.subtract(BigInteger.ONE); var q1 = this.q.subtract(BigInteger.ONE); var phi = p1.multiply(q1); if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { this.n = this.p.multiply(this.q); this.d = ee.modInverse(phi); this.dmp1 = this.d.mod(p1); this.dmq1 = this.d.mod(q1); this.coeff = this.q.modInverse(this.p); break; } } } // Perform raw private operation on "x": return x^d (mod n) function RSADoPrivate(x) { if(this.p == null || this.q == null) return x.modPow(this.d, this.n); // TODO: re-calculate any missing CRT params var xp = x.mod(this.p).modPow(this.dmp1, this.p); var xq = x.mod(this.q).modPow(this.dmq1, this.q); while(xp.compareTo(xq) < 0) xp = xp.add(this.p); return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); } // Return the PKCS#1 RSA decryption of "ctext". // "ctext" is an even-length hex string and the output is a plain string. function RSADecrypt(ctext) { var c = parseBigInt(ctext, 16); var m = this.doPrivate(c); if(m == null) return null; return pkcs1unpad2(m, (this.n.bitLength()+7)>>3); } // Return the PKCS#1 RSA decryption of "ctext". // "ctext" is a Base64-encoded string and the output is a plain string. //function RSAB64Decrypt(ctext) { // var h = b64tohex(ctext); // if(h) return this.decrypt(h); else return null; //} // protected RSAKey.prototype.doPrivate = RSADoPrivate; // public RSAKey.prototype.setPrivate = RSASetPrivate; RSAKey.prototype.setPrivateEx = RSASetPrivateEx; RSAKey.prototype.generate = RSAGenerate; RSAKey.prototype.decrypt = RSADecrypt; //RSAKey.prototype.b64_decrypt = RSAB64Decrypt; nValue="a5261939975948bb7a58dffe5ff54e65f0498f9175f5a09288810b8975871e99af3b5dd94057b0fc07535f5f97444504fa35169d461d0d30cf0192e307727c065168c788771c561a9400fb49175e9e6aa4e23fe11af69e9412dd23b0cb6684c4c2429bce139e848ab26d0829073351f4acd36074eafd036a5eb83359d2a698d3"; eValue="10001"; dValue="8e9912f6d3645894e8d38cb58c0db81ff516cf4c7e5a14c7f1eddb1459d2cded4d8d293fc97aee6aefb861859c8b6a3d1dfe710463e1f9ddc72048c09751971c4a580aa51eb523357a3cc48d31cfad1d4a165066ed92d4748fb6571211da5cb14bc11b6e2df7c1a559e6d5ac1cd5c94703a22891464fba23d0d965086277a161"; pValue="d090ce58a92c75233a6486cb0a9209bf3583b64f540c76f5294bb97d285eed33aec220bde14b2417951178ac152ceab6da7090905b478195498b352048f15e7d"; qValue="cab575dc652bb66df15a0359609d51d1db184750c00c6698b90ef3465c99655103edbf0d54c56aec0ce3c4d22592338092a126a0cc49f65a4a30d222b411e58f"; dmp1Value="1a24bca8e273df2f0e47c199bbf678604e7df7215480c77c8db39f49b000ce2cf7500038acfff5433b7d582a01f1826e6f4d42e1c57f5e1fef7b12aabc59fd25"; dmq1Value="3d06982efbbe47339e1f6d36b1216b8a741d410b0c662f54f7118b27b9a4ec9d914337eb39841d8666f3034408cf94f5b62f11c402fc994fe15a05493150d9fd"; coeffValue="3a3e731acd8960b7ff9eb81a7ff93bd1cfa74cbd56987db58b4594fb09c09084db1734c8143f98b602b981aaa9243ca28deb69b5b280ee8dcee0fd2625e53250"; setupEngine(am3, 28); var TEXT = "The quick brown fox jumped over the extremely lazy frog! " + "Now is the time for all good men to come to the party."; var encrypted; function encrypt() { var RSA = new RSAKey(); RSA.setPublic(nValue, eValue); RSA.setPrivateEx(nValue, eValue, dValue, pValue, qValue, dmp1Value, dmq1Value, coeffValue); encrypted = RSA.encrypt(TEXT); } function decrypt() { var RSA = new RSAKey(); RSA.setPublic(nValue, eValue); RSA.setPrivateEx(nValue, eValue, dValue, pValue, qValue, dmp1Value, dmq1Value, coeffValue); var decrypted = RSA.decrypt(encrypted); if (decrypted != TEXT) { throw new Error("Crypto operation failed"); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/benchmarks/v8/splay.js0000644000175000017500000002426711314263504030552 0ustar jamespagejamespage00000000000000// Copyright 2009 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This benchmark is based on a JavaScript log processing module used // by the V8 profiler to generate execution time profiles for runs of // JavaScript applications, and it effectively measures how fast the // JavaScript engine is at allocating nodes and reclaiming the memory // used for old nodes. Because of the way splay trees work, the engine // also has to deal with a lot of changes to the large tree object // graph. var Splay = new BenchmarkSuite('Splay', 126125, [ new Benchmark("Splay", SplayRun, SplaySetup, SplayTearDown) ]); // Configuration. var kSplayTreeSize = 8000; var kSplayTreeModifications = 80; var kSplayTreePayloadDepth = 5; var splayTree = null; function GeneratePayloadTree(depth, key) { if (depth == 0) { return { array : [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], string : 'String for key ' + key + ' in leaf node' }; } else { return { left: GeneratePayloadTree(depth - 1, key), right: GeneratePayloadTree(depth - 1, key) }; } } function GenerateKey() { // The benchmark framework guarantees that Math.random is // deterministic; see base.js. return Math.random(); } function InsertNewNode() { // Insert new node with a unique key. var key; do { key = GenerateKey(); } while (splayTree.find(key) != null); splayTree.insert(key, GeneratePayloadTree(kSplayTreePayloadDepth, key)); return key; } function SplaySetup() { splayTree = new SplayTree(); for (var i = 0; i < kSplayTreeSize; i++) InsertNewNode(); } function SplayTearDown() { // Allow the garbage collector to reclaim the memory // used by the splay tree no matter how we exit the // tear down function. var keys = splayTree.exportKeys(); splayTree = null; // Verify that the splay tree has the right size. var length = keys.length; if (length != kSplayTreeSize) { throw new Error("Splay tree has wrong size"); } // Verify that the splay tree has sorted, unique keys. for (var i = 0; i < length - 1; i++) { if (keys[i] >= keys[i + 1]) { throw new Error("Splay tree not sorted"); } } } function SplayRun() { // Replace a few nodes in the splay tree. for (var i = 0; i < kSplayTreeModifications; i++) { var key = InsertNewNode(); var greatest = splayTree.findGreatestLessThan(key); if (greatest == null) splayTree.remove(key); else splayTree.remove(greatest.key); } } /** * Constructs a Splay tree. A splay tree is a self-balancing binary * search tree with the additional property that recently accessed * elements are quick to access again. It performs basic operations * such as insertion, look-up and removal in O(log(n)) amortized time. * * @constructor */ function SplayTree() { }; /** * Pointer to the root node of the tree. * * @type {SplayTree.Node} * @private */ SplayTree.prototype.root_ = null; /** * @return {boolean} Whether the tree is empty. */ SplayTree.prototype.isEmpty = function() { return !this.root_; }; /** * Inserts a node into the tree with the specified key and value if * the tree does not already contain a node with the specified key. If * the value is inserted, it becomes the root of the tree. * * @param {number} key Key to insert into the tree. * @param {*} value Value to insert into the tree. */ SplayTree.prototype.insert = function(key, value) { if (this.isEmpty()) { this.root_ = new SplayTree.Node(key, value); return; } // Splay on the key to move the last node on the search path for // the key to the root of the tree. this.splay_(key); if (this.root_.key == key) { return; } var node = new SplayTree.Node(key, value); if (key > this.root_.key) { node.left = this.root_; node.right = this.root_.right; this.root_.right = null; } else { node.right = this.root_; node.left = this.root_.left; this.root_.left = null; } this.root_ = node; }; /** * Removes a node with the specified key from the tree if the tree * contains a node with this key. The removed node is returned. If the * key is not found, an exception is thrown. * * @param {number} key Key to find and remove from the tree. * @return {SplayTree.Node} The removed node. */ SplayTree.prototype.remove = function(key) { if (this.isEmpty()) { throw Error('Key not found: ' + key); } this.splay_(key); if (this.root_.key != key) { throw Error('Key not found: ' + key); } var removed = this.root_; if (!this.root_.left) { this.root_ = this.root_.right; } else { var right = this.root_.right; this.root_ = this.root_.left; // Splay to make sure that the new root has an empty right child. this.splay_(key); // Insert the original right child as the right child of the new // root. this.root_.right = right; } return removed; }; /** * Returns the node having the specified key or null if the tree doesn't contain * a node with the specified key. * * @param {number} key Key to find in the tree. * @return {SplayTree.Node} Node having the specified key. */ SplayTree.prototype.find = function(key) { if (this.isEmpty()) { return null; } this.splay_(key); return this.root_.key == key ? this.root_ : null; }; /** * @return {SplayTree.Node} Node having the maximum key value that * is less or equal to the specified key value. */ SplayTree.prototype.findGreatestLessThan = function(key) { if (this.isEmpty()) { return null; } // Splay on the key to move the node with the given key or the last // node on the search path to the top of the tree. this.splay_(key); // Now the result is either the root node or the greatest node in // the left subtree. if (this.root_.key <= key) { return this.root_; } else if (this.root_.left) { return this.findMax(this.root_.left); } else { return null; } }; /** * @return {Array<*>} An array containing all the keys of tree's nodes. */ SplayTree.prototype.exportKeys = function() { var result = []; if (!this.isEmpty()) { this.root_.traverse_(function(node) { result.push(node.key); }); } return result; }; /** * Perform the splay operation for the given key. Moves the node with * the given key to the top of the tree. If no node has the given * key, the last node on the search path is moved to the top of the * tree. This is the simplified top-down splaying algorithm from: * "Self-adjusting Binary Search Trees" by Sleator and Tarjan * * @param {number} key Key to splay the tree on. * @private */ SplayTree.prototype.splay_ = function(key) { if (this.isEmpty()) { return; } // Create a dummy node. The use of the dummy node is a bit // counter-intuitive: The right child of the dummy node will hold // the L tree of the algorithm. The left child of the dummy node // will hold the R tree of the algorithm. Using a dummy node, left // and right will always be nodes and we avoid special cases. var dummy, left, right; dummy = left = right = new SplayTree.Node(null, null); var current = this.root_; while (true) { if (key < current.key) { if (!current.left) { break; } if (key < current.left.key) { // Rotate right. var tmp = current.left; current.left = tmp.right; tmp.right = current; current = tmp; if (!current.left) { break; } } // Link right. right.left = current; right = current; current = current.left; } else if (key > current.key) { if (!current.right) { break; } if (key > current.right.key) { // Rotate left. var tmp = current.right; current.right = tmp.left; tmp.left = current; current = tmp; if (!current.right) { break; } } // Link left. left.right = current; left = current; current = current.right; } else { break; } } // Assemble. left.right = current.left; right.left = current.right; current.left = dummy.right; current.right = dummy.left; this.root_ = current; }; /** * Constructs a Splay tree node. * * @param {number} key Key. * @param {*} value Value. */ SplayTree.Node = function(key, value) { this.key = key; this.value = value; }; /** * @type {SplayTree.Node} */ SplayTree.Node.prototype.left = null; /** * @type {SplayTree.Node} */ SplayTree.Node.prototype.right = null; /** * Performs an ordered traversal of the subtree starting at * this SplayTree.Node. * * @param {function(SplayTree.Node)} f Visitor function. * @private */ SplayTree.Node.prototype.traverse_ = function(f) { var current = this; while (current) { var left = current.left; if (left) left.traverse_(f); f(current); current = current.right; } }; jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/benchmarks/v8/deltablue.js0000644000175000017500000006203111314263504031352 0ustar jamespagejamespage00000000000000// Copyright 2008 the V8 project authors. All rights reserved. // Copyright 1996 John Maloney and Mario Wolczko. // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // This implementation of the DeltaBlue benchmark is derived // from the Smalltalk implementation by John Maloney and Mario // Wolczko. Some parts have been translated directly, whereas // others have been modified more aggresively to make it feel // more like a JavaScript program. var DeltaBlue = new BenchmarkSuite('DeltaBlue', 71104, [ new Benchmark('DeltaBlue', deltaBlue) ]); /** * A JavaScript implementation of the DeltaBlue constrain-solving * algorithm, as described in: * * "The DeltaBlue Algorithm: An Incremental Constraint Hierarchy Solver" * Bjorn N. Freeman-Benson and John Maloney * January 1990 Communications of the ACM, * also available as University of Washington TR 89-08-06. * * Beware: this benchmark is written in a grotesque style where * the constraint model is built by side-effects from constructors. * I've kept it this way to avoid deviating too much from the original * implementation. */ /* --- O b j e c t M o d e l --- */ Object.prototype.inherits = function (shuper) { function Inheriter() { } Inheriter.prototype = shuper.prototype; this.prototype = new Inheriter(); this.superConstructor = shuper; } function OrderedCollection() { this.elms = new Array(); } OrderedCollection.prototype.add = function (elm) { this.elms.push(elm); } OrderedCollection.prototype.at = function (index) { return this.elms[index]; } OrderedCollection.prototype.size = function () { return this.elms.length; } OrderedCollection.prototype.removeFirst = function () { return this.elms.pop(); } OrderedCollection.prototype.remove = function (elm) { var index = 0, skipped = 0; for (var i = 0; i < this.elms.length; i++) { var value = this.elms[i]; if (value != elm) { this.elms[index] = value; index++; } else { skipped++; } } for (var i = 0; i < skipped; i++) this.elms.pop(); } /* --- * * S t r e n g t h * --- */ /** * Strengths are used to measure the relative importance of constraints. * New strengths may be inserted in the strength hierarchy without * disrupting current constraints. Strengths cannot be created outside * this class, so pointer comparison can be used for value comparison. */ function Strength(strengthValue, name) { this.strengthValue = strengthValue; this.name = name; } Strength.stronger = function (s1, s2) { return s1.strengthValue < s2.strengthValue; } Strength.weaker = function (s1, s2) { return s1.strengthValue > s2.strengthValue; } Strength.weakestOf = function (s1, s2) { return this.weaker(s1, s2) ? s1 : s2; } Strength.strongest = function (s1, s2) { return this.stronger(s1, s2) ? s1 : s2; } Strength.prototype.nextWeaker = function () { switch (this.strengthValue) { case 0: return Strength.WEAKEST; case 1: return Strength.WEAK_DEFAULT; case 2: return Strength.NORMAL; case 3: return Strength.STRONG_DEFAULT; case 4: return Strength.PREFERRED; case 5: return Strength.REQUIRED; } } // Strength constants. Strength.REQUIRED = new Strength(0, "required"); Strength.STONG_PREFERRED = new Strength(1, "strongPreferred"); Strength.PREFERRED = new Strength(2, "preferred"); Strength.STRONG_DEFAULT = new Strength(3, "strongDefault"); Strength.NORMAL = new Strength(4, "normal"); Strength.WEAK_DEFAULT = new Strength(5, "weakDefault"); Strength.WEAKEST = new Strength(6, "weakest"); /* --- * * C o n s t r a i n t * --- */ /** * An abstract class representing a system-maintainable relationship * (or "constraint") between a set of variables. A constraint supplies * a strength instance variable; concrete subclasses provide a means * of storing the constrained variables and other information required * to represent a constraint. */ function Constraint(strength) { this.strength = strength; } /** * Activate this constraint and attempt to satisfy it. */ Constraint.prototype.addConstraint = function () { this.addToGraph(); planner.incrementalAdd(this); } /** * Attempt to find a way to enforce this constraint. If successful, * record the solution, perhaps modifying the current dataflow * graph. Answer the constraint that this constraint overrides, if * there is one, or nil, if there isn't. * Assume: I am not already satisfied. */ Constraint.prototype.satisfy = function (mark) { this.chooseMethod(mark); if (!this.isSatisfied()) { if (this.strength == Strength.REQUIRED) alert("Could not satisfy a required constraint!"); return null; } this.markInputs(mark); var out = this.output(); var overridden = out.determinedBy; if (overridden != null) overridden.markUnsatisfied(); out.determinedBy = this; if (!planner.addPropagate(this, mark)) alert("Cycle encountered"); out.mark = mark; return overridden; } Constraint.prototype.destroyConstraint = function () { if (this.isSatisfied()) planner.incrementalRemove(this); else this.removeFromGraph(); } /** * Normal constraints are not input constraints. An input constraint * is one that depends on external state, such as the mouse, the * keybord, a clock, or some arbitraty piece of imperative code. */ Constraint.prototype.isInput = function () { return false; } /* --- * * U n a r y C o n s t r a i n t * --- */ /** * Abstract superclass for constraints having a single possible output * variable. */ function UnaryConstraint(v, strength) { UnaryConstraint.superConstructor.call(this, strength); this.myOutput = v; this.satisfied = false; this.addConstraint(); } UnaryConstraint.inherits(Constraint); /** * Adds this constraint to the constraint graph */ UnaryConstraint.prototype.addToGraph = function () { this.myOutput.addConstraint(this); this.satisfied = false; } /** * Decides if this constraint can be satisfied and records that * decision. */ UnaryConstraint.prototype.chooseMethod = function (mark) { this.satisfied = (this.myOutput.mark != mark) && Strength.stronger(this.strength, this.myOutput.walkStrength); } /** * Returns true if this constraint is satisfied in the current solution. */ UnaryConstraint.prototype.isSatisfied = function () { return this.satisfied; } UnaryConstraint.prototype.markInputs = function (mark) { // has no inputs } /** * Returns the current output variable. */ UnaryConstraint.prototype.output = function () { return this.myOutput; } /** * Calculate the walkabout strength, the stay flag, and, if it is * 'stay', the value for the current output of this constraint. Assume * this constraint is satisfied. */ UnaryConstraint.prototype.recalculate = function () { this.myOutput.walkStrength = this.strength; this.myOutput.stay = !this.isInput(); if (this.myOutput.stay) this.execute(); // Stay optimization } /** * Records that this constraint is unsatisfied */ UnaryConstraint.prototype.markUnsatisfied = function () { this.satisfied = false; } UnaryConstraint.prototype.inputsKnown = function () { return true; } UnaryConstraint.prototype.removeFromGraph = function () { if (this.myOutput != null) this.myOutput.removeConstraint(this); this.satisfied = false; } /* --- * * S t a y C o n s t r a i n t * --- */ /** * Variables that should, with some level of preference, stay the same. * Planners may exploit the fact that instances, if satisfied, will not * change their output during plan execution. This is called "stay * optimization". */ function StayConstraint(v, str) { StayConstraint.superConstructor.call(this, v, str); } StayConstraint.inherits(UnaryConstraint); StayConstraint.prototype.execute = function () { // Stay constraints do nothing } /* --- * * E d i t C o n s t r a i n t * --- */ /** * A unary input constraint used to mark a variable that the client * wishes to change. */ function EditConstraint(v, str) { EditConstraint.superConstructor.call(this, v, str); } EditConstraint.inherits(UnaryConstraint); /** * Edits indicate that a variable is to be changed by imperative code. */ EditConstraint.prototype.isInput = function () { return true; } EditConstraint.prototype.execute = function () { // Edit constraints do nothing } /* --- * * B i n a r y C o n s t r a i n t * --- */ var Direction = new Object(); Direction.NONE = 0; Direction.FORWARD = 1; Direction.BACKWARD = -1; /** * Abstract superclass for constraints having two possible output * variables. */ function BinaryConstraint(var1, var2, strength) { BinaryConstraint.superConstructor.call(this, strength); this.v1 = var1; this.v2 = var2; this.direction = Direction.NONE; this.addConstraint(); } BinaryConstraint.inherits(Constraint); /** * Decides if this constratint can be satisfied and which way it * should flow based on the relative strength of the variables related, * and record that decision. */ BinaryConstraint.prototype.chooseMethod = function (mark) { if (this.v1.mark == mark) { this.direction = (this.v1.mark != mark && Strength.stronger(this.strength, this.v2.walkStrength)) ? Direction.FORWARD : Direction.NONE; } if (this.v2.mark == mark) { this.direction = (this.v1.mark != mark && Strength.stronger(this.strength, this.v1.walkStrength)) ? Direction.BACKWARD : Direction.NONE; } if (Strength.weaker(this.v1.walkStrength, this.v2.walkStrength)) { this.direction = Strength.stronger(this.strength, this.v1.walkStrength) ? Direction.BACKWARD : Direction.NONE; } else { this.direction = Strength.stronger(this.strength, this.v2.walkStrength) ? Direction.FORWARD : Direction.BACKWARD } } /** * Add this constraint to the constraint graph */ BinaryConstraint.prototype.addToGraph = function () { this.v1.addConstraint(this); this.v2.addConstraint(this); this.direction = Direction.NONE; } /** * Answer true if this constraint is satisfied in the current solution. */ BinaryConstraint.prototype.isSatisfied = function () { return this.direction != Direction.NONE; } /** * Mark the input variable with the given mark. */ BinaryConstraint.prototype.markInputs = function (mark) { this.input().mark = mark; } /** * Returns the current input variable */ BinaryConstraint.prototype.input = function () { return (this.direction == Direction.FORWARD) ? this.v1 : this.v2; } /** * Returns the current output variable */ BinaryConstraint.prototype.output = function () { return (this.direction == Direction.FORWARD) ? this.v2 : this.v1; } /** * Calculate the walkabout strength, the stay flag, and, if it is * 'stay', the value for the current output of this * constraint. Assume this constraint is satisfied. */ BinaryConstraint.prototype.recalculate = function () { var ihn = this.input(), out = this.output(); out.walkStrength = Strength.weakestOf(this.strength, ihn.walkStrength); out.stay = ihn.stay; if (out.stay) this.execute(); } /** * Record the fact that this constraint is unsatisfied. */ BinaryConstraint.prototype.markUnsatisfied = function () { this.direction = Direction.NONE; } BinaryConstraint.prototype.inputsKnown = function (mark) { var i = this.input(); return i.mark == mark || i.stay || i.determinedBy == null; } BinaryConstraint.prototype.removeFromGraph = function () { if (this.v1 != null) this.v1.removeConstraint(this); if (this.v2 != null) this.v2.removeConstraint(this); this.direction = Direction.NONE; } /* --- * * S c a l e C o n s t r a i n t * --- */ /** * Relates two variables by the linear scaling relationship: "v2 = * (v1 * scale) + offset". Either v1 or v2 may be changed to maintain * this relationship but the scale factor and offset are considered * read-only. */ function ScaleConstraint(src, scale, offset, dest, strength) { this.direction = Direction.NONE; this.scale = scale; this.offset = offset; ScaleConstraint.superConstructor.call(this, src, dest, strength); } ScaleConstraint.inherits(BinaryConstraint); /** * Adds this constraint to the constraint graph. */ ScaleConstraint.prototype.addToGraph = function () { ScaleConstraint.superConstructor.prototype.addToGraph.call(this); this.scale.addConstraint(this); this.offset.addConstraint(this); } ScaleConstraint.prototype.removeFromGraph = function () { ScaleConstraint.superConstructor.prototype.removeFromGraph.call(this); if (this.scale != null) this.scale.removeConstraint(this); if (this.offset != null) this.offset.removeConstraint(this); } ScaleConstraint.prototype.markInputs = function (mark) { ScaleConstraint.superConstructor.prototype.markInputs.call(this, mark); this.scale.mark = this.offset.mark = mark; } /** * Enforce this constraint. Assume that it is satisfied. */ ScaleConstraint.prototype.execute = function () { if (this.direction == Direction.FORWARD) { this.v2.value = this.v1.value * this.scale.value + this.offset.value; } else { this.v1.value = (this.v2.value - this.offset.value) / this.scale.value; } } /** * Calculate the walkabout strength, the stay flag, and, if it is * 'stay', the value for the current output of this constraint. Assume * this constraint is satisfied. */ ScaleConstraint.prototype.recalculate = function () { var ihn = this.input(), out = this.output(); out.walkStrength = Strength.weakestOf(this.strength, ihn.walkStrength); out.stay = ihn.stay && this.scale.stay && this.offset.stay; if (out.stay) this.execute(); } /* --- * * E q u a l i t y C o n s t r a i n t * --- */ /** * Constrains two variables to have the same value. */ function EqualityConstraint(var1, var2, strength) { EqualityConstraint.superConstructor.call(this, var1, var2, strength); } EqualityConstraint.inherits(BinaryConstraint); /** * Enforce this constraint. Assume that it is satisfied. */ EqualityConstraint.prototype.execute = function () { this.output().value = this.input().value; } /* --- * * V a r i a b l e * --- */ /** * A constrained variable. In addition to its value, it maintain the * structure of the constraint graph, the current dataflow graph, and * various parameters of interest to the DeltaBlue incremental * constraint solver. **/ function Variable(name, initialValue) { this.value = initialValue || 0; this.constraints = new OrderedCollection(); this.determinedBy = null; this.mark = 0; this.walkStrength = Strength.WEAKEST; this.stay = true; this.name = name; } /** * Add the given constraint to the set of all constraints that refer * this variable. */ Variable.prototype.addConstraint = function (c) { this.constraints.add(c); } /** * Removes all traces of c from this variable. */ Variable.prototype.removeConstraint = function (c) { this.constraints.remove(c); if (this.determinedBy == c) this.determinedBy = null; } /* --- * * P l a n n e r * --- */ /** * The DeltaBlue planner */ function Planner() { this.currentMark = 0; } /** * Attempt to satisfy the given constraint and, if successful, * incrementally update the dataflow graph. Details: If satifying * the constraint is successful, it may override a weaker constraint * on its output. The algorithm attempts to resatisfy that * constraint using some other method. This process is repeated * until either a) it reaches a variable that was not previously * determined by any constraint or b) it reaches a constraint that * is too weak to be satisfied using any of its methods. The * variables of constraints that have been processed are marked with * a unique mark value so that we know where we've been. This allows * the algorithm to avoid getting into an infinite loop even if the * constraint graph has an inadvertent cycle. */ Planner.prototype.incrementalAdd = function (c) { var mark = this.newMark(); var overridden = c.satisfy(mark); while (overridden != null) overridden = overridden.satisfy(mark); } /** * Entry point for retracting a constraint. Remove the given * constraint and incrementally update the dataflow graph. * Details: Retracting the given constraint may allow some currently * unsatisfiable downstream constraint to be satisfied. We therefore collect * a list of unsatisfied downstream constraints and attempt to * satisfy each one in turn. This list is traversed by constraint * strength, strongest first, as a heuristic for avoiding * unnecessarily adding and then overriding weak constraints. * Assume: c is satisfied. */ Planner.prototype.incrementalRemove = function (c) { var out = c.output(); c.markUnsatisfied(); c.removeFromGraph(); var unsatisfied = this.removePropagateFrom(out); var strength = Strength.REQUIRED; do { for (var i = 0; i < unsatisfied.size(); i++) { var u = unsatisfied.at(i); if (u.strength == strength) this.incrementalAdd(u); } strength = strength.nextWeaker(); } while (strength != Strength.WEAKEST); } /** * Select a previously unused mark value. */ Planner.prototype.newMark = function () { return ++this.currentMark; } /** * Extract a plan for resatisfaction starting from the given source * constraints, usually a set of input constraints. This method * assumes that stay optimization is desired; the plan will contain * only constraints whose output variables are not stay. Constraints * that do no computation, such as stay and edit constraints, are * not included in the plan. * Details: The outputs of a constraint are marked when it is added * to the plan under construction. A constraint may be appended to * the plan when all its input variables are known. A variable is * known if either a) the variable is marked (indicating that has * been computed by a constraint appearing earlier in the plan), b) * the variable is 'stay' (i.e. it is a constant at plan execution * time), or c) the variable is not determined by any * constraint. The last provision is for past states of history * variables, which are not stay but which are also not computed by * any constraint. * Assume: sources are all satisfied. */ Planner.prototype.makePlan = function (sources) { var mark = this.newMark(); var plan = new Plan(); var todo = sources; while (todo.size() > 0) { var c = todo.removeFirst(); if (c.output().mark != mark && c.inputsKnown(mark)) { plan.addConstraint(c); c.output().mark = mark; this.addConstraintsConsumingTo(c.output(), todo); } } return plan; } /** * Extract a plan for resatisfying starting from the output of the * given constraints, usually a set of input constraints. */ Planner.prototype.extractPlanFromConstraints = function (constraints) { var sources = new OrderedCollection(); for (var i = 0; i < constraints.size(); i++) { var c = constraints.at(i); if (c.isInput() && c.isSatisfied()) // not in plan already and eligible for inclusion sources.add(c); } return this.makePlan(sources); } /** * Recompute the walkabout strengths and stay flags of all variables * downstream of the given constraint and recompute the actual * values of all variables whose stay flag is true. If a cycle is * detected, remove the given constraint and answer * false. Otherwise, answer true. * Details: Cycles are detected when a marked variable is * encountered downstream of the given constraint. The sender is * assumed to have marked the inputs of the given constraint with * the given mark. Thus, encountering a marked node downstream of * the output constraint means that there is a path from the * constraint's output to one of its inputs. */ Planner.prototype.addPropagate = function (c, mark) { var todo = new OrderedCollection(); todo.add(c); while (todo.size() > 0) { var d = todo.removeFirst(); if (d.output().mark == mark) { this.incrementalRemove(c); return false; } d.recalculate(); this.addConstraintsConsumingTo(d.output(), todo); } return true; } /** * Update the walkabout strengths and stay flags of all variables * downstream of the given constraint. Answer a collection of * unsatisfied constraints sorted in order of decreasing strength. */ Planner.prototype.removePropagateFrom = function (out) { out.determinedBy = null; out.walkStrength = Strength.WEAKEST; out.stay = true; var unsatisfied = new OrderedCollection(); var todo = new OrderedCollection(); todo.add(out); while (todo.size() > 0) { var v = todo.removeFirst(); for (var i = 0; i < v.constraints.size(); i++) { var c = v.constraints.at(i); if (!c.isSatisfied()) unsatisfied.add(c); } var determining = v.determinedBy; for (var i = 0; i < v.constraints.size(); i++) { var next = v.constraints.at(i); if (next != determining && next.isSatisfied()) { next.recalculate(); todo.add(next.output()); } } } return unsatisfied; } Planner.prototype.addConstraintsConsumingTo = function (v, coll) { var determining = v.determinedBy; var cc = v.constraints; for (var i = 0; i < cc.size(); i++) { var c = cc.at(i); if (c != determining && c.isSatisfied()) coll.add(c); } } /* --- * * P l a n * --- */ /** * A Plan is an ordered list of constraints to be executed in sequence * to resatisfy all currently satisfiable constraints in the face of * one or more changing inputs. */ function Plan() { this.v = new OrderedCollection(); } Plan.prototype.addConstraint = function (c) { this.v.add(c); } Plan.prototype.size = function () { return this.v.size(); } Plan.prototype.constraintAt = function (index) { return this.v.at(index); } Plan.prototype.execute = function () { for (var i = 0; i < this.size(); i++) { var c = this.constraintAt(i); c.execute(); } } /* --- * * M a i n * --- */ /** * This is the standard DeltaBlue benchmark. A long chain of equality * constraints is constructed with a stay constraint on one end. An * edit constraint is then added to the opposite end and the time is * measured for adding and removing this constraint, and extracting * and executing a constraint satisfaction plan. There are two cases. * In case 1, the added constraint is stronger than the stay * constraint and values must propagate down the entire length of the * chain. In case 2, the added constraint is weaker than the stay * constraint so it cannot be accomodated. The cost in this case is, * of course, very low. Typical situations lie somewhere between these * two extremes. */ function chainTest(n) { planner = new Planner(); var prev = null, first = null, last = null; // Build chain of n equality constraints for (var i = 0; i <= n; i++) { var name = "v" + i; var v = new Variable(name); if (prev != null) new EqualityConstraint(prev, v, Strength.REQUIRED); if (i == 0) first = v; if (i == n) last = v; prev = v; } new StayConstraint(last, Strength.STRONG_DEFAULT); var edit = new EditConstraint(first, Strength.PREFERRED); var edits = new OrderedCollection(); edits.add(edit); var plan = planner.extractPlanFromConstraints(edits); for (var i = 0; i < 100; i++) { first.value = i; plan.execute(); if (last.value != i) alert("Chain test failed."); } } /** * This test constructs a two sets of variables related to each * other by a simple linear transformation (scale and offset). The * time is measured to change a variable on either side of the * mapping and to change the scale and offset factors. */ function projectionTest(n) { planner = new Planner(); var scale = new Variable("scale", 10); var offset = new Variable("offset", 1000); var src = null, dst = null; var dests = new OrderedCollection(); for (var i = 0; i < n; i++) { src = new Variable("src" + i, i); dst = new Variable("dst" + i, i); dests.add(dst); new StayConstraint(src, Strength.NORMAL); new ScaleConstraint(src, scale, offset, dst, Strength.REQUIRED); } change(src, 17); if (dst.value != 1170) alert("Projection 1 failed"); change(dst, 1050); if (src.value != 5) alert("Projection 2 failed"); change(scale, 5); for (var i = 0; i < n - 1; i++) { if (dests.at(i).value != i * 5 + 1000) alert("Projection 3 failed"); } change(offset, 2000); for (var i = 0; i < n - 1; i++) { if (dests.at(i).value != i * 5 + 2000) alert("Projection 4 failed"); } } function change(v, newValue) { var edit = new EditConstraint(v, Strength.PREFERRED); var edits = new OrderedCollection(); edits.add(edit); var plan = planner.extractPlanFromConstraints(edits); for (var i = 0; i < 10; i++) { v.value = newValue; plan.execute(); } edit.destroyConstraint(); } // Global variable holding the current planner. var planner = null; function deltaBlue() { chainTest(100); projectionTest(100); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/benchmarks/v8/base.js0000644000175000017500000002114011314263504030317 0ustar jamespagejamespage00000000000000// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Simple framework for running the benchmark suites and // computing a score based on the timing measurements. // A benchmark has a name (string) and a function that will be run to // do the performance measurement. The optional setup and tearDown // arguments are functions that will be invoked before and after // running the benchmark, but the running time of these functions will // not be accounted for in the benchmark score. function Benchmark(name, run, setup, tearDown) { this.name = name; this.run = run; this.Setup = setup ? setup : function() { }; this.TearDown = tearDown ? tearDown : function() { }; } // Benchmark results hold the benchmark and the measured time used to // run the benchmark. The benchmark score is computed later once a // full benchmark suite has run to completion. function BenchmarkResult(benchmark, time) { this.benchmark = benchmark; this.time = time; } // Automatically convert results to numbers. Used by the geometric // mean computation. BenchmarkResult.prototype.valueOf = function() { return this.time; } // Suites of benchmarks consist of a name and the set of benchmarks in // addition to the reference timing that the final score will be based // on. This way, all scores are relative to a reference run and higher // scores implies better performance. function BenchmarkSuite(name, reference, benchmarks) { this.name = name; this.reference = reference; this.benchmarks = benchmarks; BenchmarkSuite.suites.push(this); } // Keep track of all declared benchmark suites. BenchmarkSuite.suites = []; // Scores are not comparable across versions. Bump the version if // you're making changes that will affect that scores, e.g. if you add // a new benchmark or change an existing one. BenchmarkSuite.version = '4'; // To make the benchmark results predictable, we replace Math.random // with a 100% deterministic alternative. Math.random = (function() { var seed = 49734321; return function() { // Robert Jenkins' 32 bit integer hash function. seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff; seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff; seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff; seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff; seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff; seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff; seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff; return (seed & 0xfffffff) / 0x10000000; }; })(); // Runs all registered benchmark suites and optionally yields between // each individual benchmark to avoid running for too long in the // context of browsers. Once done, the final score is reported to the // runner. BenchmarkSuite.RunSuites = function(runner) { var continuation = null; var suites = BenchmarkSuite.suites; var length = suites.length; BenchmarkSuite.scores = []; var index = 0; function RunStep() { while (continuation || index < length) { if (continuation) { continuation = continuation(); } else { var suite = suites[index++]; if (runner.NotifyStart) runner.NotifyStart(suite.name); continuation = suite.RunStep(runner); } if (continuation && typeof window != 'undefined' && window.setTimeout) { window.setTimeout(RunStep, 25); return; } } if (runner.NotifyScore) { var score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores); var formatted = BenchmarkSuite.FormatScore(100 * score); runner.NotifyScore(formatted); } } RunStep(); } // Counts the total number of registered benchmarks. Useful for // showing progress as a percentage. BenchmarkSuite.CountBenchmarks = function() { var result = 0; var suites = BenchmarkSuite.suites; for (var i = 0; i < suites.length; i++) { result += suites[i].benchmarks.length; } return result; } // Computes the geometric mean of a set of numbers. BenchmarkSuite.GeometricMean = function(numbers) { var log = 0; for (var i = 0; i < numbers.length; i++) { log += Math.log(numbers[i]); } return Math.pow(Math.E, log / numbers.length); } // Converts a score value to a string with at least three significant // digits. BenchmarkSuite.FormatScore = function(value) { if (value > 100) { return value.toFixed(0); } else { return value.toPrecision(3); } } // Notifies the runner that we're done running a single benchmark in // the benchmark suite. This can be useful to report progress. BenchmarkSuite.prototype.NotifyStep = function(result) { this.results.push(result); if (this.runner.NotifyStep) this.runner.NotifyStep(result.benchmark.name); } // Notifies the runner that we're done with running a suite and that // we have a result which can be reported to the user if needed. BenchmarkSuite.prototype.NotifyResult = function() { var mean = BenchmarkSuite.GeometricMean(this.results); var score = this.reference / mean; BenchmarkSuite.scores.push(score); if (this.runner.NotifyResult) { var formatted = BenchmarkSuite.FormatScore(100 * score); this.runner.NotifyResult(this.name, formatted); } } // Notifies the runner that running a benchmark resulted in an error. BenchmarkSuite.prototype.NotifyError = function(error) { if (this.runner.NotifyError) { this.runner.NotifyError(this.name, error); } if (this.runner.NotifyStep) { this.runner.NotifyStep(this.name); } } // Runs a single benchmark for at least a second and computes the // average time it takes to run a single iteration. BenchmarkSuite.prototype.RunSingleBenchmark = function(benchmark) { var elapsed = 0; var start = new Date(); for (var n = 0; elapsed < 1000; n++) { benchmark.run(); elapsed = new Date() - start; } var usec = (elapsed * 1000) / n; this.NotifyStep(new BenchmarkResult(benchmark, usec)); } // This function starts running a suite, but stops between each // individual benchmark in the suite and returns a continuation // function which can be invoked to run the next benchmark. Once the // last benchmark has been executed, null is returned. BenchmarkSuite.prototype.RunStep = function(runner) { this.results = []; this.runner = runner; var length = this.benchmarks.length; var index = 0; var suite = this; // Run the setup, the actual benchmark, and the tear down in three // separate steps to allow the framework to yield between any of the // steps. function RunNextSetup() { if (index < length) { try { suite.benchmarks[index].Setup(); } catch (e) { suite.NotifyError(e); return null; } return RunNextBenchmark; } suite.NotifyResult(); return null; } function RunNextBenchmark() { try { suite.RunSingleBenchmark(suite.benchmarks[index]); } catch (e) { suite.NotifyError(e); return null; } return RunNextTearDown; } function RunNextTearDown() { try { suite.benchmarks[index++].TearDown(); } catch (e) { suite.NotifyError(e); return null; } return RunNextSetup; } // Start out running the setup. return RunNextSetup(); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/benchmarks/v8/regexp.js0000644000175000017500000031612511314263504030711 0ustar jamespagejamespage00000000000000// Copyright 2009 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Automatically generated on 2009-01-30. // This benchmark is generated by loading 50 of the most popular pages // on the web and logging all regexp operations performed. Each // operation is given a weight that is calculated from an estimate of // the popularity of the pages where it occurs and the number of times // it is executed while loading each page. Finally the literal // letters in the data are encoded using ROT13 in a way that does not // affect how the regexps match their input. var RegRxp = new BenchmarkSuite('RegExp', 995230, [ new Benchmark("RegExp", runRegExpBenchmark) ]); function runRegExpBenchmark() { var re0 = /^ba/; var re1 = /(((\w+):\/\/)([^\/:]*)(:(\d+))?)?([^#?]*)(\?([^#]*))?(#(.*))?/; var re2 = /^\s*|\s*$/g; var re3 = /\bQBZPbageby_cynprubyqre\b/; var re4 = /,/; var re5 = /\bQBZPbageby_cynprubyqre\b/g; var re6 = /^[\s\xa0]+|[\s\xa0]+$/g; var re7 = /(\d*)(\D*)/g; var re8 = /=/; var re9 = /(^|\s)lhv\-h(\s|$)/; var str0 = 'Zbmvyyn/5.0 (Jvaqbjf; H; Jvaqbjf AG 5.1; ra-HF) NccyrJroXvg/528.9 (XUGZY, yvxr Trpxb) Puebzr/2.0.157.0 Fnsnev/528.9'; var re10 = /\#/g; var re11 = /\./g; var re12 = /'/g; var re13 = /\?[\w\W]*(sevraqvq|punaaryvq|tebhcvq)=([^\&\?#]*)/i; var str1 = 'Fubpxjnir Synfu 9.0 e115'; var re14 = /\s+/g; var re15 = /^\s*(\S*(\s+\S+)*)\s*$/; var re16 = /(-[a-z])/i; function runBlock0() { for (var i = 0; i < 6511; i++) { re0.exec('pyvpx'); } for (var i = 0; i < 1844; i++) { re1.exec('uggc://jjj.snprobbx.pbz/ybtva.cuc'); } for (var i = 0; i < 739; i++) { 'QBZPbageby_cynprubyqre'.replace(re2, ''); } for (var i = 0; i < 598; i++) { re1.exec('uggc://jjj.snprobbx.pbz/'); } for (var i = 0; i < 454; i++) { re1.exec('uggc://jjj.snprobbx.pbz/fepu.cuc'); } for (var i = 0; i < 352; i++) { /qqqq|qqq|qq|q|ZZZZ|ZZZ|ZZ|Z|llll|ll|l|uu|u|UU|U|zz|z|ff|f|gg|g|sss|ss|s|mmm|mm|m/g.exec('qqqq, ZZZ q, llll'); } for (var i = 0; i < 312; i++) { re3.exec('vachggrkg QBZPbageby_cynprubyqre'); } for (var i = 0; i < 282; i++) { re4.exec('/ZlFcnprUbzrcntr/Vaqrk-FvgrUbzr,10000000'); } for (var i = 0; i < 177; i++) { 'vachggrkg'.replace(re5, ''); } for (var i = 0; i < 170; i++) { '528.9'.replace(re6, ''); re7.exec('528'); } for (var i = 0; i < 156; i++) { re8.exec('VCPhygher=ra-HF'); re8.exec('CersreerqPhygher=ra-HF'); } for (var i = 0; i < 144; i++) { re0.exec('xrlcerff'); } for (var i = 0; i < 139; i++) { '521'.replace(re6, ''); re7.exec('521'); re9.exec(''); /JroXvg\/(\S+)/.exec(str0); } for (var i = 0; i < 137; i++) { 'qvi .so_zrah'.replace(re10, ''); 'qvi .so_zrah'.replace(/\[/g, ''); 'qvi.so_zrah'.replace(re11, ''); } for (var i = 0; i < 117; i++) { 'uvqqra_ryrz'.replace(re2, ''); } for (var i = 0; i < 95; i++) { /(?:^|;)\s*sevraqfgre_ynat=([^;]*)/.exec('sevraqfgre_naba=nvq%3Qn6ss9p85n868ro9s059pn854735956o3%26ers%3Q%26df%3Q%26vpgl%3QHF'); } for (var i = 0; i < 93; i++) { 'uggc://ubzr.zlfcnpr.pbz/vaqrk.psz'.replace(re12, ''); re13.exec('uggc://ubzr.zlfcnpr.pbz/vaqrk.psz'); } for (var i = 0; i < 92; i++) { str1.replace(/([a-zA-Z]|\s)+/, ''); } for (var i = 0; i < 85; i++) { 'svefg'.replace(re14, ''); 'svefg'.replace(re15, ''); 'uggc://cebsvyr.zlfcnpr.pbz/vaqrk.psz'.replace(re12, ''); 'ynfg'.replace(re14, ''); 'ynfg'.replace(re15, ''); re16.exec('qvfcynl'); re13.exec('uggc://cebsvyr.zlfcnpr.pbz/vaqrk.psz'); } } var re17 = /(^|[^\\])\"\\\/Qngr\((-?[0-9]+)\)\\\/\"/g; var str2 = '{"anzr":"","ahzoreSbezng":{"PheeraplQrpvznyQvtvgf":2,"PheeraplQrpvznyFrcnengbe":".","VfErnqBayl":gehr,"PheeraplTebhcFvmrf":[3],"AhzoreTebhcFvmrf":[3],"CrepragTebhcFvmrf":[3],"PheeraplTebhcFrcnengbe":",","PheeraplFlzoby":"\xa4","AnAFlzoby":"AnA","PheeraplArtngvirCnggrea":0,"AhzoreArtngvirCnggrea":1,"CrepragCbfvgvirCnggrea":0,"CrepragArtngvirCnggrea":0,"ArtngvirVasvavglFlzoby":"-Vasvavgl","ArtngvirFvta":"-","AhzoreQrpvznyQvtvgf":2,"AhzoreQrpvznyFrcnengbe":".","AhzoreTebhcFrcnengbe":",","PheeraplCbfvgvirCnggrea":0,"CbfvgvirVasvavglFlzoby":"Vasvavgl","CbfvgvirFvta":"+","CrepragQrpvznyQvtvgf":2,"CrepragQrpvznyFrcnengbe":".","CrepragTebhcFrcnengbe":",","CrepragFlzoby":"%","CreZvyyrFlzoby":"\u2030","AngvirQvtvgf":["0","1","2","3","4","5","6","7","8","9"],"QvtvgFhofgvghgvba":1},"qngrGvzrSbezng":{"NZQrfvtangbe":"NZ","Pnyraqne":{"ZvaFhccbegrqQngrGvzr":"@-62135568000000@","ZnkFhccbegrqQngrGvzr":"@253402300799999@","NytbevguzGlcr":1,"PnyraqneGlcr":1,"Renf":[1],"GjbQvtvgLrneZnk":2029,"VfErnqBayl":gehr},"QngrFrcnengbe":"/","SvefgQnlBsJrrx":0,"PnyraqneJrrxEhyr":0,"ShyyQngrGvzrCnggrea":"qqqq, qq ZZZZ llll UU:zz:ff","YbatQngrCnggrea":"qqqq, qq ZZZZ llll","YbatGvzrCnggrea":"UU:zz:ff","ZbaguQnlCnggrea":"ZZZZ qq","CZQrfvtangbe":"CZ","ESP1123Cnggrea":"qqq, qq ZZZ llll UU\':\'zz\':\'ff \'TZG\'","FubegQngrCnggrea":"ZZ/qq/llll","FubegGvzrCnggrea":"UU:zz","FbegnoyrQngrGvzrCnggrea":"llll\'-\'ZZ\'-\'qq\'G\'UU\':\'zz\':\'ff","GvzrFrcnengbe":":","HavirefnyFbegnoyrQngrGvzrCnggrea":"llll\'-\'ZZ\'-\'qq UU\':\'zz\':\'ff\'M\'","LrneZbaguCnggrea":"llll ZZZZ","NooerivngrqQnlAnzrf":["Fha","Zba","Ghr","Jrq","Guh","Sev","Fng"],"FubegrfgQnlAnzrf":["Fh","Zb","Gh","Jr","Gu","Se","Fn"],"QnlAnzrf":["Fhaqnl","Zbaqnl","Ghrfqnl","Jrqarfqnl","Guhefqnl","Sevqnl","Fngheqnl"],"NooerivngrqZbaguAnzrf":["Wna","Sro","Zne","Nce","Znl","Wha","Why","Nht","Frc","Bpg","Abi","Qrp",""],"ZbaguAnzrf":["Wnahnel","Sroehnel","Znepu","Ncevy","Znl","Whar","Whyl","Nhthfg","Frcgrzore","Bpgbore","Abirzore","Qrprzore",""],"VfErnqBayl":gehr,"AngvirPnyraqneAnzr":"Tertbevna Pnyraqne","NooerivngrqZbaguTravgvirAnzrf":["Wna","Sro","Zne","Nce","Znl","Wha","Why","Nht","Frc","Bpg","Abi","Qrp",""],"ZbaguTravgvirAnzrf":["Wnahnel","Sroehnel","Znepu","Ncevy","Znl","Whar","Whyl","Nhthfg","Frcgrzore","Bpgbore","Abirzore","Qrprzore",""]}}'; var str3 = '{"anzr":"ra-HF","ahzoreSbezng":{"PheeraplQrpvznyQvtvgf":2,"PheeraplQrpvznyFrcnengbe":".","VfErnqBayl":snyfr,"PheeraplTebhcFvmrf":[3],"AhzoreTebhcFvmrf":[3],"CrepragTebhcFvmrf":[3],"PheeraplTebhcFrcnengbe":",","PheeraplFlzoby":"$","AnAFlzoby":"AnA","PheeraplArtngvirCnggrea":0,"AhzoreArtngvirCnggrea":1,"CrepragCbfvgvirCnggrea":0,"CrepragArtngvirCnggrea":0,"ArtngvirVasvavglFlzoby":"-Vasvavgl","ArtngvirFvta":"-","AhzoreQrpvznyQvtvgf":2,"AhzoreQrpvznyFrcnengbe":".","AhzoreTebhcFrcnengbe":",","PheeraplCbfvgvirCnggrea":0,"CbfvgvirVasvavglFlzoby":"Vasvavgl","CbfvgvirFvta":"+","CrepragQrpvznyQvtvgf":2,"CrepragQrpvznyFrcnengbe":".","CrepragTebhcFrcnengbe":",","CrepragFlzoby":"%","CreZvyyrFlzoby":"\u2030","AngvirQvtvgf":["0","1","2","3","4","5","6","7","8","9"],"QvtvgFhofgvghgvba":1},"qngrGvzrSbezng":{"NZQrfvtangbe":"NZ","Pnyraqne":{"ZvaFhccbegrqQngrGvzr":"@-62135568000000@","ZnkFhccbegrqQngrGvzr":"@253402300799999@","NytbevguzGlcr":1,"PnyraqneGlcr":1,"Renf":[1],"GjbQvtvgLrneZnk":2029,"VfErnqBayl":snyfr},"QngrFrcnengbe":"/","SvefgQnlBsJrrx":0,"PnyraqneJrrxEhyr":0,"ShyyQngrGvzrCnggrea":"qqqq, ZZZZ qq, llll u:zz:ff gg","YbatQngrCnggrea":"qqqq, ZZZZ qq, llll","YbatGvzrCnggrea":"u:zz:ff gg","ZbaguQnlCnggrea":"ZZZZ qq","CZQrfvtangbe":"CZ","ESP1123Cnggrea":"qqq, qq ZZZ llll UU\':\'zz\':\'ff \'TZG\'","FubegQngrCnggrea":"Z/q/llll","FubegGvzrCnggrea":"u:zz gg","FbegnoyrQngrGvzrCnggrea":"llll\'-\'ZZ\'-\'qq\'G\'UU\':\'zz\':\'ff","GvzrFrcnengbe":":","HavirefnyFbegnoyrQngrGvzrCnggrea":"llll\'-\'ZZ\'-\'qq UU\':\'zz\':\'ff\'M\'","LrneZbaguCnggrea":"ZZZZ, llll","NooerivngrqQnlAnzrf":["Fha","Zba","Ghr","Jrq","Guh","Sev","Fng"],"FubegrfgQnlAnzrf":["Fh","Zb","Gh","Jr","Gu","Se","Fn"],"QnlAnzrf":["Fhaqnl","Zbaqnl","Ghrfqnl","Jrqarfqnl","Guhefqnl","Sevqnl","Fngheqnl"],"NooerivngrqZbaguAnzrf":["Wna","Sro","Zne","Nce","Znl","Wha","Why","Nht","Frc","Bpg","Abi","Qrp",""],"ZbaguAnzrf":["Wnahnel","Sroehnel","Znepu","Ncevy","Znl","Whar","Whyl","Nhthfg","Frcgrzore","Bpgbore","Abirzore","Qrprzore",""],"VfErnqBayl":snyfr,"AngvirPnyraqneAnzr":"Tertbevna Pnyraqne","NooerivngrqZbaguTravgvirAnzrf":["Wna","Sro","Zne","Nce","Znl","Wha","Why","Nht","Frc","Bpg","Abi","Qrp",""],"ZbaguTravgvirAnzrf":["Wnahnel","Sroehnel","Znepu","Ncevy","Znl","Whar","Whyl","Nhthfg","Frcgrzore","Bpgbore","Abirzore","Qrprzore",""]}}'; var str4 = 'HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str5 = 'HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; var re18 = /^\s+|\s+$/g; var str6 = 'uggc://jjj.snprobbx.pbz/vaqrk.cuc'; var re19 = /(?:^|\s+)ba(?:\s+|$)/; var re20 = /[+, ]/; var re21 = /ybnqrq|pbzcyrgr/; var str7 = ';;jvaqbj.IjPurpxZbhfrCbfvgvbaNQ_VQ=shapgvba(r){vs(!r)ine r=jvaqbj.rirag;ine c=-1;vs(d1)c=d1.EbyybssCnary;ine bo=IjTrgBow("IjCnayNQ_VQ_"+c);vs(bo&&bo.fglyr.ivfvovyvgl=="ivfvoyr"){ine fns=IjFns?8:0;ine pheK=r.pyvragK+IjBOFpe("U")+fns,pheL=r.pyvragL+IjBOFpe("I")+fns;ine y=IjBOEC(NQ_VQ,bo,"Y"),g=IjBOEC(NQ_VQ,bo,"G");ine e=y+d1.Cnaryf[c].Jvqgu,o=g+d1.Cnaryf[c].Urvtug;vs((pheKe)||(pheLo)){vs(jvaqbj.IjBaEbyybssNQ_VQ)IjBaEbyybssNQ_VQ(c);ryfr IjPybfrNq(NQ_VQ,c,gehr,"");}ryfr erghea;}IjPnapryZbhfrYvfgrareNQ_VQ();};;jvaqbj.IjFrgEbyybssCnaryNQ_VQ=shapgvba(c){ine z="zbhfrzbir",q=qbphzrag,s=IjPurpxZbhfrCbfvgvbaNQ_VQ;c=IjTc(NQ_VQ,c);vs(d1&&d1.EbyybssCnary>-1)IjPnapryZbhfrYvfgrareNQ_VQ();vs(d1)d1.EbyybssCnary=c;gel{vs(q.nqqRiragYvfgrare)q.nqqRiragYvfgrare(z,s,snyfr);ryfr vs(q.nggnpuRirag)q.nggnpuRirag("ba"+z,s);}pngpu(r){}};;jvaqbj.IjPnapryZbhfrYvfgrareNQ_VQ=shapgvba(){ine z="zbhfrzbir",q=qbphzrag,s=IjPurpxZbhfrCbfvgvbaNQ_VQ;vs(d1)d1.EbyybssCnary=-1;gel{vs(q.erzbirRiragYvfgrare)q.erzbirRiragYvfgrare(z,s,snyfr);ryfr vs(q.qrgnpuRirag)q.qrgnpuRirag("ba"+z,s);}pngpu(r){}};;d1.IjTc=d2(n,c){ine nq=d1;vs(vfAnA(c)){sbe(ine v=0;v0){vs(nq.FzV.yratgu>0)nq.FzV+="/";nq.FzV+=vh[v];nq.FtZ[nq.FtZ.yratgu]=snyfr;}}};;d1.IjYvzvg0=d2(n,f){ine nq=d1,vh=f.fcyvg("/");sbe(ine v=0;v0){vs(nq.OvC.yratgu>0)nq.OvC+="/";nq.OvC+=vh[v];}}};;d1.IjRVST=d2(n,c){jvaqbj["IjCnayNQ_VQ_"+c+"_Bow"]=IjTrgBow("IjCnayNQ_VQ_"+c+"_Bow");vs(jvaqbj["IjCnayNQ_VQ_"+c+"_Bow"]==ahyy)frgGvzrbhg("IjRVST(NQ_VQ,"+c+")",d1.rvsg);};;d1.IjNavzSHC=d2(n,c){ine nq=d1;vs(c>nq.Cnaryf.yratgu)erghea;ine cna=nq.Cnaryf[c],nn=gehr,on=gehr,yn=gehr,en=gehr,cn=nq.Cnaryf[0],sf=nq.ShF,j=cn.Jvqgu,u=cn.Urvtug;vs(j=="100%"){j=sf;en=snyfr;yn=snyfr;}vs(u=="100%"){u=sf;nn=snyfr;on=snyfr;}vs(cn.YnY=="Y")yn=snyfr;vs(cn.YnY=="E")en=snyfr;vs(cn.GnY=="G")nn=snyfr;vs(cn.GnY=="O")on=snyfr;ine k=0,l=0;fjvgpu(nq.NshP%8){pnfr 0:oernx;pnfr 1:vs(nn)l=-sf;oernx;pnfr 2:k=j-sf;oernx;pnfr 3:vs(en)k=j;oernx;pnfr 4:k=j-sf;l=u-sf;oernx;pnfr 5:k=j-sf;vs(on)l=u;oernx;pnfr 6:l=u-sf;oernx;pnfr 7:vs(yn)k=-sf;l=u-sf;oernx;}vs(nq.NshP++ 0)||(nethzragf.yratgu==3&&bG>0))){pyrneGvzrbhg(cay.UgU);cay.UgU=frgGvzrbhg(cay.UvqrNpgvba,(nethzragf.yratgu==3?bG:cay.UvqrGvzrbhgInyhr));}};;d1.IjErfrgGvzrbhg=d2(n,c,bG){c=IjTc(n,c);IjPnapryGvzrbhg(n,c);riny("IjFgnegGvzrbhg(NQ_VQ,c"+(nethzragf.yratgu==3?",bG":"")+")");};;d1.IjErfrgNyyGvzrbhgf=d2(n){sbe(ine c=0;c]/g; var str15 = 'FrffvbaQQS2=s6r4579npn4rn2135s904r0s75pp1o5334p6s6pospo12696; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669316860113296&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R=; AFP_zp_dfctwzs-aowb_80=44132r503660'; var str16 = 'FrffvbaQQS2=s6r4579npn4rn2135s904r0s75pp1o5334p6s6pospo12696; AFP_zp_dfctwzs-aowb_80=44132r503660; __hgzm=144631658.1231363638.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.965867047679498800.1231363638.1231363638.1231363638.1; __hgzo=144631658.0.10.1231363638; __hgzp=144631658; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669316860113296&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str17 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231363621014&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231363621014&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Scebsvyr.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=348699119.1231363624&tn_fvq=1231363624&tn_uvq=895511034&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; var str18 = 'uggc://jjj.yrobapbva.se/yv'; var str19 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669316860113296&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str20 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669316860113296&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; function runBlock3() { for (var i = 0; i < 27; i++) { 'e115'.replace(/[A-Za-z]/g, ''); } for (var i = 0; i < 23; i++) { 'qvfcynl'.replace(re27, ''); 'cbfvgvba'.replace(re27, ''); } for (var i = 0; i < 22; i++) { 'unaqyr'.replace(re14, ''); 'unaqyr'.replace(re15, ''); 'yvar'.replace(re14, ''); 'yvar'.replace(re15, ''); 'cnerag puebzr6 fvatyr1 gno'.replace(re14, ''); 'cnerag puebzr6 fvatyr1 gno'.replace(re15, ''); 'fyvqre'.replace(re14, ''); 'fyvqre'.replace(re15, ''); re28.exec(''); } for (var i = 0; i < 21; i++) { 'uggc://jjj.zlfcnpr.pbz/'.replace(re12, ''); re13.exec('uggc://jjj.zlfcnpr.pbz/'); } for (var i = 0; i < 20; i++) { 'cntrivrj'.replace(re29, ''); 'cntrivrj'.replace(re30, ''); re19.exec('ynfg'); re19.exec('ba svefg'); re8.exec('VC=74.125.75.3'); } for (var i = 0; i < 19; i++) { re31.exec('ra'); } for (var i = 0; i < 18; i++) { str10.split(re32); str11.split(re32); str12.replace(re33, ''); re8.exec('144631658.0.10.1231363570'); re8.exec('144631658.1231363570.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re8.exec('144631658.3426875219718084000.1231363570.1231363570.1231363570.1'); re8.exec(str13); re8.exec(str14); re8.exec('__hgzn=144631658.3426875219718084000.1231363570.1231363570.1231363570.1'); re8.exec('__hgzo=144631658.0.10.1231363570'); re8.exec('__hgzm=144631658.1231363570.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re34.exec(str10); re34.exec(str11); } for (var i = 0; i < 17; i++) { str0.match(/zfvr/gi); str0.match(/bcren/gi); str15.split(re32); str16.split(re32); 'ohggba'.replace(re14, ''); 'ohggba'.replace(re15, ''); 'puvyq p1 svefg sylbhg pybfrq'.replace(re14, ''); 'puvyq p1 svefg sylbhg pybfrq'.replace(re15, ''); 'pvgvrf'.replace(re14, ''); 'pvgvrf'.replace(re15, ''); 'pybfrq'.replace(re14, ''); 'pybfrq'.replace(re15, ''); 'qry'.replace(re14, ''); 'qry'.replace(re15, ''); 'uqy_zba'.replace(re14, ''); 'uqy_zba'.replace(re15, ''); str17.replace(re33, ''); str18.replace(/%3P/g, ''); str18.replace(/%3R/g, ''); str18.replace(/%3q/g, ''); str18.replace(re35, ''); 'yvaxyvfg16'.replace(re14, ''); 'yvaxyvfg16'.replace(re15, ''); 'zvahf'.replace(re14, ''); 'zvahf'.replace(re15, ''); 'bcra'.replace(re14, ''); 'bcra'.replace(re15, ''); 'cnerag puebzr5 fvatyr1 ps NU'.replace(re14, ''); 'cnerag puebzr5 fvatyr1 ps NU'.replace(re15, ''); 'cynlre'.replace(re14, ''); 'cynlre'.replace(re15, ''); 'cyhf'.replace(re14, ''); 'cyhf'.replace(re15, ''); 'cb_uqy'.replace(re14, ''); 'cb_uqy'.replace(re15, ''); 'hyJVzt'.replace(re14, ''); 'hyJVzt'.replace(re15, ''); re8.exec('144631658.0.10.1231363638'); re8.exec('144631658.1231363638.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re8.exec('144631658.965867047679498800.1231363638.1231363638.1231363638.1'); re8.exec('4413268q3660'); re8.exec('4ss747o77904333q374or84qrr1s9r0nprp8r5q81534o94n'); re8.exec('SbeprqRkcvengvba=633669321699093060'); re8.exec('VC=74.125.75.20'); re8.exec(str19); re8.exec(str20); re8.exec('AFP_zp_tfwsbrg-aowb_80=4413268q3660'); re8.exec('FrffvbaQQS2=4ss747o77904333q374or84qrr1s9r0nprp8r5q81534o94n'); re8.exec('__hgzn=144631658.965867047679498800.1231363638.1231363638.1231363638.1'); re8.exec('__hgzo=144631658.0.10.1231363638'); re8.exec('__hgzm=144631658.1231363638.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re34.exec(str15); re34.exec(str16); } } var re36 = /uers|fep|fryrpgrq/; var re37 = /\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g; var re38 = /^(\w+|\*)$/; var str21 = 'FrffvbaQQS2=s15q53p9n372sn76npr13o271n4s3p5r29p235746p908p58; ZFPhygher=VC=66.249.85.130&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669358527244818&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; var str22 = 'FrffvbaQQS2=s15q53p9n372sn76npr13o271n4s3p5r29p235746p908p58; __hgzm=144631658.1231367822.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.4127520630321984500.1231367822.1231367822.1231367822.1; __hgzo=144631658.0.10.1231367822; __hgzp=144631658; ZFPhygher=VC=66.249.85.130&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669358527244818&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str23 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231367803797&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231367803797&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Szrffntvat.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=1192552091.1231367807&tn_fvq=1231367807&tn_uvq=1155446857&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; var str24 = 'ZFPhygher=VC=66.249.85.130&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669358527244818&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str25 = 'ZFPhygher=VC=66.249.85.130&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669358527244818&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; var str26 = 'hy.ynat-fryrpgbe'; var re39 = /\\/g; var re40 = / /g; var re41 = /\/\xc4\/t/; var re42 = /\/\xd6\/t/; var re43 = /\/\xdc\/t/; var re44 = /\/\xdf\/t/; var re45 = /\/\xe4\/t/; var re46 = /\/\xf6\/t/; var re47 = /\/\xfc\/t/; var re48 = /\W/g; var re49 = /uers|fep|fglyr/; function runBlock4() { for (var i = 0; i < 16; i++) { ''.replace(/\*/g, ''); /\bnpgvir\b/.exec('npgvir'); /sversbk/i.exec(str0); re36.exec('glcr'); /zfvr/i.exec(str0); /bcren/i.exec(str0); } for (var i = 0; i < 15; i++) { str21.split(re32); str22.split(re32); 'uggc://ohyyrgvaf.zlfcnpr.pbz/vaqrk.psz'.replace(re12, ''); str23.replace(re33, ''); 'yv'.replace(re37, ''); 'yv'.replace(re18, ''); re8.exec('144631658.0.10.1231367822'); re8.exec('144631658.1231367822.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re8.exec('144631658.4127520630321984500.1231367822.1231367822.1231367822.1'); re8.exec(str24); re8.exec(str25); re8.exec('__hgzn=144631658.4127520630321984500.1231367822.1231367822.1231367822.1'); re8.exec('__hgzo=144631658.0.10.1231367822'); re8.exec('__hgzm=144631658.1231367822.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re34.exec(str21); re34.exec(str22); /\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)["']?(.*?)["']?)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g.exec(str26); re13.exec('uggc://ohyyrgvaf.zlfcnpr.pbz/vaqrk.psz'); re38.exec('yv'); } for (var i = 0; i < 14; i++) { ''.replace(re18, ''); '9.0 e115'.replace(/(\s+e|\s+o[0-9]+)/, ''); 'Funer guvf tnqtrg'.replace(//g, ''); 'Funer guvf tnqtrg'.replace(re39, ''); 'uggc://cebsvyrrqvg.zlfcnpr.pbz/vaqrk.psz'.replace(re12, ''); 'grnfre'.replace(re40, ''); 'grnfre'.replace(re41, ''); 'grnfre'.replace(re42, ''); 'grnfre'.replace(re43, ''); 'grnfre'.replace(re44, ''); 'grnfre'.replace(re45, ''); 'grnfre'.replace(re46, ''); 'grnfre'.replace(re47, ''); 'grnfre'.replace(re48, ''); re16.exec('znetva-gbc'); re16.exec('cbfvgvba'); re19.exec('gno1'); re9.exec('qz'); re9.exec('qg'); re9.exec('zbqobk'); re9.exec('zbqobkva'); re9.exec('zbqgvgyr'); re13.exec('uggc://cebsvyrrqvg.zlfcnpr.pbz/vaqrk.psz'); re26.exec('/vt/znvytnqtrg'); re49.exec('glcr'); } } var re50 = /(?:^|\s+)fryrpgrq(?:\s+|$)/; var re51 = /\&/g; var re52 = /\+/g; var re53 = /\?/g; var re54 = /\t/g; var re55 = /(\$\{nqiHey\})|(\$nqiHey\b)/g; var re56 = /(\$\{cngu\})|(\$cngu\b)/g; function runBlock5() { for (var i = 0; i < 13; i++) { 'purpx'.replace(re14, ''); 'purpx'.replace(re15, ''); 'pvgl'.replace(re14, ''); 'pvgl'.replace(re15, ''); 'qrpe fyvqrgrkg'.replace(re14, ''); 'qrpe fyvqrgrkg'.replace(re15, ''); 'svefg fryrpgrq'.replace(re14, ''); 'svefg fryrpgrq'.replace(re15, ''); 'uqy_rag'.replace(re14, ''); 'uqy_rag'.replace(re15, ''); 'vape fyvqrgrkg'.replace(re14, ''); 'vape fyvqrgrkg'.replace(re15, ''); 'vachggrkg QBZPbageby_cynprubyqre'.replace(re5, ''); 'cnerag puebzr6 fvatyr1 gno fryrpgrq'.replace(re14, ''); 'cnerag puebzr6 fvatyr1 gno fryrpgrq'.replace(re15, ''); 'cb_guz'.replace(re14, ''); 'cb_guz'.replace(re15, ''); 'fhozvg'.replace(re14, ''); 'fhozvg'.replace(re15, ''); re50.exec(''); /NccyrJroXvg\/([^\s]*)/.exec(str0); /XUGZY/.exec(str0); } for (var i = 0; i < 12; i++) { '${cebg}://${ubfg}${cngu}/${dz}'.replace(/(\$\{cebg\})|(\$cebg\b)/g, ''); '1'.replace(re40, ''); '1'.replace(re10, ''); '1'.replace(re51, ''); '1'.replace(re52, ''); '1'.replace(re53, ''); '1'.replace(re39, ''); '1'.replace(re54, ''); '9.0 e115'.replace(/^(.*)\..*$/, ''); '9.0 e115'.replace(/^.*e(.*)$/, ''); ''.replace(re55, ''); ''.replace(re55, ''); str1.replace(/^.*\s+(\S+\s+\S+$)/, ''); 'tzk%2Subzrcntr%2Sfgneg%2Sqr%2S'.replace(re30, ''); 'tzk'.replace(re30, ''); 'uggc://${ubfg}${cngu}/${dz}'.replace(/(\$\{ubfg\})|(\$ubfg\b)/g, ''); 'uggc://nqpyvrag.hvzfrei.arg${cngu}/${dz}'.replace(re56, ''); 'uggc://nqpyvrag.hvzfrei.arg/wf.at/${dz}'.replace(/(\$\{dz\})|(\$dz\b)/g, ''); 'frpgvba'.replace(re29, ''); 'frpgvba'.replace(re30, ''); 'fvgr'.replace(re29, ''); 'fvgr'.replace(re30, ''); 'fcrpvny'.replace(re29, ''); 'fcrpvny'.replace(re30, ''); re36.exec('anzr'); /e/.exec('9.0 e115'); } } var re57 = /##yv4##/gi; var re58 = /##yv16##/gi; var re59 = /##yv19##/gi; var str27 = '##yv4##Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.##yv19##Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.##yv16##Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl.##OE## ##OE## ##N##Yrnea zber##/N##'; var str28 = 'Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.##yv19##Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.##yv16##Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl.##OE## ##OE## ##N##Yrnea zber##/N##'; var str29 = 'Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.##yv19##Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl.##OE## ##OE## ##N##Yrnea zber##/N##'; var str30 = 'Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl.##OE## ##OE## ##N##Yrnea zber##/N##'; var str31 = 'Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl. ##N##Yrnea zber##/N##'; var str32 = 'Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl. Yrnea zber##/N##'; var str33 = 'Bar Jvaqbjf Yvir VQ trgf lbh vagb Ubgznvy, Zrffratre, Kobk YVIR \u2014 naq bgure cynprf lbh frr #~#argjbexybtb#~#'; var re60 = /(?:^|\s+)bss(?:\s+|$)/; var re61 = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/; var re62 = /^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/; var str34 = '${1}://${2}${3}${4}${5}'; var str35 = ' O=6gnyg0g4znrrn&o=3&f=gc; Q=_lyu=K3bQZGSxnT4lZzD3OS9GNmV3ZGLkAQxRpTyxNmRlZmRmAmNkAQLRqTImqNZjOUEgpTjQnJ5xMKtgoN--; SCF=qy'; function runBlock6() { for (var i = 0; i < 11; i++) { str27.replace(/##yv0##/gi, ''); str27.replace(re57, ''); str28.replace(re58, ''); str29.replace(re59, ''); str30.replace(/##\/o##/gi, ''); str30.replace(/##\/v##/gi, ''); str30.replace(/##\/h##/gi, ''); str30.replace(/##o##/gi, ''); str30.replace(/##oe##/gi, ''); str30.replace(/##v##/gi, ''); str30.replace(/##h##/gi, ''); str31.replace(/##n##/gi, ''); str32.replace(/##\/n##/gi, ''); str33.replace(/#~#argjbexybtb#~#/g, ''); / Zbovyr\//.exec(str0); /##yv1##/gi.exec(str27); /##yv10##/gi.exec(str28); /##yv11##/gi.exec(str28); /##yv12##/gi.exec(str28); /##yv13##/gi.exec(str28); /##yv14##/gi.exec(str28); /##yv15##/gi.exec(str28); re58.exec(str28); /##yv17##/gi.exec(str29); /##yv18##/gi.exec(str29); re59.exec(str29); /##yv2##/gi.exec(str27); /##yv20##/gi.exec(str30); /##yv21##/gi.exec(str30); /##yv22##/gi.exec(str30); /##yv23##/gi.exec(str30); /##yv3##/gi.exec(str27); re57.exec(str27); /##yv5##/gi.exec(str28); /##yv6##/gi.exec(str28); /##yv7##/gi.exec(str28); /##yv8##/gi.exec(str28); /##yv9##/gi.exec(str28); re8.exec('473qq1rs0n2r70q9qo1pq48n021s9468ron90nps048p4p29'); re8.exec('SbeprqRkcvengvba=633669325184628362'); re8.exec('FrffvbaQQS2=473qq1rs0n2r70q9qo1pq48n021s9468ron90nps048p4p29'); /AbxvnA[^\/]*/.exec(str0); } for (var i = 0; i < 10; i++) { ' bss'.replace(/(?:^|\s+)bss(?:\s+|$)/g, ''); str34.replace(/(\$\{0\})|(\$0\b)/g, ''); str34.replace(/(\$\{1\})|(\$1\b)/g, ''); str34.replace(/(\$\{pbzcyrgr\})|(\$pbzcyrgr\b)/g, ''); str34.replace(/(\$\{sentzrag\})|(\$sentzrag\b)/g, ''); str34.replace(/(\$\{ubfgcbeg\})|(\$ubfgcbeg\b)/g, ''); str34.replace(re56, ''); str34.replace(/(\$\{cebgbpby\})|(\$cebgbpby\b)/g, ''); str34.replace(/(\$\{dhrel\})|(\$dhrel\b)/g, ''); 'nqfvmr'.replace(re29, ''); 'nqfvmr'.replace(re30, ''); 'uggc://${2}${3}${4}${5}'.replace(/(\$\{2\})|(\$2\b)/g, ''); 'uggc://wf.hv-cbegny.qr${3}${4}${5}'.replace(/(\$\{3\})|(\$3\b)/g, ''); 'arjf'.replace(re40, ''); 'arjf'.replace(re41, ''); 'arjf'.replace(re42, ''); 'arjf'.replace(re43, ''); 'arjf'.replace(re44, ''); 'arjf'.replace(re45, ''); 'arjf'.replace(re46, ''); 'arjf'.replace(re47, ''); 'arjf'.replace(re48, ''); / PC=i=(\d+)&oe=(.)/.exec(str35); re60.exec(' '); re60.exec(' bss'); re60.exec(''); re19.exec(' '); re19.exec('svefg ba'); re19.exec('ynfg vtaber'); re19.exec('ba'); re9.exec('scnq so '); re9.exec('zrqvgobk'); re9.exec('hsgy'); re9.exec('lhv-h'); /Fnsnev|Xbadhrebe|XUGZY/gi.exec(str0); re61.exec('uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/onfr.wf'); re62.exec('#Ybtva_rznvy'); } } var re63 = /\{0\}/g; var str36 = 'FrffvbaQQS2=4ss747o77904333q374or84qrr1s9r0nprp8r5q81534o94n; ZFPhygher=VC=74.125.75.20&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669321699093060&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R=; AFP_zp_tfwsbrg-aowb_80=4413268q3660'; var str37 = 'FrffvbaQQS2=4ss747o77904333q374or84qrr1s9r0nprp8r5q81534o94n; AFP_zp_tfwsbrg-aowb_80=4413268q3660; __hgzm=144631658.1231364074.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.2294274870215848400.1231364074.1231364074.1231364074.1; __hgzo=144631658.0.10.1231364074; __hgzp=144631658; ZFPhygher=VC=74.125.75.20&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669321699093060&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str38 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231364057761&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231364057761&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Ssevraqf.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=1667363813.1231364061&tn_fvq=1231364061&tn_uvq=1917563877&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; var str39 = 'ZFPhygher=VC=74.125.75.20&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669321699093060&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str40 = 'ZFPhygher=VC=74.125.75.20&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669321699093060&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; function runBlock7() { for (var i = 0; i < 9; i++) { '0'.replace(re40, ''); '0'.replace(re10, ''); '0'.replace(re51, ''); '0'.replace(re52, ''); '0'.replace(re53, ''); '0'.replace(re39, ''); '0'.replace(re54, ''); 'Lrf'.replace(re40, ''); 'Lrf'.replace(re10, ''); 'Lrf'.replace(re51, ''); 'Lrf'.replace(re52, ''); 'Lrf'.replace(re53, ''); 'Lrf'.replace(re39, ''); 'Lrf'.replace(re54, ''); } for (var i = 0; i < 8; i++) { 'Pybfr {0}'.replace(re63, ''); 'Bcra {0}'.replace(re63, ''); str36.split(re32); str37.split(re32); 'puvyq p1 svefg gnournqref'.replace(re14, ''); 'puvyq p1 svefg gnournqref'.replace(re15, ''); 'uqy_fcb'.replace(re14, ''); 'uqy_fcb'.replace(re15, ''); 'uvag'.replace(re14, ''); 'uvag'.replace(re15, ''); str38.replace(re33, ''); 'yvfg'.replace(re14, ''); 'yvfg'.replace(re15, ''); 'at_bhgre'.replace(re30, ''); 'cnerag puebzr5 qbhoyr2 NU'.replace(re14, ''); 'cnerag puebzr5 qbhoyr2 NU'.replace(re15, ''); 'cnerag puebzr5 dhnq5 ps NU osyvax zbarl'.replace(re14, ''); 'cnerag puebzr5 dhnq5 ps NU osyvax zbarl'.replace(re15, ''); 'cnerag puebzr6 fvatyr1'.replace(re14, ''); 'cnerag puebzr6 fvatyr1'.replace(re15, ''); 'cb_qrs'.replace(re14, ''); 'cb_qrs'.replace(re15, ''); 'gnopbagrag'.replace(re14, ''); 'gnopbagrag'.replace(re15, ''); 'iv_svefg_gvzr'.replace(re30, ''); /(^|.)(ronl|qri-ehf3.wbg)(|fgberf|zbgbef|yvirnhpgvbaf|jvxv|rkcerff|punggre).(pbz(|.nh|.pa|.ux|.zl|.ft|.oe|.zk)|pb(.hx|.xe|.am)|pn|qr|se|vg|ay|or|ng|pu|vr|va|rf|cy|cu|fr)$/i.exec('cntrf.ronl.pbz'); re8.exec('144631658.0.10.1231364074'); re8.exec('144631658.1231364074.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re8.exec('144631658.2294274870215848400.1231364074.1231364074.1231364074.1'); re8.exec('4413241q3660'); re8.exec('SbeprqRkcvengvba=633669357391353591'); re8.exec(str39); re8.exec(str40); re8.exec('AFP_zp_kkk-gdzogv_80=4413241q3660'); re8.exec('FrffvbaQQS2=p98s8o9q42nr21or1r61pqorn1n002nsss569635984s6qp7'); re8.exec('__hgzn=144631658.2294274870215848400.1231364074.1231364074.1231364074.1'); re8.exec('__hgzo=144631658.0.10.1231364074'); re8.exec('__hgzm=144631658.1231364074.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re8.exec('p98s8o9q42nr21or1r61pqorn1n002nsss569635984s6qp7'); re34.exec(str36); re34.exec(str37); } } var re64 = /\b[a-z]/g; var re65 = /^uggc:\/\//; var re66 = /(?:^|\s+)qvfnoyrq(?:\s+|$)/; var str41 = 'uggc://cebsvyr.zlfcnpr.pbz/Zbqhyrf/Nccyvpngvbaf/Cntrf/Pnainf.nfck'; function runBlock8() { for (var i = 0; i < 7; i++) { str1.match(/\d+/g); 'nsgre'.replace(re64, ''); 'orsber'.replace(re64, ''); 'obggbz'.replace(re64, ''); 'ohvygva_jrngure.kzy'.replace(re65, ''); 'ohggba'.replace(re37, ''); 'ohggba'.replace(re18, ''); 'qngrgvzr.kzy'.replace(re65, ''); 'uggc://eff.paa.pbz/eff/paa_gbcfgbevrf.eff'.replace(re65, ''); 'vachg'.replace(re37, ''); 'vachg'.replace(re18, ''); 'vafvqr'.replace(re64, ''); 'cbvagre'.replace(re27, ''); 'cbfvgvba'.replace(/[A-Z]/g, ''); 'gbc'.replace(re27, ''); 'gbc'.replace(re64, ''); 'hy'.replace(re37, ''); 'hy'.replace(re18, ''); str26.replace(re37, ''); str26.replace(re18, ''); 'lbhghor_vtbbtyr/i2/lbhghor.kzy'.replace(re65, ''); 'm-vaqrk'.replace(re27, ''); /#([\w-]+)/.exec(str26); re16.exec('urvtug'); re16.exec('znetvaGbc'); re16.exec('jvqgu'); re19.exec('gno0 svefg ba'); re19.exec('gno0 ba'); re19.exec('gno4 ynfg'); re19.exec('gno4'); re19.exec('gno5'); re19.exec('gno6'); re19.exec('gno7'); re19.exec('gno8'); /NqborNVE\/([^\s]*)/.exec(str0); /NccyrJroXvg\/([^ ]*)/.exec(str0); /XUGZY/gi.exec(str0); /^(?:obql|ugzy)$/i.exec('YV'); re38.exec('ohggba'); re38.exec('vachg'); re38.exec('hy'); re38.exec(str26); /^(\w+|\*)/.exec(str26); /znp|jva|yvahk/i.exec('Jva32'); /eton?\([\d\s,]+\)/.exec('fgngvp'); } for (var i = 0; i < 6; i++) { ''.replace(/\r/g, ''); '/'.replace(re40, ''); '/'.replace(re10, ''); '/'.replace(re51, ''); '/'.replace(re52, ''); '/'.replace(re53, ''); '/'.replace(re39, ''); '/'.replace(re54, ''); 'uggc://zfacbegny.112.2b7.arg/o/ff/zfacbegnyubzr/1/U.7-cqi-2/{0}?[NDO]&{1}&{2}&[NDR]'.replace(re63, ''); str41.replace(re12, ''); 'uggc://jjj.snprobbx.pbz/fepu.cuc'.replace(re23, ''); 'freivpr'.replace(re40, ''); 'freivpr'.replace(re41, ''); 'freivpr'.replace(re42, ''); 'freivpr'.replace(re43, ''); 'freivpr'.replace(re44, ''); 'freivpr'.replace(re45, ''); 'freivpr'.replace(re46, ''); 'freivpr'.replace(re47, ''); 'freivpr'.replace(re48, ''); /((ZFVR\s+([6-9]|\d\d)\.))/.exec(str0); re66.exec(''); re50.exec('fryrpgrq'); re8.exec('8sqq78r9n442851q565599o401385sp3s04r92rnn7o19ssn'); re8.exec('SbeprqRkcvengvba=633669340386893867'); re8.exec('VC=74.125.75.17'); re8.exec('FrffvbaQQS2=8sqq78r9n442851q565599o401385sp3s04r92rnn7o19ssn'); /Xbadhrebe|Fnsnev|XUGZY/.exec(str0); re13.exec(str41); re49.exec('unfsbphf'); } } var re67 = /zrah_byq/g; var str42 = 'FrffvbaQQS2=473qq1rs0n2r70q9qo1pq48n021s9468ron90nps048p4p29; ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669325184628362&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; var str43 = 'FrffvbaQQS2=473qq1rs0n2r70q9qo1pq48n021s9468ron90nps048p4p29; __hgzm=144631658.1231364380.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.3931862196947939300.1231364380.1231364380.1231364380.1; __hgzo=144631658.0.10.1231364380; __hgzp=144631658; ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669325184628362&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str44 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_vzntrf_wf&qg=1231364373088&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231364373088&punaary=svz_zlfcnpr_hfre-ivrj-pbzzragf%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Spbzzrag.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=1158737789.1231364375&tn_fvq=1231364375&tn_uvq=415520832&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; var str45 = 'ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669325184628362&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str46 = 'ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669325184628362&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; var re68 = /^([#.]?)((?:[\w\u0128-\uffff*_-]|\\.)*)/; var re69 = /\{1\}/g; var re70 = /\s+/; var re71 = /(\$\{4\})|(\$4\b)/g; var re72 = /(\$\{5\})|(\$5\b)/g; var re73 = /\{2\}/g; var re74 = /[^+>] [^+>]/; var re75 = /\bucpyv\s*=\s*([^;]*)/i; var re76 = /\bucuvqr\s*=\s*([^;]*)/i; var re77 = /\bucfie\s*=\s*([^;]*)/i; var re78 = /\bhfucjrn\s*=\s*([^;]*)/i; var re79 = /\bmvc\s*=\s*([^;]*)/i; var re80 = /^((?:[\w\u0128-\uffff*_-]|\\.)+)(#)((?:[\w\u0128-\uffff*_-]|\\.)+)/; var re81 = /^([>+~])\s*(\w*)/i; var re82 = /^>\s*((?:[\w\u0128-\uffff*_-]|\\.)+)/; var re83 = /^[\s[]?shapgvba/; var re84 = /v\/g.tvs#(.*)/i; var str47 = '#Zbq-Vasb-Vasb-WninFpevcgUvag'; var str48 = ',n.svryqOgaPnapry'; var str49 = 'FrffvbaQQS2=p98s8o9q42nr21or1r61pqorn1n002nsss569635984s6qp7; ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669357391353591&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R=; AFP_zp_kkk-gdzogv_80=4413241q3660'; var str50 = 'FrffvbaQQS2=p98s8o9q42nr21or1r61pqorn1n002nsss569635984s6qp7; AFP_zp_kkk-gdzogv_80=4413241q3660; AFP_zp_kkk-aowb_80=4413235p3660; __hgzm=144631658.1231367708.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.2770915348920628700.1231367708.1231367708.1231367708.1; __hgzo=144631658.0.10.1231367708; __hgzp=144631658; ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669357391353591&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str51 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231367691141&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231367691141&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Sjjj.zlfcnpr.pbz%2S&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=320757904.1231367694&tn_fvq=1231367694&tn_uvq=1758792003&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; var str52 = 'uggc://zfacbegny.112.2b7.arg/o/ff/zfacbegnyubzr/1/U.7-cqi-2/f55332979829981?[NDO]&aqu=1&g=7%2S0%2S2009%2014%3N38%3N42%203%20480&af=zfacbegny&cntrAnzr=HF%20UCZFSGJ&t=uggc%3N%2S%2Sjjj.zfa.pbz%2S&f=1024k768&p=24&x=L&oj=994&ou=634&uc=A&{2}&[NDR]'; var str53 = 'cnerag puebzr6 fvatyr1 gno fryrpgrq ovaq qbhoyr2 ps'; var str54 = 'ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669357391353591&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str55 = 'ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669357391353591&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; var str56 = 'ne;ng;nh;or;oe;pn;pu;py;pa;qr;qx;rf;sv;se;to;ux;vq;vr;va;vg;wc;xe;zk;zl;ay;ab;am;cu;cy;cg;eh;fr;ft;gu;ge;gj;mn;'; var str57 = 'ZP1=I=3&THVQ=6nnpr9q661804s33nnop45nosqp17q85; zu=ZFSG; PHYGHER=RA-HF; SyvtugTebhcVq=97; SyvtugVq=OnfrCntr; ucfie=Z:5|S:5|G:5|R:5|Q:oyh|J:S; ucpyv=J.U|Y.|F.|E.|H.Y|P.|U.; hfucjrn=jp:HFPN0746; ZHVQ=Q783SN9O14054831N4869R51P0SO8886&GHVQ=1'; var str58 = 'ZP1=I=3&THVQ=6nnpr9q661804s33nnop45nosqp17q85; zu=ZFSG; PHYGHER=RA-HF; SyvtugTebhcVq=97; SyvtugVq=OnfrCntr; ucfie=Z:5|S:5|G:5|R:5|Q:oyh|J:S; ucpyv=J.U|Y.|F.|E.|H.Y|P.|U.; hfucjrn=jp:HFPN0746; ZHVQ=Q783SN9O14054831N4869R51P0SO8886'; var str59 = 'ZP1=I=3&THVQ=6nnpr9q661804s33nnop45nosqp17q85; zu=ZFSG; PHYGHER=RA-HF; SyvtugTebhcVq=97; SyvtugVq=OnfrCntr; ucfie=Z:5|S:5|G:5|R:5|Q:oyh|J:S; ucpyv=J.U|Y.|F.|E.|H.Y|P.|U.; hfucjrn=jp:HFPN0746; ZHVQ=Q783SN9O14054831N4869R51P0SO8886; mvc=m:94043|yn:37.4154|yb:-122.0585|p:HF|ue:1'; var str60 = 'ZP1=I=3&THVQ=6nnpr9q661804s33nnop45nosqp17q85; zu=ZFSG; PHYGHER=RA-HF; SyvtugTebhcVq=97; SyvtugVq=OnfrCntr; ucfie=Z:5|S:5|G:5|R:5|Q:oyh|J:S; ucpyv=J.U|Y.|F.|E.|H.Y|P.|U.; hfucjrn=jp:HFPN0746; ZHVQ=Q783SN9O14054831N4869R51P0SO8886; mvc=m:94043|yn:37.4154|yb:-122.0585|p:HF'; var str61 = 'uggc://gx2.fgp.f-zfa.pbz/oe/uc/11/ra-hf/pff/v/g.tvs#uggc://gx2.fgo.f-zfa.pbz/v/29/4RQP4969777N048NPS4RRR3PO2S7S.wct'; var str62 = 'uggc://gx2.fgp.f-zfa.pbz/oe/uc/11/ra-hf/pff/v/g.tvs#uggc://gx2.fgo.f-zfa.pbz/v/OQ/63NP9O94NS5OQP1249Q9S1ROP7NS3.wct'; var str63 = 'zbmvyyn/5.0 (jvaqbjf; h; jvaqbjf ag 5.1; ra-hf) nccyrjroxvg/528.9 (xugzy, yvxr trpxb) puebzr/2.0.157.0 fnsnev/528.9'; function runBlock9() { for (var i = 0; i < 5; i++) { str42.split(re32); str43.split(re32); 'svz_zlfcnpr_hfre-ivrj-pbzzragf,svz_zlfcnpr_havgrq-fgngrf'.split(re20); str44.replace(re33, ''); 'zrah_arj zrah_arj_gbttyr zrah_gbttyr'.replace(re67, ''); 'zrah_byq zrah_byq_gbttyr zrah_gbttyr'.replace(re67, ''); re8.exec('102n9o0o9pq60132qn0337rr867p75953502q2s27s2s5r98'); re8.exec('144631658.0.10.1231364380'); re8.exec('144631658.1231364380.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re8.exec('144631658.3931862196947939300.1231364380.1231364380.1231364380.1'); re8.exec('441326q33660'); re8.exec('SbeprqRkcvengvba=633669341278771470'); re8.exec(str45); re8.exec(str46); re8.exec('AFP_zp_dfctwzssrwh-aowb_80=441326q33660'); re8.exec('FrffvbaQQS2=102n9o0o9pq60132qn0337rr867p75953502q2s27s2s5r98'); re8.exec('__hgzn=144631658.3931862196947939300.1231364380.1231364380.1231364380.1'); re8.exec('__hgzo=144631658.0.10.1231364380'); re8.exec('__hgzm=144631658.1231364380.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); } for (var i = 0; i < 4; i++) { ' yvfg1'.replace(re14, ''); ' yvfg1'.replace(re15, ''); ' yvfg2'.replace(re14, ''); ' yvfg2'.replace(re15, ''); ' frneputebhc1'.replace(re14, ''); ' frneputebhc1'.replace(re15, ''); str47.replace(re68, ''); str47.replace(re18, ''); ''.replace(/&/g, ''); ''.replace(re35, ''); '(..-{0})(\|(\d+)|)'.replace(re63, ''); str48.replace(re18, ''); '//vzt.jro.qr/vij/FC/${cngu}/${anzr}/${inyhr}?gf=${abj}'.replace(re56, ''); '//vzt.jro.qr/vij/FC/tzk_uc/${anzr}/${inyhr}?gf=${abj}'.replace(/(\$\{anzr\})|(\$anzr\b)/g, ''); 'Jvaqbjf Yvir Ubgznvy{1}'.replace(re69, ''); '{0}{1}'.replace(re63, ''); '{1}'.replace(re69, ''); '{1}'.replace(re63, ''); 'Vzntrf'.replace(re15, ''); 'ZFA'.replace(re15, ''); 'Zncf'.replace(re15, ''); 'Zbq-Vasb-Vasb-WninFpevcgUvag'.replace(re39, ''); 'Arjf'.replace(re15, ''); str49.split(re32); str50.split(re32); 'Ivqrb'.replace(re15, ''); 'Jro'.replace(re15, ''); 'n'.replace(re39, ''); 'nwnkFgneg'.split(re70); 'nwnkFgbc'.split(re70); 'ovaq'.replace(re14, ''); 'ovaq'.replace(re15, ''); 'oevatf lbh zber. Zber fcnpr (5TO), zber frphevgl, fgvyy serr.'.replace(re63, ''); 'puvyq p1 svefg qrpx'.replace(re14, ''); 'puvyq p1 svefg qrpx'.replace(re15, ''); 'puvyq p1 svefg qbhoyr2'.replace(re14, ''); 'puvyq p1 svefg qbhoyr2'.replace(re15, ''); 'puvyq p2 ynfg'.replace(re14, ''); 'puvyq p2 ynfg'.replace(re15, ''); 'puvyq p2'.replace(re14, ''); 'puvyq p2'.replace(re15, ''); 'puvyq p3'.replace(re14, ''); 'puvyq p3'.replace(re15, ''); 'puvyq p4 ynfg'.replace(re14, ''); 'puvyq p4 ynfg'.replace(re15, ''); 'pbclevtug'.replace(re14, ''); 'pbclevtug'.replace(re15, ''); 'qZFAZR_1'.replace(re14, ''); 'qZFAZR_1'.replace(re15, ''); 'qbhoyr2 ps'.replace(re14, ''); 'qbhoyr2 ps'.replace(re15, ''); 'qbhoyr2'.replace(re14, ''); 'qbhoyr2'.replace(re15, ''); 'uqy_arj'.replace(re14, ''); 'uqy_arj'.replace(re15, ''); 'uc_fubccvatobk'.replace(re30, ''); 'ugzy%2Rvq'.replace(re29, ''); 'ugzy%2Rvq'.replace(re30, ''); str51.replace(re33, ''); 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/cebgbglcr.wf${4}${5}'.replace(re71, ''); 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/cebgbglcr.wf${5}'.replace(re72, ''); str52.replace(re73, ''); 'uggc://zfacbegny.112.2b7.arg/o/ff/zfacbegnyubzr/1/U.7-cqi-2/f55332979829981?[NDO]&{1}&{2}&[NDR]'.replace(re69, ''); 'vztZFSG'.replace(re14, ''); 'vztZFSG'.replace(re15, ''); 'zfasbbg1 ps'.replace(re14, ''); 'zfasbbg1 ps'.replace(re15, ''); str53.replace(re14, ''); str53.replace(re15, ''); 'cnerag puebzr6 fvatyr1 gno fryrpgrq ovaq'.replace(re14, ''); 'cnerag puebzr6 fvatyr1 gno fryrpgrq ovaq'.replace(re15, ''); 'cevznel'.replace(re14, ''); 'cevznel'.replace(re15, ''); 'erpgnatyr'.replace(re30, ''); 'frpbaqnel'.replace(re14, ''); 'frpbaqnel'.replace(re15, ''); 'haybnq'.split(re70); '{0}{1}1'.replace(re63, ''); '|{1}1'.replace(re69, ''); /(..-HF)(\|(\d+)|)/i.exec('xb-xe,ra-va,gu-gu'); re4.exec('/ZlFcnprNccf/NccPnainf,45000012'); re8.exec('144631658.0.10.1231367708'); re8.exec('144631658.1231367708.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re8.exec('144631658.2770915348920628700.1231367708.1231367708.1231367708.1'); re8.exec('4413235p3660'); re8.exec('441327q73660'); re8.exec('9995p6rp12rrnr893334ro7nq70o7p64p69rqn844prs1473'); re8.exec('SbeprqRkcvengvba=633669350559478880'); re8.exec(str54); re8.exec(str55); re8.exec('AFP_zp_dfctwzs-aowb_80=441327q73660'); re8.exec('AFP_zp_kkk-aowb_80=4413235p3660'); re8.exec('FrffvbaQQS2=9995p6rp12rrnr893334ro7nq70o7p64p69rqn844prs1473'); re8.exec('__hgzn=144631658.2770915348920628700.1231367708.1231367708.1231367708.1'); re8.exec('__hgzo=144631658.0.10.1231367708'); re8.exec('__hgzm=144631658.1231367708.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re34.exec(str49); re34.exec(str50); /ZFVR\s+5[.]01/.exec(str0); /HF(?=;)/i.exec(str56); re74.exec(str47); re28.exec('svefg npgvir svefgNpgvir'); re28.exec('ynfg'); /\bp:(..)/i.exec('m:94043|yn:37.4154|yb:-122.0585|p:HF'); re75.exec(str57); re75.exec(str58); re76.exec(str57); re76.exec(str58); re77.exec(str57); re77.exec(str58); /\bhfucce\s*=\s*([^;]*)/i.exec(str59); re78.exec(str57); re78.exec(str58); /\bjci\s*=\s*([^;]*)/i.exec(str59); re79.exec(str58); re79.exec(str60); re79.exec(str59); /\|p:([a-z]{2})/i.exec('m:94043|yn:37.4154|yb:-122.0585|p:HF|ue:1'); re80.exec(str47); re61.exec('cebgbglcr.wf'); re68.exec(str47); re81.exec(str47); re82.exec(str47); /^Fubpxjnir Synfu (\d)/.exec(str1); /^Fubpxjnir Synfu (\d+)/.exec(str1); re83.exec('[bowrpg tybony]'); re62.exec(str47); re84.exec(str61); re84.exec(str62); /jroxvg/.exec(str63); } } var re85 = /eaq_zbqobkva/; var str64 = '1231365729213'; var str65 = '74.125.75.3-1057165600.29978900'; var str66 = '74.125.75.3-1057165600.29978900.1231365730214'; var str67 = 'Frnepu%20Zvpebfbsg.pbz'; var str68 = 'FrffvbaQQS2=8sqq78r9n442851q565599o401385sp3s04r92rnn7o19ssn; ZFPhygher=VC=74.125.75.17&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669340386893867&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; var str69 = 'FrffvbaQQS2=8sqq78r9n442851q565599o401385sp3s04r92rnn7o19ssn; __hgzm=144631658.1231365779.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.1877536177953918500.1231365779.1231365779.1231365779.1; __hgzo=144631658.0.10.1231365779; __hgzp=144631658; ZFPhygher=VC=74.125.75.17&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669340386893867&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str70 = 'I=3%26THVQ=757q3ss871q44o7o805n8113n5p72q52'; var str71 = 'I=3&THVQ=757q3ss871q44o7o805n8113n5p72q52'; var str72 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231365765292&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231365765292&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Sohyyrgvaf.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=1579793869.1231365768&tn_fvq=1231365768&tn_uvq=2056210897&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; var str73 = 'frnepu.zvpebfbsg.pbz'; var str74 = 'frnepu.zvpebfbsg.pbz/'; var str75 = 'ZFPhygher=VC=74.125.75.17&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669340386893867&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str76 = 'ZFPhygher=VC=74.125.75.17&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669340386893867&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; function runBlock10() { for (var i = 0; i < 3; i++) { '%3Szxg=ra-HF'.replace(re39, ''); '-8'.replace(re40, ''); '-8'.replace(re10, ''); '-8'.replace(re51, ''); '-8'.replace(re52, ''); '-8'.replace(re53, ''); '-8'.replace(re39, ''); '-8'.replace(re54, ''); '1.5'.replace(re40, ''); '1.5'.replace(re10, ''); '1.5'.replace(re51, ''); '1.5'.replace(re52, ''); '1.5'.replace(re53, ''); '1.5'.replace(re39, ''); '1.5'.replace(re54, ''); '1024k768'.replace(re40, ''); '1024k768'.replace(re10, ''); '1024k768'.replace(re51, ''); '1024k768'.replace(re52, ''); '1024k768'.replace(re53, ''); '1024k768'.replace(re39, ''); '1024k768'.replace(re54, ''); str64.replace(re40, ''); str64.replace(re10, ''); str64.replace(re51, ''); str64.replace(re52, ''); str64.replace(re53, ''); str64.replace(re39, ''); str64.replace(re54, ''); '14'.replace(re40, ''); '14'.replace(re10, ''); '14'.replace(re51, ''); '14'.replace(re52, ''); '14'.replace(re53, ''); '14'.replace(re39, ''); '14'.replace(re54, ''); '24'.replace(re40, ''); '24'.replace(re10, ''); '24'.replace(re51, ''); '24'.replace(re52, ''); '24'.replace(re53, ''); '24'.replace(re39, ''); '24'.replace(re54, ''); str65.replace(re40, ''); str65.replace(re10, ''); str65.replace(re51, ''); str65.replace(re52, ''); str65.replace(re53, ''); str65.replace(re39, ''); str65.replace(re54, ''); str66.replace(re40, ''); str66.replace(re10, ''); str66.replace(re51, ''); str66.replace(re52, ''); str66.replace(re53, ''); str66.replace(re39, ''); str66.replace(re54, ''); '9.0'.replace(re40, ''); '9.0'.replace(re10, ''); '9.0'.replace(re51, ''); '9.0'.replace(re52, ''); '9.0'.replace(re53, ''); '9.0'.replace(re39, ''); '9.0'.replace(re54, ''); '994k634'.replace(re40, ''); '994k634'.replace(re10, ''); '994k634'.replace(re51, ''); '994k634'.replace(re52, ''); '994k634'.replace(re53, ''); '994k634'.replace(re39, ''); '994k634'.replace(re54, ''); '?zxg=ra-HF'.replace(re40, ''); '?zxg=ra-HF'.replace(re10, ''); '?zxg=ra-HF'.replace(re51, ''); '?zxg=ra-HF'.replace(re52, ''); '?zxg=ra-HF'.replace(re53, ''); '?zxg=ra-HF'.replace(re54, ''); 'PAA.pbz'.replace(re25, ''); 'PAA.pbz'.replace(re12, ''); 'PAA.pbz'.replace(re39, ''); 'Qngr & Gvzr'.replace(re25, ''); 'Qngr & Gvzr'.replace(re12, ''); 'Qngr & Gvzr'.replace(re39, ''); 'Frnepu Zvpebfbsg.pbz'.replace(re40, ''); 'Frnepu Zvpebfbsg.pbz'.replace(re54, ''); str67.replace(re10, ''); str67.replace(re51, ''); str67.replace(re52, ''); str67.replace(re53, ''); str67.replace(re39, ''); str68.split(re32); str69.split(re32); str70.replace(re52, ''); str70.replace(re53, ''); str70.replace(re39, ''); str71.replace(re40, ''); str71.replace(re10, ''); str71.replace(re51, ''); str71.replace(re54, ''); 'Jrngure'.replace(re25, ''); 'Jrngure'.replace(re12, ''); 'Jrngure'.replace(re39, ''); 'LbhGhor'.replace(re25, ''); 'LbhGhor'.replace(re12, ''); 'LbhGhor'.replace(re39, ''); str72.replace(re33, ''); 'erzbgr_vsenzr_1'.replace(/^erzbgr_vsenzr_/, ''); str73.replace(re40, ''); str73.replace(re10, ''); str73.replace(re51, ''); str73.replace(re52, ''); str73.replace(re53, ''); str73.replace(re39, ''); str73.replace(re54, ''); str74.replace(re40, ''); str74.replace(re10, ''); str74.replace(re51, ''); str74.replace(re52, ''); str74.replace(re53, ''); str74.replace(re39, ''); str74.replace(re54, ''); 'lhv-h'.replace(/\-/g, ''); re9.exec('p'); re9.exec('qz p'); re9.exec('zbqynory'); re9.exec('lhv-h svefg'); re8.exec('144631658.0.10.1231365779'); re8.exec('144631658.1231365779.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re8.exec('144631658.1877536177953918500.1231365779.1231365779.1231365779.1'); re8.exec(str75); re8.exec(str76); re8.exec('__hgzn=144631658.1877536177953918500.1231365779.1231365779.1231365779.1'); re8.exec('__hgzo=144631658.0.10.1231365779'); re8.exec('__hgzm=144631658.1231365779.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re34.exec(str68); re34.exec(str69); /^$/.exec(''); re31.exec('qr'); /^znk\d+$/.exec(''); /^zva\d+$/.exec(''); /^erfgber$/.exec(''); re85.exec('zbqobkva zbqobk_abcnqqvat '); re85.exec('zbqgvgyr'); re85.exec('eaq_zbqobkva '); re85.exec('eaq_zbqgvgyr '); /frpgvba\d+_pbagragf/.exec('obggbz_ani'); } } var re86 = /;\s*/; var re87 = /(\$\{inyhr\})|(\$inyhr\b)/g; var re88 = /(\$\{abj\})|(\$abj\b)/g; var re89 = /\s+$/; var re90 = /^\s+/; var re91 = /(\\\"|\x00-|\x1f|\x7f-|\x9f|\u00ad|\u0600-|\u0604|\u070f|\u17b4|\u17b5|\u200c-|\u200f|\u2028-|\u202f|\u2060-|\u206f|\ufeff|\ufff0-|\uffff)/g; var re92 = /^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/; var re93 = /^([:.#]*)((?:[\w\u0128-\uffff*_-]|\\.)+)/; var re94 = /^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/; var str77 = '#fubhgobk .pybfr'; var str78 = 'FrffvbaQQS2=102n9o0o9pq60132qn0337rr867p75953502q2s27s2s5r98; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669341278771470&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R=; AFP_zp_dfctwzssrwh-aowb_80=441326q33660'; var str79 = 'FrffvbaQQS2=102n9o0o9pq60132qn0337rr867p75953502q2s27s2s5r98; AFP_zp_dfctwzssrwh-aowb_80=441326q33660; __hgzm=144631658.1231365869.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.1670816052019209000.1231365869.1231365869.1231365869.1; __hgzo=144631658.0.10.1231365869; __hgzp=144631658; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669341278771470&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str80 = 'FrffvbaQQS2=9995p6rp12rrnr893334ro7nq70o7p64p69rqn844prs1473; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669350559478880&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R=; AFP_zp_dfctwzs-aowb_80=441327q73660'; var str81 = 'FrffvbaQQS2=9995p6rp12rrnr893334ro7nq70o7p64p69rqn844prs1473; AFP_zp_dfctwzs-aowb_80=441327q73660; __hgzm=144631658.1231367054.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.1796080716621419500.1231367054.1231367054.1231367054.1; __hgzo=144631658.0.10.1231367054; __hgzp=144631658; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669350559478880&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str82 = '[glcr=fhozvg]'; var str83 = 'n.svryqOga,n.svryqOgaPnapry'; var str84 = 'n.svryqOgaPnapry'; var str85 = 'oyvpxchaxg'; var str86 = 'qvi.bow-nppbeqvba qg'; var str87 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_nccf_wf&qg=1231367052227&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231367052227&punaary=svz_zlfcnpr_nccf-pnainf%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Scebsvyr.zlfcnpr.pbz%2SZbqhyrf%2SNccyvpngvbaf%2SCntrf%2SPnainf.nfck&nq_glcr=grkg&rvq=6083027&rn=0&sez=1&tn_ivq=716357910.1231367056&tn_fvq=1231367056&tn_uvq=1387206491&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; var str88 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231365851658&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231365851658&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Scebsvyrrqvg.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=1979828129.1231365855&tn_fvq=1231365855&tn_uvq=2085229649&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; var str89 = 'uggc://zfacbegny.112.2b7.arg/o/ff/zfacbegnyubzr/1/U.7-cqi-2/f55023338617756?[NDO]&aqu=1&g=7%2S0%2S2009%2014%3N12%3N47%203%20480&af=zfacbegny&cntrAnzr=HF%20UCZFSGJ&t=uggc%3N%2S%2Sjjj.zfa.pbz%2S&f=0k0&p=43835816&x=A&oj=994&ou=634&uc=A&{2}&[NDR]'; var str90 = 'zrgn[anzr=nwnkHey]'; var str91 = 'anpuevpugra'; var str92 = 'b oS={\'oT\':1.1};x $8n(B){z(B!=o9)};x $S(B){O(!$8n(B))z A;O(B.4L)z\'T\';b S=7t B;O(S==\'2P\'&&B.p4){23(B.7f){12 1:z\'T\';12 3:z/\S/.2g(B.8M)?\'ox\':\'oh\'}}O(S==\'2P\'||S==\'x\'){23(B.nE){12 2V:z\'1O\';12 7I:z\'5a\';12 18:z\'4B\'}O(7t B.I==\'4F\'){O(B.3u)z\'pG\';O(B.8e)z\'1p\'}}z S};x $2p(){b 4E={};Z(b v=0;v<1p.I;v++){Z(b X 1o 1p[v]){b nc=1p[v][X];b 6E=4E[X];O(6E&&$S(nc)==\'2P\'&&$S(6E)==\'2P\')4E[X]=$2p(6E,nc);17 4E[X]=nc}}z 4E};b $E=7p.E=x(){b 1d=1p;O(!1d[1])1d=[p,1d[0]];Z(b X 1o 1d[1])1d[0][X]=1d[1][X];z 1d[0]};b $4D=7p.pJ=x(){Z(b v=0,y=1p.I;v-1:p.3F(2R)>-1},nX:x(){z p.3y(/([.*+?^${}()|[\]\/\\])/t,\'\\$1\')}});2V.E({5V:x(1O){O(p.I<3)z A;O(p.I==4&&p[3]==0&&!1O)z\'p5\';b 3P=[];Z(b v=0;v<3;v++){b 52=(p[v]-0).4h(16);3P.1x((52.I==1)?\'0\'+52:52)}z 1O?3P:\'#\'+3P.2u(\'\')},5U:x(1O){O(p.I!=3)z A;b 1i=[];Z(b v=0;v<3;v++){1i.1x(5K((p[v].I==1)?p[v]+p[v]:p[v],16))}z 1O?1i:\'1i(\'+1i.2u(\',\')+\')\'}});7F.E({3n:x(P){b J=p;P=$2p({\'L\':J,\'V\':A,\'1p\':1S,\'2x\':A,\'4s\':A,\'6W\':A},P);O($2O(P.1p)&&$S(P.1p)!=\'1O\')P.1p=[P.1p];z x(V){b 1d;O(P.V){V=V||H.V;1d=[(P.V===1r)?V:Y P.V(V)];O(P.1p)1d.E(P.1p)}17 1d=P.1p||1p;b 3C=x(){z J.3H($5S(P'; var str93 = 'hagreunyghat'; var str94 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669341278771470&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str95 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669350559478880&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; var str96 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669341278771470&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; var str97 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669350559478880&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; var str98 = 'shapgvba (){Cuk.Nccyvpngvba.Frghc.Pber();Cuk.Nccyvpngvba.Frghc.Nwnk();Cuk.Nccyvpngvba.Frghc.Synfu();Cuk.Nccyvpngvba.Frghc.Zbqhyrf()}'; function runBlock11() { for (var i = 0; i < 2; i++) { ' .pybfr'.replace(re18, ''); ' n.svryqOgaPnapry'.replace(re18, ''); ' qg'.replace(re18, ''); str77.replace(re68, ''); str77.replace(re18, ''); ''.replace(re39, ''); ''.replace(/^/, ''); ''.split(re86); '*'.replace(re39, ''); '*'.replace(re68, ''); '*'.replace(re18, ''); '.pybfr'.replace(re68, ''); '.pybfr'.replace(re18, ''); '//vzt.jro.qr/vij/FC/tzk_uc/fperra/${inyhr}?gf=${abj}'.replace(re87, ''); '//vzt.jro.qr/vij/FC/tzk_uc/fperra/1024?gf=${abj}'.replace(re88, ''); '//vzt.jro.qr/vij/FC/tzk_uc/jvafvmr/${inyhr}?gf=${abj}'.replace(re87, ''); '//vzt.jro.qr/vij/FC/tzk_uc/jvafvmr/992/608?gf=${abj}'.replace(re88, ''); '300k120'.replace(re30, ''); '300k250'.replace(re30, ''); '310k120'.replace(re30, ''); '310k170'.replace(re30, ''); '310k250'.replace(re30, ''); '9.0 e115'.replace(/^.*\.(.*)\s.*$/, ''); 'Nppbeqvba'.replace(re2, ''); 'Nxghryy\x0a'.replace(re89, ''); 'Nxghryy\x0a'.replace(re90, ''); 'Nccyvpngvba'.replace(re2, ''); 'Oyvpxchaxg\x0a'.replace(re89, ''); 'Oyvpxchaxg\x0a'.replace(re90, ''); 'Svanamra\x0a'.replace(re89, ''); 'Svanamra\x0a'.replace(re90, ''); 'Tnzrf\x0a'.replace(re89, ''); 'Tnzrf\x0a'.replace(re90, ''); 'Ubebfxbc\x0a'.replace(re89, ''); 'Ubebfxbc\x0a'.replace(re90, ''); 'Xvab\x0a'.replace(re89, ''); 'Xvab\x0a'.replace(re90, ''); 'Zbqhyrf'.replace(re2, ''); 'Zhfvx\x0a'.replace(re89, ''); 'Zhfvx\x0a'.replace(re90, ''); 'Anpuevpugra\x0a'.replace(re89, ''); 'Anpuevpugra\x0a'.replace(re90, ''); 'Cuk'.replace(re2, ''); 'ErdhrfgSvavfu'.split(re70); 'ErdhrfgSvavfu.NWNK.Cuk'.split(re70); 'Ebhgr\x0a'.replace(re89, ''); 'Ebhgr\x0a'.replace(re90, ''); str78.split(re32); str79.split(re32); str80.split(re32); str81.split(re32); 'Fcbeg\x0a'.replace(re89, ''); 'Fcbeg\x0a'.replace(re90, ''); 'GI-Fcbg\x0a'.replace(re89, ''); 'GI-Fcbg\x0a'.replace(re90, ''); 'Gbhe\x0a'.replace(re89, ''); 'Gbhe\x0a'.replace(re90, ''); 'Hagreunyghat\x0a'.replace(re89, ''); 'Hagreunyghat\x0a'.replace(re90, ''); 'Ivqrb\x0a'.replace(re89, ''); 'Ivqrb\x0a'.replace(re90, ''); 'Jrggre\x0a'.replace(re89, ''); 'Jrggre\x0a'.replace(re90, ''); str82.replace(re68, ''); str82.replace(re18, ''); str83.replace(re68, ''); str83.replace(re18, ''); str84.replace(re68, ''); str84.replace(re18, ''); 'nqiFreivprObk'.replace(re30, ''); 'nqiFubccvatObk'.replace(re30, ''); 'nwnk'.replace(re39, ''); 'nxghryy'.replace(re40, ''); 'nxghryy'.replace(re41, ''); 'nxghryy'.replace(re42, ''); 'nxghryy'.replace(re43, ''); 'nxghryy'.replace(re44, ''); 'nxghryy'.replace(re45, ''); 'nxghryy'.replace(re46, ''); 'nxghryy'.replace(re47, ''); 'nxghryy'.replace(re48, ''); str85.replace(re40, ''); str85.replace(re41, ''); str85.replace(re42, ''); str85.replace(re43, ''); str85.replace(re44, ''); str85.replace(re45, ''); str85.replace(re46, ''); str85.replace(re47, ''); str85.replace(re48, ''); 'pngrtbel'.replace(re29, ''); 'pngrtbel'.replace(re30, ''); 'pybfr'.replace(re39, ''); 'qvi'.replace(re39, ''); str86.replace(re68, ''); str86.replace(re18, ''); 'qg'.replace(re39, ''); 'qg'.replace(re68, ''); 'qg'.replace(re18, ''); 'rzorq'.replace(re39, ''); 'rzorq'.replace(re68, ''); 'rzorq'.replace(re18, ''); 'svryqOga'.replace(re39, ''); 'svryqOgaPnapry'.replace(re39, ''); 'svz_zlfcnpr_nccf-pnainf,svz_zlfcnpr_havgrq-fgngrf'.split(re20); 'svanamra'.replace(re40, ''); 'svanamra'.replace(re41, ''); 'svanamra'.replace(re42, ''); 'svanamra'.replace(re43, ''); 'svanamra'.replace(re44, ''); 'svanamra'.replace(re45, ''); 'svanamra'.replace(re46, ''); 'svanamra'.replace(re47, ''); 'svanamra'.replace(re48, ''); 'sbphf'.split(re70); 'sbphf.gno sbphfva.gno'.split(re70); 'sbphfva'.split(re70); 'sbez'.replace(re39, ''); 'sbez.nwnk'.replace(re68, ''); 'sbez.nwnk'.replace(re18, ''); 'tnzrf'.replace(re40, ''); 'tnzrf'.replace(re41, ''); 'tnzrf'.replace(re42, ''); 'tnzrf'.replace(re43, ''); 'tnzrf'.replace(re44, ''); 'tnzrf'.replace(re45, ''); 'tnzrf'.replace(re46, ''); 'tnzrf'.replace(re47, ''); 'tnzrf'.replace(re48, ''); 'ubzrcntr'.replace(re30, ''); 'ubebfxbc'.replace(re40, ''); 'ubebfxbc'.replace(re41, ''); 'ubebfxbc'.replace(re42, ''); 'ubebfxbc'.replace(re43, ''); 'ubebfxbc'.replace(re44, ''); 'ubebfxbc'.replace(re45, ''); 'ubebfxbc'.replace(re46, ''); 'ubebfxbc'.replace(re47, ''); 'ubebfxbc'.replace(re48, ''); 'uc_cebzbobk_ugzy%2Puc_cebzbobk_vzt'.replace(re30, ''); 'uc_erpgnatyr'.replace(re30, ''); str87.replace(re33, ''); str88.replace(re33, ''); 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/onfr.wf${4}${5}'.replace(re71, ''); 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/onfr.wf${5}'.replace(re72, ''); 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/qlaYvo.wf${4}${5}'.replace(re71, ''); 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/qlaYvo.wf${5}'.replace(re72, ''); 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/rssrpgYvo.wf${4}${5}'.replace(re71, ''); 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/rssrpgYvo.wf${5}'.replace(re72, ''); str89.replace(re73, ''); 'uggc://zfacbegny.112.2b7.arg/o/ff/zfacbegnyubzr/1/U.7-cqi-2/f55023338617756?[NDO]&{1}&{2}&[NDR]'.replace(re69, ''); str6.replace(re23, ''); 'xvab'.replace(re40, ''); 'xvab'.replace(re41, ''); 'xvab'.replace(re42, ''); 'xvab'.replace(re43, ''); 'xvab'.replace(re44, ''); 'xvab'.replace(re45, ''); 'xvab'.replace(re46, ''); 'xvab'.replace(re47, ''); 'xvab'.replace(re48, ''); 'ybnq'.split(re70); 'zrqvnzbqgno lhv-anifrg lhv-anifrg-gbc'.replace(re18, ''); 'zrgn'.replace(re39, ''); str90.replace(re68, ''); str90.replace(re18, ''); 'zbhfrzbir'.split(re70); 'zbhfrzbir.gno'.split(re70); str63.replace(/^.*jroxvg\/(\d+(\.\d+)?).*$/, ''); 'zhfvx'.replace(re40, ''); 'zhfvx'.replace(re41, ''); 'zhfvx'.replace(re42, ''); 'zhfvx'.replace(re43, ''); 'zhfvx'.replace(re44, ''); 'zhfvx'.replace(re45, ''); 'zhfvx'.replace(re46, ''); 'zhfvx'.replace(re47, ''); 'zhfvx'.replace(re48, ''); 'zlfcnpr_nccf_pnainf'.replace(re52, ''); str91.replace(re40, ''); str91.replace(re41, ''); str91.replace(re42, ''); str91.replace(re43, ''); str91.replace(re44, ''); str91.replace(re45, ''); str91.replace(re46, ''); str91.replace(re47, ''); str91.replace(re48, ''); 'anzr'.replace(re39, ''); str92.replace(/\b\w+\b/g, ''); 'bow-nppbeqvba'.replace(re39, ''); 'bowrpg'.replace(re39, ''); 'bowrpg'.replace(re68, ''); 'bowrpg'.replace(re18, ''); 'cnenzf%2Rfglyrf'.replace(re29, ''); 'cnenzf%2Rfglyrf'.replace(re30, ''); 'cbchc'.replace(re30, ''); 'ebhgr'.replace(re40, ''); 'ebhgr'.replace(re41, ''); 'ebhgr'.replace(re42, ''); 'ebhgr'.replace(re43, ''); 'ebhgr'.replace(re44, ''); 'ebhgr'.replace(re45, ''); 'ebhgr'.replace(re46, ''); 'ebhgr'.replace(re47, ''); 'ebhgr'.replace(re48, ''); 'freivprobk_uc'.replace(re30, ''); 'fubccvatobk_uc'.replace(re30, ''); 'fubhgobk'.replace(re39, ''); 'fcbeg'.replace(re40, ''); 'fcbeg'.replace(re41, ''); 'fcbeg'.replace(re42, ''); 'fcbeg'.replace(re43, ''); 'fcbeg'.replace(re44, ''); 'fcbeg'.replace(re45, ''); 'fcbeg'.replace(re46, ''); 'fcbeg'.replace(re47, ''); 'fcbeg'.replace(re48, ''); 'gbhe'.replace(re40, ''); 'gbhe'.replace(re41, ''); 'gbhe'.replace(re42, ''); 'gbhe'.replace(re43, ''); 'gbhe'.replace(re44, ''); 'gbhe'.replace(re45, ''); 'gbhe'.replace(re46, ''); 'gbhe'.replace(re47, ''); 'gbhe'.replace(re48, ''); 'gi-fcbg'.replace(re40, ''); 'gi-fcbg'.replace(re41, ''); 'gi-fcbg'.replace(re42, ''); 'gi-fcbg'.replace(re43, ''); 'gi-fcbg'.replace(re44, ''); 'gi-fcbg'.replace(re45, ''); 'gi-fcbg'.replace(re46, ''); 'gi-fcbg'.replace(re47, ''); 'gi-fcbg'.replace(re48, ''); 'glcr'.replace(re39, ''); 'haqrsvarq'.replace(/\//g, ''); str93.replace(re40, ''); str93.replace(re41, ''); str93.replace(re42, ''); str93.replace(re43, ''); str93.replace(re44, ''); str93.replace(re45, ''); str93.replace(re46, ''); str93.replace(re47, ''); str93.replace(re48, ''); 'ivqrb'.replace(re40, ''); 'ivqrb'.replace(re41, ''); 'ivqrb'.replace(re42, ''); 'ivqrb'.replace(re43, ''); 'ivqrb'.replace(re44, ''); 'ivqrb'.replace(re45, ''); 'ivqrb'.replace(re46, ''); 'ivqrb'.replace(re47, ''); 'ivqrb'.replace(re48, ''); 'ivfvgf=1'.split(re86); 'jrggre'.replace(re40, ''); 'jrggre'.replace(re41, ''); 'jrggre'.replace(re42, ''); 'jrggre'.replace(re43, ''); 'jrggre'.replace(re44, ''); 'jrggre'.replace(re45, ''); 'jrggre'.replace(re46, ''); 'jrggre'.replace(re47, ''); 'jrggre'.replace(re48, ''); /#[a-z0-9]+$/i.exec('uggc://jjj.fpuhryreim.arg/Qrsnhyg'); re66.exec('fryrpgrq'); /(?:^|\s+)lhv-ani(?:\s+|$)/.exec('sff lhv-ani'); /(?:^|\s+)lhv-anifrg(?:\s+|$)/.exec('zrqvnzbqgno lhv-anifrg'); /(?:^|\s+)lhv-anifrg-gbc(?:\s+|$)/.exec('zrqvnzbqgno lhv-anifrg'); re91.exec('GnoThvq'); re91.exec('thvq'); /(pbzcngvoyr|jroxvg)/.exec(str63); /.+(?:ei|vg|en|vr)[\/: ]([\d.]+)/.exec(str63); re8.exec('144631658.0.10.1231365869'); re8.exec('144631658.0.10.1231367054'); re8.exec('144631658.1231365869.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re8.exec('144631658.1231367054.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re8.exec('144631658.1670816052019209000.1231365869.1231365869.1231365869.1'); re8.exec('144631658.1796080716621419500.1231367054.1231367054.1231367054.1'); re8.exec(str94); re8.exec(str95); re8.exec(str96); re8.exec(str97); re8.exec('__hgzn=144631658.1670816052019209000.1231365869.1231365869.1231365869.1'); re8.exec('__hgzn=144631658.1796080716621419500.1231367054.1231367054.1231367054.1'); re8.exec('__hgzo=144631658.0.10.1231365869'); re8.exec('__hgzo=144631658.0.10.1231367054'); re8.exec('__hgzm=144631658.1231365869.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re8.exec('__hgzm=144631658.1231367054.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); re34.exec(str78); re34.exec(str79); re34.exec(str81); re74.exec(str77); re74.exec('*'); re74.exec(str82); re74.exec(str83); re74.exec(str86); re74.exec('rzorq'); re74.exec('sbez.nwnk'); re74.exec(str90); re74.exec('bowrpg'); /\/onfr.wf(\?.+)?$/.exec('/uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/onfr.wf'); re28.exec('uvag ynfgUvag ynfg'); re75.exec(''); re76.exec(''); re77.exec(''); re78.exec(''); re80.exec(str77); re80.exec('*'); re80.exec('.pybfr'); re80.exec(str82); re80.exec(str83); re80.exec(str84); re80.exec(str86); re80.exec('qg'); re80.exec('rzorq'); re80.exec('sbez.nwnk'); re80.exec(str90); re80.exec('bowrpg'); re61.exec('qlaYvo.wf'); re61.exec('rssrpgYvo.wf'); re61.exec('uggc://jjj.tzk.arg/qr/?fgnghf=uvajrvf'); re92.exec(' .pybfr'); re92.exec(' n.svryqOgaPnapry'); re92.exec(' qg'); re92.exec(str48); re92.exec('.nwnk'); re92.exec('.svryqOga,n.svryqOgaPnapry'); re92.exec('.svryqOgaPnapry'); re92.exec('.bow-nppbeqvba qg'); re68.exec(str77); re68.exec('*'); re68.exec('.pybfr'); re68.exec(str82); re68.exec(str83); re68.exec(str84); re68.exec(str86); re68.exec('qg'); re68.exec('rzorq'); re68.exec('sbez.nwnk'); re68.exec(str90); re68.exec('bowrpg'); re93.exec(' .pybfr'); re93.exec(' n.svryqOgaPnapry'); re93.exec(' qg'); re93.exec(str48); re93.exec('.nwnk'); re93.exec('.svryqOga,n.svryqOgaPnapry'); re93.exec('.svryqOgaPnapry'); re93.exec('.bow-nppbeqvba qg'); re81.exec(str77); re81.exec('*'); re81.exec(str48); re81.exec('.pybfr'); re81.exec(str82); re81.exec(str83); re81.exec(str84); re81.exec(str86); re81.exec('qg'); re81.exec('rzorq'); re81.exec('sbez.nwnk'); re81.exec(str90); re81.exec('bowrpg'); re94.exec(' .pybfr'); re94.exec(' n.svryqOgaPnapry'); re94.exec(' qg'); re94.exec(str48); re94.exec('.nwnk'); re94.exec('.svryqOga,n.svryqOgaPnapry'); re94.exec('.svryqOgaPnapry'); re94.exec('.bow-nppbeqvba qg'); re94.exec('[anzr=nwnkHey]'); re94.exec(str82); re31.exec('rf'); re31.exec('wn'); re82.exec(str77); re82.exec('*'); re82.exec(str48); re82.exec('.pybfr'); re82.exec(str82); re82.exec(str83); re82.exec(str84); re82.exec(str86); re82.exec('qg'); re82.exec('rzorq'); re82.exec('sbez.nwnk'); re82.exec(str90); re82.exec('bowrpg'); re83.exec(str98); re83.exec('shapgvba sbphf() { [angvir pbqr] }'); re62.exec('#Ybtva'); re62.exec('#Ybtva_cnffjbeq'); re62.exec(str77); re62.exec('#fubhgobkWf'); re62.exec('#fubhgobkWfReebe'); re62.exec('#fubhgobkWfFhpprff'); re62.exec('*'); re62.exec(str82); re62.exec(str83); re62.exec(str86); re62.exec('rzorq'); re62.exec('sbez.nwnk'); re62.exec(str90); re62.exec('bowrpg'); re49.exec('pbagrag'); re24.exec(str6); /xbadhrebe/.exec(str63); /znp/.exec('jva32'); /zbmvyyn/.exec(str63); /zfvr/.exec(str63); /ag\s5\.1/.exec(str63); /bcren/.exec(str63); /fnsnev/.exec(str63); /jva/.exec('jva32'); /jvaqbjf/.exec(str63); } } for (var i = 0; i < 5; i++) { runBlock0(); runBlock1(); runBlock2(); runBlock3(); runBlock4(); runBlock5(); runBlock6(); runBlock7(); runBlock8(); runBlock9(); runBlock10(); runBlock11(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/benchmarks/v8/run.js0000644000175000017500000000430611314263504030216 0ustar jamespagejamespage00000000000000// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. load('base.js'); load('richards.js'); load('deltablue.js'); load('crypto.js'); load('raytrace.js'); load('earley-boyer.js'); load('regexp.js'); load('splay.js'); var success = true; function PrintResult(name, result) { print(name + ': ' + result); } function PrintError(name, error) { PrintResult(name, error); success = false; } function PrintScore(score) { if (success) { print('----'); print('Score (version ' + BenchmarkSuite.version + '): ' + score); } } BenchmarkSuite.RunSuites({ NotifyResult: PrintResult, NotifyError: PrintError, NotifyScore: PrintScore }); jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/benchmarks/v8/earley-boyer.js0000644000175000017500000057534111314263504032025 0ustar jamespagejamespage00000000000000// This file is automatically generated by scheme2js, except for the // benchmark harness code at the beginning and end of the file. var EarleyBoyer = new BenchmarkSuite('EarleyBoyer', 765819, [ new Benchmark("Earley", function () { BgL_earleyzd2benchmarkzd2(); }), new Benchmark("Boyer", function () { BgL_nboyerzd2benchmarkzd2(); }) ]); /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /* * To use write/prints/... the default-output port has to be set first. * Simply setting SC_DEFAULT_OUT and SC_ERROR_OUT to the desired values * should do the trick. * In the following example the std-out and error-port are redirected to * a DIV. function initRuntime() { function escapeHTML(s) { var tmp = s; tmp = tmp.replace(/&/g, "&"); tmp = tmp.replace(//g, ">"); tmp = tmp.replace(/ /g, " "); tmp = tmp.replace(/\n/g, "
"); tmp = tmp.replace(/\t/g, "    "); return tmp; } document.write("
"); SC_DEFAULT_OUT = new sc_GenericOutputPort( function(s) { var stdout = document.getElementById('stdout'); stdout.innerHTML = stdout.innerHTML + escapeHTML(s); }); SC_ERROR_OUT = SC_DEFAULT_OUT; } */ function sc_print_debug() { sc_print.apply(null, arguments); } /*** META ((export *js*)) */ var sc_JS_GLOBALS = this; var __sc_LINE=-1; var __sc_FILE=""; /*** META ((export #t)) */ function sc_alert() { var len = arguments.length; var s = ""; var i; for( i = 0; i < len; i++ ) { s += sc_toDisplayString(arguments[ i ]); } return alert( s ); } /*** META ((export #t)) */ function sc_typeof( x ) { return typeof x; } /*** META ((export #t)) */ function sc_error() { var a = [sc_jsstring2symbol("*error*")]; for (var i = 0; i < arguments.length; i++) { a[i+1] = arguments[i]; } throw a; } /*** META ((export #t) (peephole (prefix "throw "))) */ function sc_raise(obj) { throw obj; } /*** META ((export with-handler-lambda)) */ function sc_withHandlerLambda(handler, body) { try { return body(); } catch(e) { if (!e._internalException) return handler(e); else throw e; } } var sc_properties = new Object(); /*** META ((export #t)) */ function sc_putpropBang(sym, key, val) { var ht = sc_properties[sym]; if (!ht) { ht = new Object(); sc_properties[sym] = ht; } ht[key] = val; } /*** META ((export #t)) */ function sc_getprop(sym, key) { var ht = sc_properties[sym]; if (ht) { if (key in ht) return ht[key]; else return false; } else return false; } /*** META ((export #t)) */ function sc_rempropBang(sym, key) { var ht = sc_properties[sym]; if (ht) delete ht[key]; } /*** META ((export #t)) */ function sc_any2String(o) { return jsstring2string(sc_toDisplayString(o)); } /*** META ((export #t) (peephole (infix 2 2 "===")) (type bool)) */ function sc_isEqv(o1, o2) { return (o1 === o2); } /*** META ((export #t) (peephole (infix 2 2 "===")) (type bool)) */ function sc_isEq(o1, o2) { return (o1 === o2); } /*** META ((export #t) (type bool)) */ function sc_isNumber(n) { return (typeof n === "number"); } /*** META ((export #t) (type bool)) */ function sc_isComplex(n) { return sc_isNumber(n); } /*** META ((export #t) (type bool)) */ function sc_isReal(n) { return sc_isNumber(n); } /*** META ((export #t) (type bool)) */ function sc_isRational(n) { return sc_isReal(n); } /*** META ((export #t) (type bool)) */ function sc_isInteger(n) { return (parseInt(n) === n); } /*** META ((export #t) (type bool) (peephole (postfix ", false"))) */ // we don't have exact numbers... function sc_isExact(n) { return false; } /*** META ((export #t) (peephole (postfix ", true")) (type bool)) */ function sc_isInexact(n) { return true; } /*** META ((export = =fx =fl) (type bool) (peephole (infix 2 2 "==="))) */ function sc_equal(x) { for (var i = 1; i < arguments.length; i++) if (x !== arguments[i]) return false; return true; } /*** META ((export < = arguments[i]) return false; x = arguments[i]; } return true; } /*** META ((export > >fx >fl) (type bool) (peephole (infix 2 2 ">"))) */ function sc_greater(x, y) { for (var i = 1; i < arguments.length; i++) { if (x <= arguments[i]) return false; x = arguments[i]; } return true; } /*** META ((export <= <=fx <=fl) (type bool) (peephole (infix 2 2 "<="))) */ function sc_lessEqual(x, y) { for (var i = 1; i < arguments.length; i++) { if (x > arguments[i]) return false; x = arguments[i]; } return true; } /*** META ((export >= >=fl >=fx) (type bool) (peephole (infix 2 2 ">="))) */ function sc_greaterEqual(x, y) { for (var i = 1; i < arguments.length; i++) { if (x < arguments[i]) return false; x = arguments[i]; } return true; } /*** META ((export #t) (type bool) (peephole (postfix "=== 0"))) */ function sc_isZero(x) { return (x === 0); } /*** META ((export #t) (type bool) (peephole (postfix "> 0"))) */ function sc_isPositive(x) { return (x > 0); } /*** META ((export #t) (type bool) (peephole (postfix "< 0"))) */ function sc_isNegative(x) { return (x < 0); } /*** META ((export #t) (type bool) (peephole (postfix "%2===1"))) */ function sc_isOdd(x) { return (x % 2 === 1); } /*** META ((export #t) (type bool) (peephole (postfix "%2===0"))) */ function sc_isEven(x) { return (x % 2 === 0); } /*** META ((export #t)) */ var sc_max = Math.max; /*** META ((export #t)) */ var sc_min = Math.min; /*** META ((export + +fx +fl) (peephole (infix 0 #f "+" "0"))) */ function sc_plus() { var sum = 0; for (var i = 0; i < arguments.length; i++) sum += arguments[i]; return sum; } /*** META ((export * *fx *fl) (peephole (infix 0 #f "*" "1"))) */ function sc_multi() { var product = 1; for (var i = 0; i < arguments.length; i++) product *= arguments[i]; return product; } /*** META ((export - -fx -fl) (peephole (minus))) */ function sc_minus(x) { if (arguments.length === 1) return -x; else { var res = x; for (var i = 1; i < arguments.length; i++) res -= arguments[i]; return res; } } /*** META ((export / /fl) (peephole (div))) */ function sc_div(x) { if (arguments.length === 1) return 1/x; else { var res = x; for (var i = 1; i < arguments.length; i++) res /= arguments[i]; return res; } } /*** META ((export #t)) */ var sc_abs = Math.abs; /*** META ((export quotient /fx) (peephole (hole 2 "parseInt(" x "/" y ")"))) */ function sc_quotient(x, y) { return parseInt(x / y); } /*** META ((export #t) (peephole (infix 2 2 "%"))) */ function sc_remainder(x, y) { return x % y; } /*** META ((export #t) (peephole (modulo))) */ function sc_modulo(x, y) { var remainder = x % y; // if they don't have the same sign if ((remainder * y) < 0) return remainder + y; else return remainder; } function sc_euclid_gcd(a, b) { var temp; if (a === 0) return b; if (b === 0) return a; if (a < 0) {a = -a;}; if (b < 0) {b = -b;}; if (b > a) {temp = a; a = b; b = temp;}; while (true) { a %= b; if(a === 0) {return b;}; b %= a; if(b === 0) {return a;}; }; return b; } /*** META ((export #t)) */ function sc_gcd() { var gcd = 0; for (var i = 0; i < arguments.length; i++) gcd = sc_euclid_gcd(gcd, arguments[i]); return gcd; } /*** META ((export #t)) */ function sc_lcm() { var lcm = 1; for (var i = 0; i < arguments.length; i++) { var f = Math.round(arguments[i] / sc_euclid_gcd(arguments[i], lcm)); lcm *= Math.abs(f); } return lcm; } // LIMITATION: numerator and denominator don't make sense in floating point world. //var SC_MAX_DECIMALS = 1000000 // // function sc_numerator(x) { // var rounded = Math.round(x * SC_MAX_DECIMALS); // return Math.round(rounded / sc_euclid_gcd(rounded, SC_MAX_DECIMALS)); // } // function sc_denominator(x) { // var rounded = Math.round(x * SC_MAX_DECIMALS); // return Math.round(SC_MAX_DECIMALS / sc_euclid_gcd(rounded, SC_MAX_DECIMALS)); // } /*** META ((export #t)) */ var sc_floor = Math.floor; /*** META ((export #t)) */ var sc_ceiling = Math.ceil; /*** META ((export #t)) */ var sc_truncate = parseInt; /*** META ((export #t)) */ var sc_round = Math.round; // LIMITATION: sc_rationalize doesn't make sense in a floating point world. /*** META ((export #t)) */ var sc_exp = Math.exp; /*** META ((export #t)) */ var sc_log = Math.log; /*** META ((export #t)) */ var sc_sin = Math.sin; /*** META ((export #t)) */ var sc_cos = Math.cos; /*** META ((export #t)) */ var sc_tan = Math.tan; /*** META ((export #t)) */ var sc_asin = Math.asin; /*** META ((export #t)) */ var sc_acos = Math.acos; /*** META ((export #t)) */ var sc_atan = Math.atan; /*** META ((export #t)) */ var sc_sqrt = Math.sqrt; /*** META ((export #t)) */ var sc_expt = Math.pow; // LIMITATION: we don't have complex numbers. // LIMITATION: the following functions are hence not implemented. // LIMITATION: make-rectangular, make-polar, real-part, imag-part, magnitude, angle // LIMITATION: 2 argument atan /*** META ((export #t) (peephole (id))) */ function sc_exact2inexact(x) { return x; } /*** META ((export #t) (peephole (id))) */ function sc_inexact2exact(x) { return x; } function sc_number2jsstring(x, radix) { if (radix) return x.toString(radix); else return x.toString(); } function sc_jsstring2number(s, radix) { if (s === "") return false; if (radix) { var t = parseInt(s, radix); if (!t && t !== 0) return false; // verify that each char is in range. (parseInt ignores leading // white and trailing chars) var allowedChars = "01234567890abcdefghijklmnopqrstuvwxyz".substring(0, radix+1); if ((new RegExp("^["+allowedChars+"]*$", "i")).test(s)) return t; else return false; } else { var t = +s; // does not ignore trailing chars. if (!t && t !== 0) return false; // simply verify that first char is not whitespace. var c = s.charAt(0); // if +c is 0, but the char is not "0", then we have a whitespace. if (+c === 0 && c !== "0") return false; return t; } } /*** META ((export #t) (type bool) (peephole (not))) */ function sc_not(b) { return b === false; } /*** META ((export #t) (type bool)) */ function sc_isBoolean(b) { return (b === true) || (b === false); } function sc_Pair(car, cdr) { this.car = car; this.cdr = cdr; } sc_Pair.prototype.toString = function() { return sc_toDisplayString(this); }; sc_Pair.prototype.sc_toWriteOrDisplayString = function(writeOrDisplay) { var current = this; var res = "("; while(true) { res += writeOrDisplay(current.car); if (sc_isPair(current.cdr)) { res += " "; current = current.cdr; } else if (current.cdr !== null) { res += " . " + writeOrDisplay(current.cdr); break; } else // current.cdr == null break; } res += ")"; return res; }; sc_Pair.prototype.sc_toDisplayString = function() { return this.sc_toWriteOrDisplayString(sc_toDisplayString); }; sc_Pair.prototype.sc_toWriteString = function() { return this.sc_toWriteOrDisplayString(sc_toWriteString); }; // sc_Pair.prototype.sc_toWriteCircleString in IO.js /*** META ((export #t) (type bool) (peephole (postfix " instanceof sc_Pair"))) */ function sc_isPair(p) { return (p instanceof sc_Pair); } function sc_isPairEqual(p1, p2, comp) { return (comp(p1.car, p2.car) && comp(p1.cdr, p2.cdr)); } /*** META ((export #t) (peephole (hole 2 "new sc_Pair(" car ", " cdr ")"))) */ function sc_cons(car, cdr) { return new sc_Pair(car, cdr); } /*** META ((export cons*)) */ function sc_consStar() { var res = arguments[arguments.length - 1]; for (var i = arguments.length-2; i >= 0; i--) res = new sc_Pair(arguments[i], res); return res; } /*** META ((export #t) (peephole (postfix ".car"))) */ function sc_car(p) { return p.car; } /*** META ((export #t) (peephole (postfix ".cdr"))) */ function sc_cdr(p) { return p.cdr; } /*** META ((export #t) (peephole (hole 2 p ".car = " val))) */ function sc_setCarBang(p, val) { p.car = val; } /*** META ((export #t) (peephole (hole 2 p ".cdr = " val))) */ function sc_setCdrBang(p, val) { p.cdr = val; } /*** META ((export #t) (peephole (postfix ".car.car"))) */ function sc_caar(p) { return p.car.car; } /*** META ((export #t) (peephole (postfix ".cdr.car"))) */ function sc_cadr(p) { return p.cdr.car; } /*** META ((export #t) (peephole (postfix ".car.cdr"))) */ function sc_cdar(p) { return p.car.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.cdr"))) */ function sc_cddr(p) { return p.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".car.car.car"))) */ function sc_caaar(p) { return p.car.car.car; } /*** META ((export #t) (peephole (postfix ".car.cdr.car"))) */ function sc_cadar(p) { return p.car.cdr.car; } /*** META ((export #t) (peephole (postfix ".cdr.car.car"))) */ function sc_caadr(p) { return p.cdr.car.car; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.car"))) */ function sc_caddr(p) { return p.cdr.cdr.car; } /*** META ((export #t) (peephole (postfix ".car.car.cdr"))) */ function sc_cdaar(p) { return p.car.car.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.car.cdr"))) */ function sc_cdadr(p) { return p.cdr.car.cdr; } /*** META ((export #t) (peephole (postfix ".car.cdr.cdr"))) */ function sc_cddar(p) { return p.car.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.cdr"))) */ function sc_cdddr(p) { return p.cdr.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".car.car.car.car"))) */ function sc_caaaar(p) { return p.car.car.car.car; } /*** META ((export #t) (peephole (postfix ".car.cdr.car.car"))) */ function sc_caadar(p) { return p.car.cdr.car.car; } /*** META ((export #t) (peephole (postfix ".cdr.car.car.car"))) */ function sc_caaadr(p) { return p.cdr.car.car.car; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.car.car"))) */ function sc_caaddr(p) { return p.cdr.cdr.car.car; } /*** META ((export #t) (peephole (postfix ".car.car.car.cdr"))) */ function sc_cdaaar(p) { return p.car.car.car.cdr; } /*** META ((export #t) (peephole (postfix ".car.cdr.car.cdr"))) */ function sc_cdadar(p) { return p.car.cdr.car.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.car.car.cdr"))) */ function sc_cdaadr(p) { return p.cdr.car.car.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.car.cdr"))) */ function sc_cdaddr(p) { return p.cdr.cdr.car.cdr; } /*** META ((export #t) (peephole (postfix ".car.car.cdr.car"))) */ function sc_cadaar(p) { return p.car.car.cdr.car; } /*** META ((export #t) (peephole (postfix ".car.cdr.cdr.car"))) */ function sc_caddar(p) { return p.car.cdr.cdr.car; } /*** META ((export #t) (peephole (postfix ".cdr.car.cdr.car"))) */ function sc_cadadr(p) { return p.cdr.car.cdr.car; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.cdr.car"))) */ function sc_cadddr(p) { return p.cdr.cdr.cdr.car; } /*** META ((export #t) (peephole (postfix ".car.car.cdr.cdr"))) */ function sc_cddaar(p) { return p.car.car.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".car.cdr.cdr.cdr"))) */ function sc_cdddar(p) { return p.car.cdr.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.car.cdr.cdr"))) */ function sc_cddadr(p) { return p.cdr.car.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.cdr.cdr"))) */ function sc_cddddr(p) { return p.cdr.cdr.cdr.cdr; } /*** META ((export #t)) */ function sc_lastPair(l) { if (!sc_isPair(l)) sc_error("sc_lastPair: pair expected"); var res = l; var cdr = l.cdr; while (sc_isPair(cdr)) { res = cdr; cdr = res.cdr; } return res; } /*** META ((export #t) (type bool) (peephole (postfix " === null"))) */ function sc_isNull(o) { return (o === null); } /*** META ((export #t) (type bool)) */ function sc_isList(o) { var rabbit; var turtle; var rabbit = o; var turtle = o; while (true) { if (rabbit === null || (rabbit instanceof sc_Pair && rabbit.cdr === null)) return true; // end of list else if ((rabbit instanceof sc_Pair) && (rabbit.cdr instanceof sc_Pair)) { rabbit = rabbit.cdr.cdr; turtle = turtle.cdr; if (rabbit === turtle) return false; // cycle } else return false; // not pair } } /*** META ((export #t)) */ function sc_list() { var res = null; var a = arguments; for (var i = a.length-1; i >= 0; i--) res = new sc_Pair(a[i], res); return res; } /*** META ((export #t)) */ function sc_iota(num, init) { var res = null; if (!init) init = 0; for (var i = num - 1; i >= 0; i--) res = new sc_Pair(i + init, res); return res; } /*** META ((export #t)) */ function sc_makeList(nbEls, fill) { var res = null; for (var i = 0; i < nbEls; i++) res = new sc_Pair(fill, res); return res; } /*** META ((export #t)) */ function sc_length(l) { var res = 0; while (l !== null) { res++; l = l.cdr; } return res; } /*** META ((export #t)) */ function sc_remq(o, l) { var dummy = { cdr : null }; var tail = dummy; while (l !== null) { if (l.car !== o) { tail.cdr = sc_cons(l.car, null); tail = tail.cdr; } l = l.cdr; } return dummy.cdr; } /*** META ((export #t)) */ function sc_remqBang(o, l) { var dummy = { cdr : null }; var tail = dummy; var needsAssig = true; while (l !== null) { if (l.car === o) { needsAssig = true; } else { if (needsAssig) { tail.cdr = l; needsAssig = false; } tail = l; } l = l.cdr; } tail.cdr = null; return dummy.cdr; } /*** META ((export #t)) */ function sc_delete(o, l) { var dummy = { cdr : null }; var tail = dummy; while (l !== null) { if (!sc_isEqual(l.car, o)) { tail.cdr = sc_cons(l.car, null); tail = tail.cdr; } l = l.cdr; } return dummy.cdr; } /*** META ((export #t)) */ function sc_deleteBang(o, l) { var dummy = { cdr : null }; var tail = dummy; var needsAssig = true; while (l !== null) { if (sc_isEqual(l.car, o)) { needsAssig = true; } else { if (needsAssig) { tail.cdr = l; needsAssig = false; } tail = l; } l = l.cdr; } tail.cdr = null; return dummy.cdr; } function sc_reverseAppendBang(l1, l2) { var res = l2; while (l1 !== null) { var tmp = res; res = l1; l1 = l1.cdr; res.cdr = tmp; } return res; } function sc_dualAppend(l1, l2) { if (l1 === null) return l2; if (l2 === null) return l1; var rev = sc_reverse(l1); return sc_reverseAppendBang(rev, l2); } /*** META ((export #t)) */ function sc_append() { if (arguments.length === 0) return null; var res = arguments[arguments.length - 1]; for (var i = arguments.length - 2; i >= 0; i--) res = sc_dualAppend(arguments[i], res); return res; } function sc_dualAppendBang(l1, l2) { if (l1 === null) return l2; if (l2 === null) return l1; var tmp = l1; while (tmp.cdr !== null) tmp=tmp.cdr; tmp.cdr = l2; return l1; } /*** META ((export #t)) */ function sc_appendBang() { var res = null; for (var i = 0; i < arguments.length; i++) res = sc_dualAppendBang(res, arguments[i]); return res; } /*** META ((export #t)) */ function sc_reverse(l1) { var res = null; while (l1 !== null) { res = sc_cons(l1.car, res); l1 = l1.cdr; } return res; } /*** META ((export #t)) */ function sc_reverseBang(l) { return sc_reverseAppendBang(l, null); } /*** META ((export #t)) */ function sc_listTail(l, k) { var res = l; for (var i = 0; i < k; i++) { res = res.cdr; } return res; } /*** META ((export #t)) */ function sc_listRef(l, k) { return sc_listTail(l, k).car; } /* // unoptimized generic versions function sc_memX(o, l, comp) { while (l != null) { if (comp(l.car, o)) return l; l = l.cdr; } return false; } function sc_memq(o, l) { return sc_memX(o, l, sc_isEq); } function sc_memv(o, l) { return sc_memX(o, l, sc_isEqv); } function sc_member(o, l) { return sc_memX(o, l, sc_isEqual); } */ /* optimized versions */ /*** META ((export #t)) */ function sc_memq(o, l) { while (l !== null) { if (l.car === o) return l; l = l.cdr; } return false; } /*** META ((export #t)) */ function sc_memv(o, l) { while (l !== null) { if (l.car === o) return l; l = l.cdr; } return false; } /*** META ((export #t)) */ function sc_member(o, l) { while (l !== null) { if (sc_isEqual(l.car,o)) return l; l = l.cdr; } return false; } /* // generic unoptimized versions function sc_assX(o, al, comp) { while (al != null) { if (comp(al.car.car, o)) return al.car; al = al.cdr; } return false; } function sc_assq(o, al) { return sc_assX(o, al, sc_isEq); } function sc_assv(o, al) { return sc_assX(o, al, sc_isEqv); } function sc_assoc(o, al) { return sc_assX(o, al, sc_isEqual); } */ // optimized versions /*** META ((export #t)) */ function sc_assq(o, al) { while (al !== null) { if (al.car.car === o) return al.car; al = al.cdr; } return false; } /*** META ((export #t)) */ function sc_assv(o, al) { while (al !== null) { if (al.car.car === o) return al.car; al = al.cdr; } return false; } /*** META ((export #t)) */ function sc_assoc(o, al) { while (al !== null) { if (sc_isEqual(al.car.car, o)) return al.car; al = al.cdr; } return false; } /* can be used for mutable strings and characters */ function sc_isCharStringEqual(cs1, cs2) { return cs1.val === cs2.val; } function sc_isCharStringLess(cs1, cs2) { return cs1.val < cs2.val; } function sc_isCharStringGreater(cs1, cs2) { return cs1.val > cs2.val; } function sc_isCharStringLessEqual(cs1, cs2) { return cs1.val <= cs2.val; } function sc_isCharStringGreaterEqual(cs1, cs2) { return cs1.val >= cs2.val; } function sc_isCharStringCIEqual(cs1, cs2) { return cs1.val.toLowerCase() === cs2.val.toLowerCase(); } function sc_isCharStringCILess(cs1, cs2) { return cs1.val.toLowerCase() < cs2.val.toLowerCase(); } function sc_isCharStringCIGreater(cs1, cs2) { return cs1.val.toLowerCase() > cs2.val.toLowerCase(); } function sc_isCharStringCILessEqual(cs1, cs2) { return cs1.val.toLowerCase() <= cs2.val.toLowerCase(); } function sc_isCharStringCIGreaterEqual(cs1, cs2) { return cs1.val.toLowerCase() >= cs2.val.toLowerCase(); } function sc_Char(c) { var cached = sc_Char.lazy[c]; if (cached) return cached; this.val = c; sc_Char.lazy[c] = this; // add return, so FF does not complain. return undefined; } sc_Char.lazy = new Object(); // thanks to Eric sc_Char.char2readable = { "\000": "#\\null", "\007": "#\\bell", "\010": "#\\backspace", "\011": "#\\tab", "\012": "#\\newline", "\014": "#\\page", "\015": "#\\return", "\033": "#\\escape", "\040": "#\\space", "\177": "#\\delete", /* poeticless names */ "\001": "#\\soh", "\002": "#\\stx", "\003": "#\\etx", "\004": "#\\eot", "\005": "#\\enq", "\006": "#\\ack", "\013": "#\\vt", "\016": "#\\so", "\017": "#\\si", "\020": "#\\dle", "\021": "#\\dc1", "\022": "#\\dc2", "\023": "#\\dc3", "\024": "#\\dc4", "\025": "#\\nak", "\026": "#\\syn", "\027": "#\\etb", "\030": "#\\can", "\031": "#\\em", "\032": "#\\sub", "\033": "#\\esc", "\034": "#\\fs", "\035": "#\\gs", "\036": "#\\rs", "\037": "#\\us"}; sc_Char.readable2char = { "null": "\000", "bell": "\007", "backspace": "\010", "tab": "\011", "newline": "\012", "page": "\014", "return": "\015", "escape": "\033", "space": "\040", "delete": "\000", "soh": "\001", "stx": "\002", "etx": "\003", "eot": "\004", "enq": "\005", "ack": "\006", "bel": "\007", "bs": "\010", "ht": "\011", "nl": "\012", "vt": "\013", "np": "\014", "cr": "\015", "so": "\016", "si": "\017", "dle": "\020", "dc1": "\021", "dc2": "\022", "dc3": "\023", "dc4": "\024", "nak": "\025", "syn": "\026", "etb": "\027", "can": "\030", "em": "\031", "sub": "\032", "esc": "\033", "fs": "\034", "gs": "\035", "rs": "\036", "us": "\037", "sp": "\040", "del": "\177"}; sc_Char.prototype.toString = function() { return this.val; }; // sc_toDisplayString == toString sc_Char.prototype.sc_toWriteString = function() { var entry = sc_Char.char2readable[this.val]; if (entry) return entry; else return "#\\" + this.val; }; /*** META ((export #t) (type bool) (peephole (postfix "instanceof sc_Char"))) */ function sc_isChar(c) { return (c instanceof sc_Char); } /*** META ((export char=?) (type bool) (peephole (hole 2 c1 ".val === " c2 ".val"))) */ var sc_isCharEqual = sc_isCharStringEqual; /*** META ((export char?) (type bool) (peephole (hole 2 c1 ".val > " c2 ".val"))) */ var sc_isCharGreater = sc_isCharStringGreater; /*** META ((export char<=?) (type bool) (peephole (hole 2 c1 ".val <= " c2 ".val"))) */ var sc_isCharLessEqual = sc_isCharStringLessEqual; /*** META ((export char>=?) (type bool) (peephole (hole 2 c1 ".val >= " c2 ".val"))) */ var sc_isCharGreaterEqual = sc_isCharStringGreaterEqual; /*** META ((export char-ci=?) (type bool) (peephole (hole 2 c1 ".val.toLowerCase() === " c2 ".val.toLowerCase()"))) */ var sc_isCharCIEqual = sc_isCharStringCIEqual; /*** META ((export char-ci?) (type bool) (peephole (hole 2 c1 ".val.toLowerCase() > " c2 ".val.toLowerCase()"))) */ var sc_isCharCIGreater = sc_isCharStringCIGreater; /*** META ((export char-ci<=?) (type bool) (peephole (hole 2 c1 ".val.toLowerCase() <= " c2 ".val.toLowerCase()"))) */ var sc_isCharCILessEqual = sc_isCharStringCILessEqual; /*** META ((export char-ci>=?) (type bool) (peephole (hole 2 c1 ".val.toLowerCase() >= " c2 ".val.toLowerCase()"))) */ var sc_isCharCIGreaterEqual = sc_isCharStringCIGreaterEqual; var SC_NUMBER_CLASS = "0123456789"; var SC_WHITESPACE_CLASS = ' \r\n\t\f'; var SC_LOWER_CLASS = 'abcdefghijklmnopqrstuvwxyz'; var SC_UPPER_CLASS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; function sc_isCharOfClass(c, cl) { return (cl.indexOf(c) != -1); } /*** META ((export #t) (type bool)) */ function sc_isCharAlphabetic(c) { return sc_isCharOfClass(c.val, SC_LOWER_CLASS) || sc_isCharOfClass(c.val, SC_UPPER_CLASS); } /*** META ((export #t) (type bool) (peephole (hole 1 "SC_NUMBER_CLASS.indexOf(" c ".val) != -1"))) */ function sc_isCharNumeric(c) { return sc_isCharOfClass(c.val, SC_NUMBER_CLASS); } /*** META ((export #t) (type bool)) */ function sc_isCharWhitespace(c) { var tmp = c.val; return tmp === " " || tmp === "\r" || tmp === "\n" || tmp === "\t" || tmp === "\f"; } /*** META ((export #t) (type bool) (peephole (hole 1 "SC_UPPER_CLASS.indexOf(" c ".val) != -1"))) */ function sc_isCharUpperCase(c) { return sc_isCharOfClass(c.val, SC_UPPER_CLASS); } /*** META ((export #t) (type bool) (peephole (hole 1 "SC_LOWER_CLASS.indexOf(" c ".val) != -1"))) */ function sc_isCharLowerCase(c) { return sc_isCharOfClass(c.val, SC_LOWER_CLASS); } /*** META ((export #t) (peephole (postfix ".val.charCodeAt(0)"))) */ function sc_char2integer(c) { return c.val.charCodeAt(0); } /*** META ((export #t) (peephole (hole 1 "new sc_Char(String.fromCharCode(" n "))"))) */ function sc_integer2char(n) { return new sc_Char(String.fromCharCode(n)); } /*** META ((export #t) (peephole (hole 1 "new sc_Char(" c ".val.toUpperCase())"))) */ function sc_charUpcase(c) { return new sc_Char(c.val.toUpperCase()); } /*** META ((export #t) (peephole (hole 1 "new sc_Char(" c ".val.toLowerCase())"))) */ function sc_charDowncase(c) { return new sc_Char(c.val.toLowerCase()); } function sc_makeJSStringOfLength(k, c) { var fill; if (c === undefined) fill = " "; else fill = c; var res = ""; var len = 1; // every round doubles the size of fill. while (k >= len) { if (k & len) res = res.concat(fill); fill = fill.concat(fill); len *= 2; } return res; } function sc_makejsString(k, c) { var fill; if (c) fill = c.val; else fill = " "; return sc_makeJSStringOfLength(k, fill); } function sc_jsstring2list(s) { var res = null; for (var i = s.length - 1; i >= 0; i--) res = sc_cons(new sc_Char(s.charAt(i)), res); return res; } function sc_list2jsstring(l) { var a = new Array(); while(l !== null) { a.push(l.car.val); l = l.cdr; } return "".concat.apply("", a); } var sc_Vector = Array; sc_Vector.prototype.sc_toWriteOrDisplayString = function(writeOrDisplay) { if (this.length === 0) return "#()"; var res = "#(" + writeOrDisplay(this[0]); for (var i = 1; i < this.length; i++) res += " " + writeOrDisplay(this[i]); res += ")"; return res; }; sc_Vector.prototype.sc_toDisplayString = function() { return this.sc_toWriteOrDisplayString(sc_toDisplayString); }; sc_Vector.prototype.sc_toWriteString = function() { return this.sc_toWriteOrDisplayString(sc_toWriteString); }; /*** META ((export vector? array?) (type bool) (peephole (postfix " instanceof sc_Vector"))) */ function sc_isVector(v) { return (v instanceof sc_Vector); } // only applies to vectors function sc_isVectorEqual(v1, v2, comp) { if (v1.length !== v2.length) return false; for (var i = 0; i < v1.length; i++) if (!comp(v1[i], v2[i])) return false; return true; } /*** META ((export make-vector make-array)) */ function sc_makeVector(size, fill) { var a = new sc_Vector(size); if (fill !== undefined) sc_vectorFillBang(a, fill); return a; } /*** META ((export vector array) (peephole (vector))) */ function sc_vector() { var a = new sc_Vector(); for (var i = 0; i < arguments.length; i++) a.push(arguments[i]); return a; } /*** META ((export vector-length array-length) (peephole (postfix ".length"))) */ function sc_vectorLength(v) { return v.length; } /*** META ((export vector-ref array-ref) (peephole (hole 2 v "[" pos "]"))) */ function sc_vectorRef(v, pos) { return v[pos]; } /*** META ((export vector-set! array-set!) (peephole (hole 3 v "[" pos "] = " val))) */ function sc_vectorSetBang(v, pos, val) { v[pos] = val; } /*** META ((export vector->list array->list)) */ function sc_vector2list(a) { var res = null; for (var i = a.length-1; i >= 0; i--) res = sc_cons(a[i], res); return res; } /*** META ((export list->vector list->array)) */ function sc_list2vector(l) { var a = new sc_Vector(); while(l !== null) { a.push(l.car); l = l.cdr; } return a; } /*** META ((export vector-fill! array-fill!)) */ function sc_vectorFillBang(a, fill) { for (var i = 0; i < a.length; i++) a[i] = fill; } /*** META ((export #t)) */ function sc_copyVector(a, len) { if (len <= a.length) return a.slice(0, len); else { var tmp = a.concat(); tmp.length = len; return tmp; } } /*** META ((export #t) (peephole (hole 3 a ".slice(" start "," end ")"))) */ function sc_vectorCopy(a, start, end) { return a.slice(start, end); } /*** META ((export #t)) */ function sc_vectorCopyBang(target, tstart, source, sstart, send) { if (!sstart) sstart = 0; if (!send) send = source.length; // if target == source we don't want to overwrite not yet copied elements. if (tstart <= sstart) { for (var i = tstart, j = sstart; j < send; i++, j++) { target[i] = source[j]; } } else { var diff = send - sstart; for (var i = tstart + diff - 1, j = send - 1; j >= sstart; i--, j--) { target[i] = source[j]; } } return target; } /*** META ((export #t) (type bool) (peephole (hole 1 "typeof " o " === 'function'"))) */ function sc_isProcedure(o) { return (typeof o === "function"); } /*** META ((export #t)) */ function sc_apply(proc) { var args = new Array(); // first part of arguments are not in list-form. for (var i = 1; i < arguments.length - 1; i++) args.push(arguments[i]); var l = arguments[arguments.length - 1]; while (l !== null) { args.push(l.car); l = l.cdr; } return proc.apply(null, args); } /*** META ((export #t)) */ function sc_map(proc, l1) { if (l1 === undefined) return null; // else var nbApplyArgs = arguments.length - 1; var applyArgs = new Array(nbApplyArgs); var revres = null; while (l1 !== null) { for (var i = 0; i < nbApplyArgs; i++) { applyArgs[i] = arguments[i + 1].car; arguments[i + 1] = arguments[i + 1].cdr; } revres = sc_cons(proc.apply(null, applyArgs), revres); } return sc_reverseAppendBang(revres, null); } /*** META ((export #t)) */ function sc_mapBang(proc, l1) { if (l1 === undefined) return null; // else var l1_orig = l1; var nbApplyArgs = arguments.length - 1; var applyArgs = new Array(nbApplyArgs); while (l1 !== null) { var tmp = l1; for (var i = 0; i < nbApplyArgs; i++) { applyArgs[i] = arguments[i + 1].car; arguments[i + 1] = arguments[i + 1].cdr; } tmp.car = proc.apply(null, applyArgs); } return l1_orig; } /*** META ((export #t)) */ function sc_forEach(proc, l1) { if (l1 === undefined) return undefined; // else var nbApplyArgs = arguments.length - 1; var applyArgs = new Array(nbApplyArgs); while (l1 !== null) { for (var i = 0; i < nbApplyArgs; i++) { applyArgs[i] = arguments[i + 1].car; arguments[i + 1] = arguments[i + 1].cdr; } proc.apply(null, applyArgs); } // add return so FF does not complain. return undefined; } /*** META ((export #t)) */ function sc_filter(proc, l1) { var dummy = { cdr : null }; var tail = dummy; while (l1 !== null) { if (proc(l1.car) !== false) { tail.cdr = sc_cons(l1.car, null); tail = tail.cdr; } l1 = l1.cdr; } return dummy.cdr; } /*** META ((export #t)) */ function sc_filterBang(proc, l1) { var head = sc_cons("dummy", l1); var it = head; var next = l1; while (next !== null) { if (proc(next.car) !== false) { it.cdr = next it = next; } next = next.cdr; } it.cdr = null; return head.cdr; } function sc_filterMap1(proc, l1) { var revres = null; while (l1 !== null) { var tmp = proc(l1.car) if (tmp !== false) revres = sc_cons(tmp, revres); l1 = l1.cdr; } return sc_reverseAppendBang(revres, null); } function sc_filterMap2(proc, l1, l2) { var revres = null; while (l1 !== null) { var tmp = proc(l1.car, l2.car); if(tmp !== false) revres = sc_cons(tmp, revres); l1 = l1.cdr; l2 = l2.cdr } return sc_reverseAppendBang(revres, null); } /*** META ((export #t)) */ function sc_filterMap(proc, l1, l2, l3) { if (l2 === undefined) return sc_filterMap1(proc, l1); else if (l3 === undefined) return sc_filterMap2(proc, l1, l2); // else var nbApplyArgs = arguments.length - 1; var applyArgs = new Array(nbApplyArgs); var revres = null; while (l1 !== null) { for (var i = 0; i < nbApplyArgs; i++) { applyArgs[i] = arguments[i + 1].car; arguments[i + 1] = arguments[i + 1].cdr; } var tmp = proc.apply(null, applyArgs); if(tmp !== false) revres = sc_cons(tmp, revres); } return sc_reverseAppendBang(revres, null); } /*** META ((export #t)) */ function sc_any(proc, l) { var revres = null; while (l !== null) { var tmp = proc(l.car); if(tmp !== false) return tmp; l = l.cdr; } return false; } /*** META ((export any?) (peephole (hole 2 "sc_any(" proc "," l ") !== false"))) */ function sc_anyPred(proc, l) { return sc_any(proc, l)!== false; } /*** META ((export #t)) */ function sc_every(proc, l) { var revres = null; var tmp = true; while (l !== null) { tmp = proc(l.car); if (tmp === false) return false; l = l.cdr; } return tmp; } /*** META ((export every?) (peephole (hole 2 "sc_every(" proc "," l ") !== false"))) */ function sc_everyPred(proc, l) { var tmp = sc_every(proc, l); if (tmp !== false) return true; return false; } /*** META ((export #t) (peephole (postfix "()"))) */ function sc_force(o) { return o(); } /*** META ((export #t)) */ function sc_makePromise(proc) { var isResultReady = false; var result = undefined; return function() { if (!isResultReady) { var tmp = proc(); if (!isResultReady) { isResultReady = true; result = tmp; } } return result; }; } function sc_Values(values) { this.values = values; } /*** META ((export #t) (peephole (values))) */ function sc_values() { if (arguments.length === 1) return arguments[0]; else return new sc_Values(arguments); } /*** META ((export #t)) */ function sc_callWithValues(producer, consumer) { var produced = producer(); if (produced instanceof sc_Values) return consumer.apply(null, produced.values); else return consumer(produced); } /*** META ((export #t)) */ function sc_dynamicWind(before, thunk, after) { before(); try { var res = thunk(); return res; } finally { after(); } } // TODO: eval/scheme-report-environment/null-environment/interaction-environment // LIMITATION: 'load' doesn't exist without files. // LIMITATION: transcript-on/transcript-off doesn't exist without files. function sc_Struct(name) { this.name = name; } sc_Struct.prototype.sc_toDisplayString = function() { return "#"; }; sc_Struct.prototype.sc_toWriteString = sc_Struct.prototype.sc_toDisplayString; /*** META ((export #t) (peephole (hole 1 "new sc_Struct(" name ")"))) */ function sc_makeStruct(name) { return new sc_Struct(name); } /*** META ((export #t) (type bool) (peephole (postfix " instanceof sc_Struct"))) */ function sc_isStruct(o) { return (o instanceof sc_Struct); } /*** META ((export #t) (type bool) (peephole (hole 2 "(" 1 " instanceof sc_Struct) && ( " 1 ".name === " 0 ")"))) */ function sc_isStructNamed(name, s) { return ((s instanceof sc_Struct) && (s.name === name)); } /*** META ((export struct-field) (peephole (hole 3 0 "[" 2 "]"))) */ function sc_getStructField(s, name, field) { return s[field]; } /*** META ((export struct-field-set!) (peephole (hole 4 0 "[" 2 "] = " 3))) */ function sc_setStructFieldBang(s, name, field, val) { s[field] = val; } /*** META ((export #t) (peephole (prefix "~"))) */ function sc_bitNot(x) { return ~x; } /*** META ((export #t) (peephole (infix 2 2 "&"))) */ function sc_bitAnd(x, y) { return x & y; } /*** META ((export #t) (peephole (infix 2 2 "|"))) */ function sc_bitOr(x, y) { return x | y; } /*** META ((export #t) (peephole (infix 2 2 "^"))) */ function sc_bitXor(x, y) { return x ^ y; } /*** META ((export #t) (peephole (infix 2 2 "<<"))) */ function sc_bitLsh(x, y) { return x << y; } /*** META ((export #t) (peephole (infix 2 2 ">>"))) */ function sc_bitRsh(x, y) { return x >> y; } /*** META ((export #t) (peephole (infix 2 2 ">>>"))) */ function sc_bitUrsh(x, y) { return x >>> y; } /*** META ((export js-field js-property) (peephole (hole 2 o "[" field "]"))) */ function sc_jsField(o, field) { return o[field]; } /*** META ((export js-field-set! js-property-set!) (peephole (hole 3 o "[" field "] = " val))) */ function sc_setJsFieldBang(o, field, val) { return o[field] = val; } /*** META ((export js-field-delete! js-property-delete!) (peephole (hole 2 "delete" o "[" field "]"))) */ function sc_deleteJsFieldBang(o, field) { delete o[field]; } /*** META ((export #t) (peephole (jsCall))) */ function sc_jsCall(o, fun) { var args = new Array(); for (var i = 2; i < arguments.length; i++) args[i-2] = arguments[i]; return fun.apply(o, args); } /*** META ((export #t) (peephole (jsMethodCall))) */ function sc_jsMethodCall(o, field) { var args = new Array(); for (var i = 2; i < arguments.length; i++) args[i-2] = arguments[i]; return o[field].apply(o, args); } /*** META ((export new js-new) (peephole (jsNew))) */ function sc_jsNew(c) { var evalStr = "new c("; evalStr +=arguments.length > 1? "arguments[1]": ""; for (var i = 2; i < arguments.length; i++) evalStr += ", arguments[" + i + "]"; evalStr +=")"; return eval(evalStr); } // ======================== RegExp ==================== /*** META ((export #t)) */ function sc_pregexp(re) { return new RegExp(sc_string2jsstring(re)); } /*** META ((export #t)) */ function sc_pregexpMatch(re, s) { var reg = (re instanceof RegExp) ? re : sc_pregexp(re); var tmp = reg.exec(sc_string2jsstring(s)); if (tmp == null) return false; var res = null; for (var i = tmp.length-1; i >= 0; i--) { if (tmp[i] !== null) { res = sc_cons(sc_jsstring2string(tmp[i]), res); } else { res = sc_cons(false, res); } } return res; } /*** META ((export #t)) */ function sc_pregexpReplace(re, s1, s2) { var reg; var jss1 = sc_string2jsstring(s1); var jss2 = sc_string2jsstring(s2); if (re instanceof RegExp) { if (re.global) reg = re; else reg = new RegExp(re.source); } else { reg = new RegExp(sc_string2jsstring(re)); } return jss1.replace(reg, jss2); } /*** META ((export pregexp-replace*)) */ function sc_pregexpReplaceAll(re, s1, s2) { var reg; var jss1 = sc_string2jsstring(s1); var jss2 = sc_string2jsstring(s2); if (re instanceof RegExp) { if (re.global) reg = re; else reg = new RegExp(re.source, "g"); } else { reg = new RegExp(sc_string2jsstring(re), "g"); } return jss1.replace(reg, jss2); } /*** META ((export #t)) */ function sc_pregexpSplit(re, s) { var reg = ((re instanceof RegExp) ? re : new RegExp(sc_string2jsstring(re))); var jss = sc_string2jsstring(s); var tmp = jss.split(reg); if (tmp == null) return false; return sc_vector2list(tmp); } /* =========================================================================== */ /* Other library stuff */ /* =========================================================================== */ /*** META ((export #t) (peephole (hole 1 "Math.floor(Math.random()*" 'n ")"))) */ function sc_random(n) { return Math.floor(Math.random()*n); } /*** META ((export current-date) (peephole (hole 0 "new Date()"))) */ function sc_currentDate() { return new Date(); } function sc_Hashtable() { } sc_Hashtable.prototype.toString = function() { return "#{%hashtable}"; }; // sc_toWriteString == sc_toDisplayString == toString function sc_HashtableElement(key, val) { this.key = key; this.val = val; } /*** META ((export #t) (peephole (hole 0 "new sc_Hashtable()"))) */ function sc_makeHashtable() { return new sc_Hashtable(); } /*** META ((export #t)) */ function sc_hashtablePutBang(ht, key, val) { var hash = sc_hash(key); ht[hash] = new sc_HashtableElement(key, val); } /*** META ((export #t)) */ function sc_hashtableGet(ht, key) { var hash = sc_hash(key); if (hash in ht) return ht[hash].val; else return false; } /*** META ((export #t)) */ function sc_hashtableForEach(ht, f) { for (var v in ht) { if (ht[v] instanceof sc_HashtableElement) f(ht[v].key, ht[v].val); } } /*** META ((export hashtable-contains?) (peephole (hole 2 "sc_hash(" 1 ") in " 0))) */ function sc_hashtableContains(ht, key) { var hash = sc_hash(key); if (hash in ht) return true; else return false; } var SC_HASH_COUNTER = 0; function sc_hash(o) { if (o === null) return "null"; else if (o === undefined) return "undefined"; else if (o === true) return "true"; else if (o === false) return "false"; else if (typeof o === "number") return "num-" + o; else if (typeof o === "string") return "jsstr-" + o; else if (o.sc_getHash) return o.sc_getHash(); else return sc_counterHash.call(o); } function sc_counterHash() { if (!this.sc_hash) { this.sc_hash = "hash-" + SC_HASH_COUNTER; SC_HASH_COUNTER++; } return this.sc_hash; } function sc_Trampoline(args, maxTailCalls) { this['__trampoline return__'] = true; this.args = args; this.MAX_TAIL_CALLs = maxTailCalls; } // TODO: call/cc stuff sc_Trampoline.prototype.restart = function() { var o = this; while (true) { // set both globals. SC_TAIL_OBJECT.calls = o.MAX_TAIL_CALLs-1; var fun = o.args.callee; var res = fun.apply(SC_TAIL_OBJECT, o.args); if (res instanceof sc_Trampoline) o = res; else return res; } } /*** META ((export bind-exit-lambda)) */ function sc_bindExitLambda(proc) { var escape_obj = new sc_BindExitException(); var escape = function(res) { escape_obj.res = res; throw escape_obj; }; try { return proc(escape); } catch(e) { if (e === escape_obj) { return e.res; } throw e; } } function sc_BindExitException() { this._internalException = true; } var SC_SCM2JS_GLOBALS = new Object(); // default tail-call depth. // normally the program should set it again. but just in case... var SC_TAIL_OBJECT = new Object(); SC_SCM2JS_GLOBALS.TAIL_OBJECT = SC_TAIL_OBJECT; // ======================== I/O ======================= /*------------------------------------------------------------------*/ function sc_EOF() { } var SC_EOF_OBJECT = new sc_EOF(); function sc_Port() { } /* --------------- Input ports -------------------------------------*/ function sc_InputPort() { } sc_InputPort.prototype = new sc_Port(); sc_InputPort.prototype.peekChar = function() { if (!("peeked" in this)) this.peeked = this.getNextChar(); return this.peeked; } sc_InputPort.prototype.readChar = function() { var tmp = this.peekChar(); delete this.peeked; return tmp; } sc_InputPort.prototype.isCharReady = function() { return true; } sc_InputPort.prototype.close = function() { // do nothing } /* .............. String port ..........................*/ function sc_ErrorInputPort() { }; sc_ErrorInputPort.prototype = new sc_InputPort(); sc_ErrorInputPort.prototype.getNextChar = function() { throw "can't read from error-port."; }; sc_ErrorInputPort.prototype.isCharReady = function() { return false; }; /* .............. String port ..........................*/ function sc_StringInputPort(jsStr) { // we are going to do some charAts on the str. // instead of recreating all the time a String-object, we // create one in the beginning. (not sure, if this is really an optim) this.str = new String(jsStr); this.pos = 0; } sc_StringInputPort.prototype = new sc_InputPort(); sc_StringInputPort.prototype.getNextChar = function() { if (this.pos >= this.str.length) return SC_EOF_OBJECT; return this.str.charAt(this.pos++); }; /* ------------- Read and other lib-funs -------------------------------*/ function sc_Token(type, val, pos) { this.type = type; this.val = val; this.pos = pos; } sc_Token.EOF = 0/*EOF*/; sc_Token.OPEN_PAR = 1/*OPEN_PAR*/; sc_Token.CLOSE_PAR = 2/*CLOSE_PAR*/; sc_Token.OPEN_BRACE = 3/*OPEN_BRACE*/; sc_Token.CLOSE_BRACE = 4/*CLOSE_BRACE*/; sc_Token.OPEN_BRACKET = 5/*OPEN_BRACKET*/; sc_Token.CLOSE_BRACKET = 6/*CLOSE_BRACKET*/; sc_Token.WHITESPACE = 7/*WHITESPACE*/; sc_Token.QUOTE = 8/*QUOTE*/; sc_Token.ID = 9/*ID*/; sc_Token.DOT = 10/*DOT*/; sc_Token.STRING = 11/*STRING*/; sc_Token.NUMBER = 12/*NUMBER*/; sc_Token.ERROR = 13/*ERROR*/; sc_Token.VECTOR_BEGIN = 14/*VECTOR_BEGIN*/; sc_Token.TRUE = 15/*TRUE*/; sc_Token.FALSE = 16/*FALSE*/; sc_Token.UNSPECIFIED = 17/*UNSPECIFIED*/; sc_Token.REFERENCE = 18/*REFERENCE*/; sc_Token.STORE = 19/*STORE*/; sc_Token.CHAR = 20/*CHAR*/; var SC_ID_CLASS = SC_LOWER_CLASS + SC_UPPER_CLASS + "!$%*+-./:<=>?@^_~"; function sc_Tokenizer(port) { this.port = port; } sc_Tokenizer.prototype.peekToken = function() { if (this.peeked) return this.peeked; var newToken = this.nextToken(); this.peeked = newToken; return newToken; }; sc_Tokenizer.prototype.readToken = function() { var tmp = this.peekToken(); delete this.peeked; return tmp; }; sc_Tokenizer.prototype.nextToken = function() { var port = this.port; function isNumberChar(c) { return (c >= "0" && c <= "9"); }; function isIdOrNumberChar(c) { return SC_ID_CLASS.indexOf(c) != -1 || // ID-char (c >= "0" && c <= "9"); } function isWhitespace(c) { return c === " " || c === "\r" || c === "\n" || c === "\t" || c === "\f"; }; function isWhitespaceOrEOF(c) { return isWhitespace(c) || c === SC_EOF_OBJECT; }; function readString() { res = ""; while (true) { var c = port.readChar(); switch (c) { case '"': return new sc_Token(11/*STRING*/, res); case "\\": var tmp = port.readChar(); switch (tmp) { case '0': res += "\0"; break; case 'a': res += "\a"; break; case 'b': res += "\b"; break; case 'f': res += "\f"; break; case 'n': res += "\n"; break; case 'r': res += "\r"; break; case 't': res += "\t"; break; case 'v': res += "\v"; break; case '"': res += '"'; break; case '\\': res += '\\'; break; case 'x': /* hexa-number */ var nb = 0; while (true) { var hexC = port.peekChar(); if (hexC >= '0' && hexC <= '9') { port.readChar(); nb = nb * 16 + hexC.charCodeAt(0) - '0'.charCodeAt(0); } else if (hexC >= 'a' && hexC <= 'f') { port.readChar(); nb = nb * 16 + hexC.charCodeAt(0) - 'a'.charCodeAt(0); } else if (hexC >= 'A' && hexC <= 'F') { port.readChar(); nb = nb * 16 + hexC.charCodeAt(0) - 'A'.charCodeAt(0); } else { // next char isn't part of hex. res += String.fromCharCode(nb); break; } } break; default: if (tmp === SC_EOF_OBJECT) { return new sc_Token(13/*ERROR*/, "unclosed string-literal" + res); } res += tmp; } break; default: if (c === SC_EOF_OBJECT) { return new sc_Token(13/*ERROR*/, "unclosed string-literal" + res); } res += c; } } }; function readIdOrNumber(firstChar) { var res = firstChar; while (isIdOrNumberChar(port.peekChar())) res += port.readChar(); if (isNaN(res)) return new sc_Token(9/*ID*/, res); else return new sc_Token(12/*NUMBER*/, res - 0); }; function skipWhitespaceAndComments() { var done = false; while (!done) { done = true; while (isWhitespace(port.peekChar())) port.readChar(); if (port.peekChar() === ';') { port.readChar(); done = false; while (true) { curChar = port.readChar(); if (curChar === SC_EOF_OBJECT || curChar === '\n') break; } } } }; function readDot() { if (isWhitespace(port.peekChar())) return new sc_Token(10/*DOT*/); else return readIdOrNumber("."); }; function readSharp() { var c = port.readChar(); if (isWhitespace(c)) return new sc_Token(13/*ERROR*/, "bad #-pattern0."); // reference if (isNumberChar(c)) { var nb = c - 0; while (isNumberChar(port.peekChar())) nb = nb*10 + (port.readChar() - 0); switch (port.readChar()) { case '#': return new sc_Token(18/*REFERENCE*/, nb); case '=': return new sc_Token(19/*STORE*/, nb); default: return new sc_Token(13/*ERROR*/, "bad #-pattern1." + nb); } } if (c === "(") return new sc_Token(14/*VECTOR_BEGIN*/); if (c === "\\") { // character var tmp = "" while (!isWhitespaceOrEOF(port.peekChar())) tmp += port.readChar(); switch (tmp.length) { case 0: // it's escaping a whitespace char: if (sc_isEOFObject(port.peekChar)) return new sc_Token(13/*ERROR*/, "bad #-pattern2."); else return new sc_Token(20/*CHAR*/, port.readChar()); case 1: return new sc_Token(20/*CHAR*/, tmp); default: var entry = sc_Char.readable2char[tmp.toLowerCase()]; if (entry) return new sc_Token(20/*CHAR*/, entry); else return new sc_Token(13/*ERROR*/, "unknown character description: #\\" + tmp); } } // some constants (#t, #f, #unspecified) var res; var needing; switch (c) { case 't': res = new sc_Token(15/*TRUE*/, true); needing = ""; break; case 'f': res = new sc_Token(16/*FALSE*/, false); needing = ""; break; case 'u': res = new sc_Token(17/*UNSPECIFIED*/, undefined); needing = "nspecified"; break; default: return new sc_Token(13/*ERROR*/, "bad #-pattern3: " + c); } while(true) { c = port.peekChar(); if ((isWhitespaceOrEOF(c) || c === ')') && needing == "") return res; else if (isWhitespace(c) || needing == "") return new sc_Token(13/*ERROR*/, "bad #-pattern4 " + c + " " + needing); else if (needing.charAt(0) == c) { port.readChar(); // consume needing = needing.slice(1); } else return new sc_Token(13/*ERROR*/, "bad #-pattern5"); } }; skipWhitespaceAndComments(); var curChar = port.readChar(); if (curChar === SC_EOF_OBJECT) return new sc_Token(0/*EOF*/, curChar); switch (curChar) { case " ": case "\n": case "\t": return readWhitespace(); case "(": return new sc_Token(1/*OPEN_PAR*/); case ")": return new sc_Token(2/*CLOSE_PAR*/); case "{": return new sc_Token(3/*OPEN_BRACE*/); case "}": return new sc_Token(4/*CLOSE_BRACE*/); case "[": return new sc_Token(5/*OPEN_BRACKET*/); case "]": return new sc_Token(6/*CLOSE_BRACKET*/); case "'": return new sc_Token(8/*QUOTE*/); case "#": return readSharp(); case ".": return readDot(); case '"': return readString(); default: if (isIdOrNumberChar(curChar)) return readIdOrNumber(curChar); throw "unexpected character: " + curChar; } }; function sc_Reader(tokenizer) { this.tokenizer = tokenizer; this.backref = new Array(); } sc_Reader.prototype.read = function() { function readList(listBeginType) { function matchesPeer(open, close) { return open === 1/*OPEN_PAR*/ && close === 2/*CLOSE_PAR*/ || open === 3/*OPEN_BRACE*/ && close === 4/*CLOSE_BRACE*/ || open === 5/*OPEN_BRACKET*/ && close === 6/*CLOSE_BRACKET*/; }; var res = null; while (true) { var token = tokenizer.peekToken(); switch (token.type) { case 2/*CLOSE_PAR*/: case 4/*CLOSE_BRACE*/: case 6/*CLOSE_BRACKET*/: if (matchesPeer(listBeginType, token.type)) { tokenizer.readToken(); // consume token return sc_reverseBang(res); } else throw "closing par doesn't match: " + listBeginType + " " + listEndType; case 0/*EOF*/: throw "unexpected end of file"; case 10/*DOT*/: tokenizer.readToken(); // consume token var cdr = this.read(); var par = tokenizer.readToken(); if (!matchesPeer(listBeginType, par.type)) throw "closing par doesn't match: " + listBeginType + " " + par.type; else return sc_reverseAppendBang(res, cdr); default: res = sc_cons(this.read(), res); } } }; function readQuote() { return sc_cons("quote", sc_cons(this.read(), null)); }; function readVector() { // opening-parenthesis is already consumed var a = new Array(); while (true) { var token = tokenizer.peekToken(); switch (token.type) { case 2/*CLOSE_PAR*/: tokenizer.readToken(); return a; default: a.push(this.read()); } } }; function storeRefence(nb) { var tmp = this.read(); this.backref[nb] = tmp; return tmp; }; function readReference(nb) { if (nb in this.backref) return this.backref[nb]; else throw "bad reference: " + nb; }; var tokenizer = this.tokenizer; var token = tokenizer.readToken(); // handle error if (token.type === 13/*ERROR*/) throw token.val; switch (token.type) { case 1/*OPEN_PAR*/: case 3/*OPEN_BRACE*/: case 5/*OPEN_BRACKET*/: return readList.call(this, token.type); case 8/*QUOTE*/: return readQuote.call(this); case 11/*STRING*/: return sc_jsstring2string(token.val); case 20/*CHAR*/: return new sc_Char(token.val); case 14/*VECTOR_BEGIN*/: return readVector.call(this); case 18/*REFERENCE*/: return readReference.call(this, token.val); case 19/*STORE*/: return storeRefence.call(this, token.val); case 9/*ID*/: return sc_jsstring2symbol(token.val); case 0/*EOF*/: case 12/*NUMBER*/: case 15/*TRUE*/: case 16/*FALSE*/: case 17/*UNSPECIFIED*/: return token.val; default: throw "unexpected token " + token.type + " " + token.val; } }; /*** META ((export #t)) */ function sc_read(port) { if (port === undefined) // we assume the port hasn't been given. port = SC_DEFAULT_IN; // THREAD: shared var... var reader = new sc_Reader(new sc_Tokenizer(port)); return reader.read(); } /*** META ((export #t)) */ function sc_readChar(port) { if (port === undefined) // we assume the port hasn't been given. port = SC_DEFAULT_IN; // THREAD: shared var... var t = port.readChar(); return t === SC_EOF_OBJECT? t: new sc_Char(t); } /*** META ((export #t)) */ function sc_peekChar(port) { if (port === undefined) // we assume the port hasn't been given. port = SC_DEFAULT_IN; // THREAD: shared var... var t = port.peekChar(); return t === SC_EOF_OBJECT? t: new sc_Char(t); } /*** META ((export #t) (type bool)) */ function sc_isCharReady(port) { if (port === undefined) // we assume the port hasn't been given. port = SC_DEFAULT_IN; // THREAD: shared var... return port.isCharReady(); } /*** META ((export #t) (peephole (postfix ".close()"))) */ function sc_closeInputPort(p) { return p.close(); } /*** META ((export #t) (type bool) (peephole (postfix " instanceof sc_InputPort"))) */ function sc_isInputPort(o) { return (o instanceof sc_InputPort); } /*** META ((export eof-object?) (type bool) (peephole (postfix " === SC_EOF_OBJECT"))) */ function sc_isEOFObject(o) { return o === SC_EOF_OBJECT; } /*** META ((export #t) (peephole (hole 0 "SC_DEFAULT_IN"))) */ function sc_currentInputPort() { return SC_DEFAULT_IN; } /* ------------ file operations are not supported -----------*/ /*** META ((export #t)) */ function sc_callWithInputFile(s, proc) { throw "can't open " + s; } /*** META ((export #t)) */ function sc_callWithOutputFile(s, proc) { throw "can't open " + s; } /*** META ((export #t)) */ function sc_withInputFromFile(s, thunk) { throw "can't open " + s; } /*** META ((export #t)) */ function sc_withOutputToFile(s, thunk) { throw "can't open " + s; } /*** META ((export #t)) */ function sc_openInputFile(s) { throw "can't open " + s; } /*** META ((export #t)) */ function sc_openOutputFile(s) { throw "can't open " + s; } /* ----------------------------------------------------------------------------*/ /*** META ((export #t)) */ function sc_basename(p) { var i = p.lastIndexOf('/'); if(i >= 0) return p.substring(i + 1, p.length); else return ''; } /*** META ((export #t)) */ function sc_dirname(p) { var i = p.lastIndexOf('/'); if(i >= 0) return p.substring(0, i); else return ''; } /* ----------------------------------------------------------------------------*/ /*** META ((export #t)) */ function sc_withInputFromPort(p, thunk) { try { var tmp = SC_DEFAULT_IN; // THREAD: shared var. SC_DEFAULT_IN = p; return thunk(); } finally { SC_DEFAULT_IN = tmp; } } /*** META ((export #t)) */ function sc_withInputFromString(s, thunk) { return sc_withInputFromPort(new sc_StringInputPort(sc_string2jsstring(s)), thunk); } /*** META ((export #t)) */ function sc_withOutputToPort(p, thunk) { try { var tmp = SC_DEFAULT_OUT; // THREAD: shared var. SC_DEFAULT_OUT = p; return thunk(); } finally { SC_DEFAULT_OUT = tmp; } } /*** META ((export #t)) */ function sc_withOutputToString(thunk) { var p = new sc_StringOutputPort(); sc_withOutputToPort(p, thunk); return p.close(); } /*** META ((export #t)) */ function sc_withOutputToProcedure(proc, thunk) { var t = function(s) { proc(sc_jsstring2string(s)); }; return sc_withOutputToPort(new sc_GenericOutputPort(t), thunk); } /*** META ((export #t) (peephole (hole 0 "new sc_StringOutputPort()"))) */ function sc_openOutputString() { return new sc_StringOutputPort(); } /*** META ((export #t)) */ function sc_openInputString(str) { return new sc_StringInputPort(sc_string2jsstring(str)); } /* ----------------------------------------------------------------------------*/ function sc_OutputPort() { } sc_OutputPort.prototype = new sc_Port(); sc_OutputPort.prototype.appendJSString = function(obj) { /* do nothing */ } sc_OutputPort.prototype.close = function() { /* do nothing */ } function sc_StringOutputPort() { this.res = ""; } sc_StringOutputPort.prototype = new sc_OutputPort(); sc_StringOutputPort.prototype.appendJSString = function(s) { this.res += s; } sc_StringOutputPort.prototype.close = function() { return sc_jsstring2string(this.res); } /*** META ((export #t)) */ function sc_getOutputString(sp) { return sc_jsstring2string(sp.res); } function sc_ErrorOutputPort() { } sc_ErrorOutputPort.prototype = new sc_OutputPort(); sc_ErrorOutputPort.prototype.appendJSString = function(s) { throw "don't write on ErrorPort!"; } sc_ErrorOutputPort.prototype.close = function() { /* do nothing */ } function sc_GenericOutputPort(appendJSString, close) { this.appendJSString = appendJSString; if (close) this.close = close; } sc_GenericOutputPort.prototype = new sc_OutputPort(); /*** META ((export #t) (type bool) (peephole (postfix " instanceof sc_OutputPort"))) */ function sc_isOutputPort(o) { return (o instanceof sc_OutputPort); } /*** META ((export #t) (peephole (postfix ".close()"))) */ function sc_closeOutputPort(p) { return p.close(); } /* ------------------ write ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_write(o, p) { if (p === undefined) // we assume not given p = SC_DEFAULT_OUT; p.appendJSString(sc_toWriteString(o)); } function sc_toWriteString(o) { if (o === null) return "()"; else if (o === true) return "#t"; else if (o === false) return "#f"; else if (o === undefined) return "#unspecified"; else if (typeof o === 'function') return "#"; else if (o.sc_toWriteString) return o.sc_toWriteString(); else return o.toString(); } function sc_escapeWriteString(s) { var res = ""; var j = 0; for (i = 0; i < s.length; i++) { switch (s.charAt(i)) { case "\0": res += s.substring(j, i) + "\\0"; j = i + 1; break; case "\b": res += s.substring(j, i) + "\\b"; j = i + 1; break; case "\f": res += s.substring(j, i) + "\\f"; j = i + 1; break; case "\n": res += s.substring(j, i) + "\\n"; j = i + 1; break; case "\r": res += s.substring(j, i) + "\\r"; j = i + 1; break; case "\t": res += s.substring(j, i) + "\\t"; j = i + 1; break; case "\v": res += s.substring(j, i) + "\\v"; j = i + 1; break; case '"': res += s.substring(j, i) + '\\"'; j = i + 1; break; case "\\": res += s.substring(j, i) + "\\\\"; j = i + 1; break; default: var c = s.charAt(i); if ("\a" !== "a" && c == "\a") { res += s.substring(j, i) + "\\a"; j = i + 1; continue; } if ("\v" !== "v" && c == "\v") { res += s.substring(j, i) + "\\v"; j = i + 1; continue; } //if (s.charAt(i) < ' ' || s.charCodeAt(i) > 127) { // CARE: Manuel is this OK with HOP? if (s.charAt(i) < ' ') { /* non printable character and special chars */ res += s.substring(j, i) + "\\x" + s.charCodeAt(i).toString(16); j = i + 1; } // else just let i increase... } } res += s.substring(j, i); return res; } /* ------------------ display ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_display(o, p) { if (p === undefined) // we assume not given p = SC_DEFAULT_OUT; p.appendJSString(sc_toDisplayString(o)); } function sc_toDisplayString(o) { if (o === null) return "()"; else if (o === true) return "#t"; else if (o === false) return "#f"; else if (o === undefined) return "#unspecified"; else if (typeof o === 'function') return "#"; else if (o.sc_toDisplayString) return o.sc_toDisplayString(); else return o.toString(); } /* ------------------ newline ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_newline(p) { if (p === undefined) // we assume not given p = SC_DEFAULT_OUT; p.appendJSString("\n"); } /* ------------------ write-char ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_writeChar(c, p) { if (p === undefined) // we assume not given p = SC_DEFAULT_OUT; p.appendJSString(c.val); } /* ------------------ write-circle ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_writeCircle(o, p) { if (p === undefined) // we assume not given p = SC_DEFAULT_OUT; p.appendJSString(sc_toWriteCircleString(o)); } function sc_toWriteCircleString(o) { var symb = sc_gensym("writeCircle"); var nbPointer = new Object(); nbPointer.nb = 0; sc_prepWriteCircle(o, symb, nbPointer); return sc_genToWriteCircleString(o, symb); } function sc_prepWriteCircle(o, symb, nbPointer) { // TODO sc_Struct if (o instanceof sc_Pair || o instanceof sc_Vector) { if (o[symb] !== undefined) { // not the first visit. o[symb]++; // unless there is already a number, assign one. if (!o[symb + "nb"]) o[symb + "nb"] = nbPointer.nb++; return; } o[symb] = 0; if (o instanceof sc_Pair) { sc_prepWriteCircle(o.car, symb, nbPointer); sc_prepWriteCircle(o.cdr, symb, nbPointer); } else { for (var i = 0; i < o.length; i++) sc_prepWriteCircle(o[i], symb, nbPointer); } } } function sc_genToWriteCircleString(o, symb) { if (!(o instanceof sc_Pair || o instanceof sc_Vector)) return sc_toWriteString(o); return o.sc_toWriteCircleString(symb); } sc_Pair.prototype.sc_toWriteCircleString = function(symb, inList) { if (this[symb + "use"]) { // use-flag is set. Just use it. var nb = this[symb + "nb"]; if (this[symb]-- === 0) { // if we are the last use. remove all fields. delete this[symb]; delete this[symb + "nb"]; delete this[symb + "use"]; } if (inList) return '. #' + nb + '#'; else return '#' + nb + '#'; } if (this[symb]-- === 0) { // if we are the last use. remove all fields. delete this[symb]; delete this[symb + "nb"]; delete this[symb + "use"]; } var res = ""; if (this[symb] !== undefined) { // implies > 0 this[symb + "use"] = true; if (inList) res += '. #' + this[symb + "nb"] + '='; else res += '#' + this[symb + "nb"] + '='; inList = false; } if (!inList) res += "("; // print car res += sc_genToWriteCircleString(this.car, symb); if (sc_isPair(this.cdr)) { res += " " + this.cdr.sc_toWriteCircleString(symb, true); } else if (this.cdr !== null) { res += " . " + sc_genToWriteCircleString(this.cdr, symb); } if (!inList) res += ")"; return res; }; sc_Vector.prototype.sc_toWriteCircleString = function(symb) { if (this[symb + "use"]) { // use-flag is set. Just use it. var nb = this[symb + "nb"]; if (this[symb]-- === 0) { // if we are the last use. remove all fields. delete this[symb]; delete this[symb + "nb"]; delete this[symb + "use"]; } return '#' + nb + '#'; } if (this[symb]-- === 0) { // if we are the last use. remove all fields. delete this[symb]; delete this[symb + "nb"]; delete this[symb + "use"]; } var res = ""; if (this[symb] !== undefined) { // implies > 0 this[symb + "use"] = true; res += '#' + this[symb + "nb"] + '='; } res += "#("; for (var i = 0; i < this.length; i++) { res += sc_genToWriteCircleString(this[i], symb); if (i < this.length - 1) res += " "; } res += ")"; return res; }; /* ------------------ print ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_print(s) { if (arguments.length === 1) { sc_display(s); sc_newline(); } else { for (var i = 0; i < arguments.length; i++) sc_display(arguments[i]); sc_newline(); } } /* ------------------ format ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_format(s, args) { var len = s.length; var p = new sc_StringOutputPort(); var i = 0, j = 1; while( i < len ) { var i2 = s.indexOf("~", i); if (i2 == -1) { p.appendJSString( s.substring( i, len ) ); return p.close(); } else { if (i2 > i) { if (i2 == (len - 1)) { p.appendJSString(s.substring(i, len)); return p.close(); } else { p.appendJSString(s.substring(i, i2)); i = i2; } } switch(s.charCodeAt(i2 + 1)) { case 65: case 97: // a sc_display(arguments[j], p); i += 2; j++; break; case 83: case 115: // s sc_write(arguments[j], p); i += 2; j++; break; case 86: case 118: // v sc_display(arguments[j], p); p.appendJSString("\n"); i += 2; j++; break; case 67: case 99: // c p.appendJSString(String.fromCharCode(arguments[j])); i += 2; j++; break; case 88: case 120: // x p.appendJSString(arguments[j].toString(6)); i += 2; j++; break; case 79: case 111: // o p.appendJSString(arguments[j].toString(8)); i += 2; j++; break; case 66: case 98: // b p.appendJSString(arguments[j].toString(2)); i += 2; j++; break; case 37: case 110: // %, n p.appendJSString("\n"); i += 2; break; case 114: // r p.appendJSString("\r"); i += 2; break; case 126: // ~ p.appendJSString("~"); i += 2; break; default: sc_error( "format: illegal ~" + String.fromCharCode(s.charCodeAt(i2 + 1)) + " sequence" ); return ""; } } } return p.close(); } /* ------------------ global ports ---------------------------------------------------*/ var SC_DEFAULT_IN = new sc_ErrorInputPort(); var SC_DEFAULT_OUT = new sc_ErrorOutputPort(); var SC_ERROR_OUT = new sc_ErrorOutputPort(); var sc_SYMBOL_PREFIX = "\u1E9C"; var sc_KEYWORD_PREFIX = "\u1E9D"; /*** META ((export #t) (peephole (id))) */ function sc_jsstring2string(s) { return s; } /*** META ((export #t) (peephole (prefix "'\\u1E9C' +"))) */ function sc_jsstring2symbol(s) { return sc_SYMBOL_PREFIX + s; } /*** META ((export #t) (peephole (id))) */ function sc_string2jsstring(s) { return s; } /*** META ((export #t) (peephole (symbol2jsstring_immutable))) */ function sc_symbol2jsstring(s) { return s.slice(1); } /*** META ((export #t) (peephole (postfix ".slice(1)"))) */ function sc_keyword2jsstring(k) { return k.slice(1); } /*** META ((export #t) (peephole (prefix "'\\u1E9D' +"))) */ function sc_jsstring2keyword(s) { return sc_KEYWORD_PREFIX + s; } /*** META ((export #t) (type bool)) */ function sc_isKeyword(s) { return (typeof s === "string") && (s.charAt(0) === sc_KEYWORD_PREFIX); } /*** META ((export #t)) */ var sc_gensym = function() { var counter = 1000; return function(sym) { counter++; if (!sym) sym = sc_SYMBOL_PREFIX; return sym + "s" + counter + "~" + "^sC-GeNsYm "; }; }(); /*** META ((export #t) (type bool)) */ function sc_isEqual(o1, o2) { return ((o1 === o2) || (sc_isPair(o1) && sc_isPair(o2) && sc_isPairEqual(o1, o2, sc_isEqual)) || (sc_isVector(o1) && sc_isVector(o2) && sc_isVectorEqual(o1, o2, sc_isEqual))); } /*** META ((export number->symbol integer->symbol)) */ function sc_number2symbol(x, radix) { return sc_SYMBOL_PREFIX + sc_number2jsstring(x, radix); } /*** META ((export number->string integer->string)) */ var sc_number2string = sc_number2jsstring; /*** META ((export #t)) */ function sc_symbol2number(s, radix) { return sc_jsstring2number(s.slice(1), radix); } /*** META ((export #t)) */ var sc_string2number = sc_jsstring2number; /*** META ((export #t) (peephole (prefix "+" s))) ;; peephole will only apply if no radix is given. */ function sc_string2integer(s, radix) { if (!radix) return +s; return parseInt(s, radix); } /*** META ((export #t) (peephole (prefix "+"))) */ function sc_string2real(s) { return +s; } /*** META ((export #t) (type bool)) */ function sc_isSymbol(s) { return (typeof s === "string") && (s.charAt(0) === sc_SYMBOL_PREFIX); } /*** META ((export #t) (peephole (symbol2string_immutable))) */ function sc_symbol2string(s) { return s.slice(1); } /*** META ((export #t) (peephole (prefix "'\\u1E9C' +"))) */ function sc_string2symbol(s) { return sc_SYMBOL_PREFIX + s; } /*** META ((export symbol-append) (peephole (symbolAppend_immutable))) */ function sc_symbolAppend() { var res = sc_SYMBOL_PREFIX; for (var i = 0; i < arguments.length; i++) res += arguments[i].slice(1); return res; } /*** META ((export #t) (peephole (postfix ".val"))) */ function sc_char2string(c) { return c.val; } /*** META ((export #t) (peephole (hole 1 "'\\u1E9C' + " c ".val"))) */ function sc_char2symbol(c) { return sc_SYMBOL_PREFIX + c.val; } /*** META ((export #t) (type bool)) */ function sc_isString(s) { return (typeof s === "string") && (s.charAt(0) !== sc_SYMBOL_PREFIX); } /*** META ((export #t)) */ var sc_makeString = sc_makejsString; /*** META ((export #t)) */ function sc_string() { for (var i = 0; i < arguments.length; i++) arguments[i] = arguments[i].val; return "".concat.apply("", arguments); } /*** META ((export #t) (peephole (postfix ".length"))) */ function sc_stringLength(s) { return s.length; } /*** META ((export #t)) */ function sc_stringRef(s, k) { return new sc_Char(s.charAt(k)); } /* there's no stringSet in the immutable version function sc_stringSet(s, k, c) */ /*** META ((export string=?) (type bool) (peephole (hole 2 str1 " === " str2))) */ function sc_isStringEqual(s1, s2) { return s1 === s2; } /*** META ((export string?) (type bool) (peephole (hole 2 str1 " > " str2))) */ function sc_isStringGreater(s1, s2) { return s1 > s2; } /*** META ((export string<=?) (type bool) (peephole (hole 2 str1 " <= " str2))) */ function sc_isStringLessEqual(s1, s2) { return s1 <= s2; } /*** META ((export string>=?) (type bool) (peephole (hole 2 str1 " >= " str2))) */ function sc_isStringGreaterEqual(s1, s2) { return s1 >= s2; } /*** META ((export string-ci=?) (type bool) (peephole (hole 2 str1 ".toLowerCase() === " str2 ".toLowerCase()"))) */ function sc_isStringCIEqual(s1, s2) { return s1.toLowerCase() === s2.toLowerCase(); } /*** META ((export string-ci?) (type bool) (peephole (hole 2 str1 ".toLowerCase() > " str2 ".toLowerCase()"))) */ function sc_isStringCIGreater(s1, s2) { return s1.toLowerCase() > s2.toLowerCase(); } /*** META ((export string-ci<=?) (type bool) (peephole (hole 2 str1 ".toLowerCase() <= " str2 ".toLowerCase()"))) */ function sc_isStringCILessEqual(s1, s2) { return s1.toLowerCase() <= s2.toLowerCase(); } /*** META ((export string-ci>=?) (type bool) (peephole (hole 2 str1 ".toLowerCase() >= " str2 ".toLowerCase()"))) */ function sc_isStringCIGreaterEqual(s1, s2) { return s1.toLowerCase() >= s2.toLowerCase(); } /*** META ((export #t) (peephole (hole 3 s ".substring(" start ", " end ")"))) */ function sc_substring(s, start, end) { return s.substring(start, end); } /*** META ((export #t)) */ function sc_isSubstring_at(s1, s2, i) { return s2 == s1.substring(i, i+ s2.length); } /*** META ((export #t) (peephole (infix 0 #f "+" "''"))) */ function sc_stringAppend() { return "".concat.apply("", arguments); } /*** META ((export #t)) */ var sc_string2list = sc_jsstring2list; /*** META ((export #t)) */ var sc_list2string = sc_list2jsstring; /*** META ((export #t) (peephole (id))) */ function sc_stringCopy(s) { return s; } /* there's no string-fill in the immutable version function sc_stringFill(s, c) */ /*** META ((export #t) (peephole (postfix ".slice(1)"))) */ function sc_keyword2string(o) { return o.slice(1); } /*** META ((export #t) (peephole (prefix "'\\u1E9D' +"))) */ function sc_string2keyword(o) { return sc_KEYWORD_PREFIX + o; } String.prototype.sc_toDisplayString = function() { if (this.charAt(0) === sc_SYMBOL_PREFIX) // TODO: care for symbols with spaces (escape-chars symbols). return this.slice(1); else if (this.charAt(0) === sc_KEYWORD_PREFIX) return ":" + this.slice(1); else return this.toString(); }; String.prototype.sc_toWriteString = function() { if (this.charAt(0) === sc_SYMBOL_PREFIX) // TODO: care for symbols with spaces (escape-chars symbols). return this.slice(1); else if (this.charAt(0) === sc_KEYWORD_PREFIX) return ":" + this.slice(1); else return '"' + sc_escapeWriteString(this) + '"'; }; /* Exported Variables */ var BgL_testzd2boyerzd2; var BgL_nboyerzd2benchmarkzd2; var BgL_setupzd2boyerzd2; /* End Exports */ var translate_term_nboyer; var translate_args_nboyer; var untranslate_term_nboyer; var BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer; var BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer; var translate_alist_nboyer; var apply_subst_nboyer; var apply_subst_lst_nboyer; var tautologyp_nboyer; var if_constructor_nboyer; var rewrite_count_nboyer; var rewrite_nboyer; var rewrite_args_nboyer; var unify_subst_nboyer; var one_way_unify1_nboyer; var false_term_nboyer; var true_term_nboyer; var trans_of_implies1_nboyer; var is_term_equal_nboyer; var is_term_member_nboyer; var const_nboyer; var sc_const_3_nboyer; var sc_const_4_nboyer; { (sc_const_4_nboyer = (new sc_Pair("\u1E9Cimplies",(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cu",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cu",(new sc_Pair("\u1E9Cw",null)))))),null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cw",null)))))),null))))))); (sc_const_3_nboyer = sc_list((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccompile",(new sc_Pair("\u1E9Cform",null)))),(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair((new sc_Pair("\u1E9Ccodegen",(new sc_Pair((new sc_Pair("\u1E9Coptimize",(new sc_Pair("\u1E9Cform",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ceqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreaterp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clesseqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatereqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cboolean",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ciff",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ceven1",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Codd",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccountps-",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Cpred",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccountps-loop",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Cpred",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfact-",(new sc_Pair("\u1E9Ci",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfact-loop",(new sc_Pair("\u1E9Ci",(new sc_Pair((1),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse-",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Creverse-loop",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdivides",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cassume-true",(new sc_Pair("\u1E9Cvar",(new sc_Pair("\u1E9Calist",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cvar",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))),(new sc_Pair("\u1E9Calist",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cassume-false",(new sc_Pair("\u1E9Cvar",(new sc_Pair("\u1E9Calist",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cvar",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))),(new sc_Pair("\u1E9Calist",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctautology-checker",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ctautologyp",(new sc_Pair((new sc_Pair("\u1E9Cnormalize",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfalsify",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfalsify1",(new sc_Pair((new sc_Pair("\u1E9Cnormalize",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cprime",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))),null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cprime1",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Cx",null)))),null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair("\u1E9Cp",(new sc_Pair("\u1E9Cq",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cq",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair("\u1E9Cp",(new sc_Pair("\u1E9Cq",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cq",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair("\u1E9Cp",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cp",(new sc_Pair("\u1E9Cq",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cq",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))))),(new sc_Pair("\u1E9Cd",(new sc_Pair("\u1E9Ce",null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cd",(new sc_Pair("\u1E9Ce",null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cd",(new sc_Pair("\u1E9Ce",null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Ca",null)))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cb",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cc",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair("\u1E9Ca",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair((new sc_Pair("\u1E9Cplus-fringe",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Ca",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cexec",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cpds",(new sc_Pair("\u1E9Cenvrn",null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cexec",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cexec",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cpds",(new sc_Pair("\u1E9Cenvrn",null)))))))),(new sc_Pair("\u1E9Cenvrn",null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmc-flatten",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Cy",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cb",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cy",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Cintersect",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Ck",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Ck",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Ck",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),(new sc_Pair("\u1E9Ck",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse-loop",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Cy",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse-loop",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccount-list",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Csort-lp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Ccount-list",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccount-list",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cbig-plus1",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair("\u1E9Ci",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cbig-plus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cbase",null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Ci",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cj",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cj",(new sc_Pair((1),null)))))),null)))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cpower-rep",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Ci",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cbig-plus",(new sc_Pair((new sc_Pair("\u1E9Cpower-rep",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cpower-rep",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair("\u1E9Cbase",null)))))))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair("\u1E9Cb",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Ca",null)))),null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cy",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cy",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cw",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cw",(new sc_Pair("\u1E9Cx",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cb",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cy",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cz",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cvalue",(new sc_Pair((new sc_Pair("\u1E9Cnormalize",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cvalue",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnlistp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair((new sc_Pair("\u1E9Cgopher",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csamefringe",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatest-factor",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatest-factor",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((1),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((1),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair((new sc_Pair("\u1E9Cgreatest-factor",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes-list",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Ctimes-list",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ctimes-list",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cprime-list",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cprime-list",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cprime-list",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cw",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cz",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cw",(new sc_Pair((1),null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatereqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((1),null)))))),(new sc_Pair(sc_list("\u1E9Cand", (new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))), (new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cb",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))), (new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Ca",null)))), (new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cb",null)))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Ca",null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cl",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cl",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cl",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csort2",(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cl",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Csort2",(new sc_Pair("\u1E9Cl",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdsort",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Csort2",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx1",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx2",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx3",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx4",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx5",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx6",(new sc_Pair("\u1E9Cx7",null)))))),null)))))),null)))))),null)))))),null)))))),null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((6),(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cx7",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((2),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((2),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair("\u1E9Cy",(new sc_Pair((2),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csigma",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Ci",null)))),null)))))),(new sc_Pair((2),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cy",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cx",null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cz",null)))),null)))))),null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair("\u1E9Ca",null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cy",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Ci",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clast",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Clast",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Ca",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Ccar",(new sc_Pair((new sc_Pair("\u1E9Clast",(new sc_Pair("\u1E9Ca",null)))),null)))),(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair("\u1E9Cb",null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),(new sc_Pair("\u1E9Cz",null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cassignment",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cassignedp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cassignment",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cassignment",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cb",null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccar",(new sc_Pair((new sc_Pair("\u1E9Cgopher",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccar",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair((new sc_Pair("\u1E9Ccdr",(new sc_Pair((new sc_Pair("\u1E9Cgopher",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccdr",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cget",(new sc_Pair("\u1E9Cj",(new sc_Pair((new sc_Pair("\u1E9Cset",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cval",(new sc_Pair("\u1E9Cmem",null)))))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Ceqp",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair("\u1E9Cval",(new sc_Pair((new sc_Pair("\u1E9Cget",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Cmem",null)))))),null)))))))),null)))))))); (const_nboyer = (new sc_Pair((new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cf",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cc",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cf",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cd",null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cf",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cu",(new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cw",(new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cb",null)))),null)))))),null)))))))),null))))))))))); BgL_nboyerzd2benchmarkzd2 = function() { var args = null; for (var sc_tmp = arguments.length - 1; sc_tmp >= 0; sc_tmp--) { args = sc_cons(arguments[sc_tmp], args); } var n; return ((n = ((args === null)?(0):(args.car))), (BgL_setupzd2boyerzd2()), (BgL_runzd2benchmarkzd2(("nboyer"+(sc_number2string(n))), (1), function() { return (BgL_testzd2boyerzd2(n)); }, function(rewrites) { if ((sc_isNumber(rewrites))) switch (n) { case (0): return (rewrites===(95024)); break; case (1): return (rewrites===(591777)); break; case (2): return (rewrites===(1813975)); break; case (3): return (rewrites===(5375678)); break; case (4): return (rewrites===(16445406)); break; case (5): return (rewrites===(51507739)); break; default: return true; break; } else return false; }))); }; BgL_setupzd2boyerzd2 = function() { return true; }; BgL_testzd2boyerzd2 = function() { return true; }; translate_term_nboyer = function(term) { var lst; return (!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), ((lst = (term.cdr)), ((lst === null)?null:(new sc_Pair((translate_term_nboyer((lst.car))), (translate_args_nboyer((lst.cdr)))))))))); }; translate_args_nboyer = function(lst) { var sc_lst_5; var term; return ((lst === null)?null:(new sc_Pair(((term = (lst.car)), (!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), (translate_args_nboyer((term.cdr))))))), ((sc_lst_5 = (lst.cdr)), ((sc_lst_5 === null)?null:(new sc_Pair((translate_term_nboyer((sc_lst_5.car))), (translate_args_nboyer((sc_lst_5.cdr)))))))))); }; untranslate_term_nboyer = function(term) { var optrOpnd; var tail1131; var L1127; var falseHead1130; var symbol_record; if (!(term instanceof sc_Pair)) return term; else { (falseHead1130 = (new sc_Pair(null, null))); (L1127 = (term.cdr)); (tail1131 = falseHead1130); while (!(L1127 === null)) { { (tail1131.cdr = (new sc_Pair((untranslate_term_nboyer((L1127.car))), null))); (tail1131 = (tail1131.cdr)); (L1127 = (L1127.cdr)); } } (optrOpnd = (falseHead1130.cdr)); return (new sc_Pair(((symbol_record = (term.car)), (symbol_record[(0)])), optrOpnd)); } }; BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer = function(sym) { var r; var x; return ((x = (sc_assq(sym, BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer))), ((x!== false)?(x.cdr):((r = [sym, null]), (BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer = (new sc_Pair((new sc_Pair(sym, r)), BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer))), r))); }; (BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer = null); translate_alist_nboyer = function(alist) { var sc_alist_6; var term; return ((alist === null)?null:(new sc_Pair((new sc_Pair((alist.car.car), ((term = (alist.car.cdr)), (!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), (translate_args_nboyer((term.cdr))))))))), ((sc_alist_6 = (alist.cdr)), ((sc_alist_6 === null)?null:(new sc_Pair((new sc_Pair((sc_alist_6.car.car), (translate_term_nboyer((sc_alist_6.car.cdr))))), (translate_alist_nboyer((sc_alist_6.cdr)))))))))); }; apply_subst_nboyer = function(alist, term) { var lst; var temp_temp; return (!(term instanceof sc_Pair)?((temp_temp = (sc_assq(term, alist))), ((temp_temp!== false)?(temp_temp.cdr):term)):(new sc_Pair((term.car), ((lst = (term.cdr)), ((lst === null)?null:(new sc_Pair((apply_subst_nboyer(alist, (lst.car))), (apply_subst_lst_nboyer(alist, (lst.cdr)))))))))); }; apply_subst_lst_nboyer = function(alist, lst) { var sc_lst_7; return ((lst === null)?null:(new sc_Pair((apply_subst_nboyer(alist, (lst.car))), ((sc_lst_7 = (lst.cdr)), ((sc_lst_7 === null)?null:(new sc_Pair((apply_subst_nboyer(alist, (sc_lst_7.car))), (apply_subst_lst_nboyer(alist, (sc_lst_7.cdr)))))))))); }; tautologyp_nboyer = function(sc_x_11, true_lst, false_lst) { var tmp1125; var x; var tmp1126; var sc_x_8; var sc_tmp1125_9; var sc_tmp1126_10; var sc_x_11; var true_lst; var false_lst; while (true) { if ((((sc_tmp1126_10 = (is_term_equal_nboyer(sc_x_11, true_term_nboyer))), ((sc_tmp1126_10!== false)?sc_tmp1126_10:(is_term_member_nboyer(sc_x_11, true_lst))))!== false)) return true; else if ((((sc_tmp1125_9 = (is_term_equal_nboyer(sc_x_11, false_term_nboyer))), ((sc_tmp1125_9!== false)?sc_tmp1125_9:(is_term_member_nboyer(sc_x_11, false_lst))))!== false)) return false; else if (!(sc_x_11 instanceof sc_Pair)) return false; else if (((sc_x_11.car)===if_constructor_nboyer)) if ((((sc_x_8 = (sc_x_11.cdr.car)), (tmp1126 = (is_term_equal_nboyer(sc_x_8, true_term_nboyer))), ((tmp1126!== false)?tmp1126:(is_term_member_nboyer(sc_x_8, true_lst))))!== false)) (sc_x_11 = (sc_x_11.cdr.cdr.car)); else if ((((x = (sc_x_11.cdr.car)), (tmp1125 = (is_term_equal_nboyer(x, false_term_nboyer))), ((tmp1125!== false)?tmp1125:(is_term_member_nboyer(x, false_lst))))!== false)) (sc_x_11 = (sc_x_11.cdr.cdr.cdr.car)); else if (((tautologyp_nboyer((sc_x_11.cdr.cdr.car), (new sc_Pair((sc_x_11.cdr.car), true_lst)), false_lst))!== false)) { (false_lst = (new sc_Pair((sc_x_11.cdr.car), false_lst))); (sc_x_11 = (sc_x_11.cdr.cdr.cdr.car)); } else return false; else return false; } }; (if_constructor_nboyer = "\u1E9C*"); (rewrite_count_nboyer = (0)); rewrite_nboyer = function(term) { var term2; var sc_term_12; var lst; var symbol_record; var sc_lst_13; { (++rewrite_count_nboyer); if (!(term instanceof sc_Pair)) return term; else { (sc_term_12 = (new sc_Pair((term.car), ((sc_lst_13 = (term.cdr)), ((sc_lst_13 === null)?null:(new sc_Pair((rewrite_nboyer((sc_lst_13.car))), (rewrite_args_nboyer((sc_lst_13.cdr)))))))))); (lst = ((symbol_record = (term.car)), (symbol_record[(1)]))); while (true) { if ((lst === null)) return sc_term_12; else if ((((term2 = ((lst.car).cdr.car)), (unify_subst_nboyer = null), (one_way_unify1_nboyer(sc_term_12, term2)))!== false)) return (rewrite_nboyer((apply_subst_nboyer(unify_subst_nboyer, ((lst.car).cdr.cdr.car))))); else (lst = (lst.cdr)); } } } }; rewrite_args_nboyer = function(lst) { var sc_lst_14; return ((lst === null)?null:(new sc_Pair((rewrite_nboyer((lst.car))), ((sc_lst_14 = (lst.cdr)), ((sc_lst_14 === null)?null:(new sc_Pair((rewrite_nboyer((sc_lst_14.car))), (rewrite_args_nboyer((sc_lst_14.cdr)))))))))); }; (unify_subst_nboyer = "\u1E9C*"); one_way_unify1_nboyer = function(term1, term2) { var lst1; var lst2; var temp_temp; if (!(term2 instanceof sc_Pair)) { (temp_temp = (sc_assq(term2, unify_subst_nboyer))); if ((temp_temp!== false)) return (is_term_equal_nboyer(term1, (temp_temp.cdr))); else if ((sc_isNumber(term2))) return (sc_isEqual(term1, term2)); else { (unify_subst_nboyer = (new sc_Pair((new sc_Pair(term2, term1)), unify_subst_nboyer))); return true; } } else if (!(term1 instanceof sc_Pair)) return false; else if (((term1.car)===(term2.car))) { (lst1 = (term1.cdr)); (lst2 = (term2.cdr)); while (true) { if ((lst1 === null)) return (lst2 === null); else if ((lst2 === null)) return false; else if (((one_way_unify1_nboyer((lst1.car), (lst2.car)))!== false)) { (lst1 = (lst1.cdr)); (lst2 = (lst2.cdr)); } else return false; } } else return false; }; (false_term_nboyer = "\u1E9C*"); (true_term_nboyer = "\u1E9C*"); trans_of_implies1_nboyer = function(n) { var sc_n_15; return ((sc_isEqual(n, (1)))?(sc_list("\u1E9Cimplies", (0), (1))):(sc_list("\u1E9Cand", (sc_list("\u1E9Cimplies", (n-(1)), n)), ((sc_n_15 = (n-(1))), ((sc_isEqual(sc_n_15, (1)))?(sc_list("\u1E9Cimplies", (0), (1))):(sc_list("\u1E9Cand", (sc_list("\u1E9Cimplies", (sc_n_15-(1)), sc_n_15)), (trans_of_implies1_nboyer((sc_n_15-(1))))))))))); }; is_term_equal_nboyer = function(x, y) { var lst1; var lst2; var r2; var r1; if ((x instanceof sc_Pair)) if ((y instanceof sc_Pair)) if ((((r1 = (x.car)), (r2 = (y.car)), (r1===r2))!== false)) { (lst1 = (x.cdr)); (lst2 = (y.cdr)); while (true) { if ((lst1 === null)) return (lst2 === null); else if ((lst2 === null)) return false; else if (((is_term_equal_nboyer((lst1.car), (lst2.car)))!== false)) { (lst1 = (lst1.cdr)); (lst2 = (lst2.cdr)); } else return false; } } else return false; else return false; else return (sc_isEqual(x, y)); }; is_term_member_nboyer = function(x, lst) { var x; var lst; while (true) { if ((lst === null)) return false; else if (((is_term_equal_nboyer(x, (lst.car)))!== false)) return true; else (lst = (lst.cdr)); } }; BgL_setupzd2boyerzd2 = function() { var symbol_record; var value; var BgL_sc_symbolzd2record_16zd2; var sym; var sc_sym_17; var term; var lst; var sc_term_18; var sc_term_19; { (BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer = null); (if_constructor_nboyer = (BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer("\u1E9Cif"))); (false_term_nboyer = ((sc_term_19 = (new sc_Pair("\u1E9Cf",null))), (!(sc_term_19 instanceof sc_Pair)?sc_term_19:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((sc_term_19.car))), (translate_args_nboyer((sc_term_19.cdr)))))))); (true_term_nboyer = ((sc_term_18 = (new sc_Pair("\u1E9Ct",null))), (!(sc_term_18 instanceof sc_Pair)?sc_term_18:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((sc_term_18.car))), (translate_args_nboyer((sc_term_18.cdr)))))))); (lst = sc_const_3_nboyer); while (!(lst === null)) { { (term = (lst.car)); if (((term instanceof sc_Pair)&&(((term.car)==="\u1E9Cequal")&&((term.cdr.car) instanceof sc_Pair)))) { (sc_sym_17 = ((term.cdr.car).car)); (value = (new sc_Pair((!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), (translate_args_nboyer((term.cdr)))))), ((sym = ((term.cdr.car).car)), (BgL_sc_symbolzd2record_16zd2 = (BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer(sym))), (BgL_sc_symbolzd2record_16zd2[(1)]))))); (symbol_record = (BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer(sc_sym_17))); (symbol_record[(1)] = value); } else (sc_error("ADD-LEMMA did not like term: ", term)); (lst = (lst.cdr)); } } return true; } }; BgL_testzd2boyerzd2 = function(n) { var optrOpnd; var term; var sc_n_20; var answer; var sc_term_21; var sc_term_22; { (rewrite_count_nboyer = (0)); (term = sc_const_4_nboyer); (sc_n_20 = n); while (!(sc_n_20=== 0)) { { (term = (sc_list("\u1E9Cor", term, (new sc_Pair("\u1E9Cf",null))))); (--sc_n_20); } } (sc_term_22 = term); if (!(sc_term_22 instanceof sc_Pair)) (optrOpnd = sc_term_22); else (optrOpnd = (new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((sc_term_22.car))), (translate_args_nboyer((sc_term_22.cdr)))))); (sc_term_21 = (apply_subst_nboyer(((const_nboyer === null)?null:(new sc_Pair((new sc_Pair((const_nboyer.car.car), (translate_term_nboyer((const_nboyer.car.cdr))))), (translate_alist_nboyer((const_nboyer.cdr)))))), optrOpnd))); (answer = (tautologyp_nboyer((rewrite_nboyer(sc_term_21)), null, null))); (sc_write(rewrite_count_nboyer)); (sc_display(" rewrites")); (sc_newline()); if ((answer!== false)) return rewrite_count_nboyer; else return false; } }; } /* Exported Variables */ var BgL_parsezd2ze3nbzd2treesze3; var BgL_earleyzd2benchmarkzd2; var BgL_parsezd2ze3parsedzf3zc2; var test; var BgL_parsezd2ze3treesz31; var BgL_makezd2parserzd2; /* End Exports */ var const_earley; { (const_earley = (new sc_Pair((new sc_Pair("\u1E9Cs",(new sc_Pair((new sc_Pair("\u1E9Ca",null)),(new sc_Pair((new sc_Pair("\u1E9Cs",(new sc_Pair("\u1E9Cs",null)))),null)))))),null))); BgL_makezd2parserzd2 = function(grammar, lexer) { var i; var parser_descr; var def_loop; var nb_nts; var names; var steps; var predictors; var enders; var starters; var nts; var sc_names_1; var sc_steps_2; var sc_predictors_3; var sc_enders_4; var sc_starters_5; var nb_confs; var BgL_sc_defzd2loop_6zd2; var BgL_sc_nbzd2nts_7zd2; var sc_nts_8; var BgL_sc_defzd2loop_9zd2; var ind; { ind = function(nt, sc_nts_10) { var i; { (i = ((sc_nts_10.length)-(1))); while (true) { if ((i>=(0))) if ((sc_isEqual((sc_nts_10[i]), nt))) return i; else (--i); else return false; } } }; (sc_nts_8 = ((BgL_sc_defzd2loop_9zd2 = function(defs, sc_nts_11) { var rule_loop; var head; var def; return ((defs instanceof sc_Pair)?((def = (defs.car)), (head = (def.car)), (rule_loop = function(rules, sc_nts_12) { var nt; var l; var sc_nts_13; var rule; if ((rules instanceof sc_Pair)) { (rule = (rules.car)); (l = rule); (sc_nts_13 = sc_nts_12); while ((l instanceof sc_Pair)) { { (nt = (l.car)); (l = (l.cdr)); (sc_nts_13 = (((sc_member(nt, sc_nts_13))!== false)?sc_nts_13:(new sc_Pair(nt, sc_nts_13)))); } } return (rule_loop((rules.cdr), sc_nts_13)); } else return (BgL_sc_defzd2loop_9zd2((defs.cdr), sc_nts_12)); }), (rule_loop((def.cdr), (((sc_member(head, sc_nts_11))!== false)?sc_nts_11:(new sc_Pair(head, sc_nts_11)))))):(sc_list2vector((sc_reverse(sc_nts_11))))); }), (BgL_sc_defzd2loop_9zd2(grammar, null)))); (BgL_sc_nbzd2nts_7zd2 = (sc_nts_8.length)); (nb_confs = (((BgL_sc_defzd2loop_6zd2 = function(defs, BgL_sc_nbzd2confs_14zd2) { var rule_loop; var def; return ((defs instanceof sc_Pair)?((def = (defs.car)), (rule_loop = function(rules, BgL_sc_nbzd2confs_15zd2) { var l; var BgL_sc_nbzd2confs_16zd2; var rule; if ((rules instanceof sc_Pair)) { (rule = (rules.car)); (l = rule); (BgL_sc_nbzd2confs_16zd2 = BgL_sc_nbzd2confs_15zd2); while ((l instanceof sc_Pair)) { { (l = (l.cdr)); (++BgL_sc_nbzd2confs_16zd2); } } return (rule_loop((rules.cdr), (BgL_sc_nbzd2confs_16zd2+(1)))); } else return (BgL_sc_defzd2loop_6zd2((defs.cdr), BgL_sc_nbzd2confs_15zd2)); }), (rule_loop((def.cdr), BgL_sc_nbzd2confs_14zd2))):BgL_sc_nbzd2confs_14zd2); }), (BgL_sc_defzd2loop_6zd2(grammar, (0))))+BgL_sc_nbzd2nts_7zd2)); (sc_starters_5 = (sc_makeVector(BgL_sc_nbzd2nts_7zd2, null))); (sc_enders_4 = (sc_makeVector(BgL_sc_nbzd2nts_7zd2, null))); (sc_predictors_3 = (sc_makeVector(BgL_sc_nbzd2nts_7zd2, null))); (sc_steps_2 = (sc_makeVector(nb_confs, false))); (sc_names_1 = (sc_makeVector(nb_confs, false))); (nts = sc_nts_8); (starters = sc_starters_5); (enders = sc_enders_4); (predictors = sc_predictors_3); (steps = sc_steps_2); (names = sc_names_1); (nb_nts = (sc_nts_8.length)); (i = (nb_nts-(1))); while ((i>=(0))) { { (sc_steps_2[i] = (i-nb_nts)); (sc_names_1[i] = (sc_list((sc_nts_8[i]), (0)))); (sc_enders_4[i] = (sc_list(i))); (--i); } } def_loop = function(defs, conf) { var rule_loop; var head; var def; return ((defs instanceof sc_Pair)?((def = (defs.car)), (head = (def.car)), (rule_loop = function(rules, conf, rule_num) { var i; var sc_i_17; var nt; var l; var sc_conf_18; var sc_i_19; var rule; if ((rules instanceof sc_Pair)) { (rule = (rules.car)); (names[conf] = (sc_list(head, rule_num))); (sc_i_19 = (ind(head, nts))); (starters[sc_i_19] = (new sc_Pair(conf, (starters[sc_i_19])))); (l = rule); (sc_conf_18 = conf); while ((l instanceof sc_Pair)) { { (nt = (l.car)); (steps[sc_conf_18] = (ind(nt, nts))); (sc_i_17 = (ind(nt, nts))); (predictors[sc_i_17] = (new sc_Pair(sc_conf_18, (predictors[sc_i_17])))); (l = (l.cdr)); (++sc_conf_18); } } (steps[sc_conf_18] = ((ind(head, nts))-nb_nts)); (i = (ind(head, nts))); (enders[i] = (new sc_Pair(sc_conf_18, (enders[i])))); return (rule_loop((rules.cdr), (sc_conf_18+(1)), (rule_num+(1)))); } else return (def_loop((defs.cdr), conf)); }), (rule_loop((def.cdr), conf, (1)))):undefined); }; (def_loop(grammar, (sc_nts_8.length))); (parser_descr = [lexer, sc_nts_8, sc_starters_5, sc_enders_4, sc_predictors_3, sc_steps_2, sc_names_1]); return function(input) { var optrOpnd; var sc_optrOpnd_20; var sc_optrOpnd_21; var sc_optrOpnd_22; var loop1; var BgL_sc_stateza2_23za2; var toks; var BgL_sc_nbzd2nts_24zd2; var sc_steps_25; var sc_enders_26; var state_num; var BgL_sc_statesza2_27za2; var states; var i; var conf; var l; var tok_nts; var sc_i_28; var sc_i_29; var l1; var l2; var tok; var tail1129; var L1125; var goal_enders; var BgL_sc_statesza2_30za2; var BgL_sc_nbzd2nts_31zd2; var BgL_sc_nbzd2confs_32zd2; var nb_toks; var goal_starters; var sc_states_33; var BgL_sc_nbzd2confs_34zd2; var BgL_sc_nbzd2toks_35zd2; var sc_toks_36; var falseHead1128; var sc_names_37; var sc_steps_38; var sc_predictors_39; var sc_enders_40; var sc_starters_41; var sc_nts_42; var lexer; var sc_ind_43; var make_states; var BgL_sc_confzd2setzd2getza2_44za2; var conf_set_merge_new_bang; var conf_set_adjoin; var BgL_sc_confzd2setzd2adjoinza2_45za2; var BgL_sc_confzd2setzd2adjoinza2za2_46z00; var conf_set_union; var forw; var is_parsed; var deriv_trees; var BgL_sc_derivzd2treesza2_47z70; var nb_deriv_trees; var BgL_sc_nbzd2derivzd2treesza2_48za2; { sc_ind_43 = function(nt, sc_nts_49) { var i; { (i = ((sc_nts_49.length)-(1))); while (true) { if ((i>=(0))) if ((sc_isEqual((sc_nts_49[i]), nt))) return i; else (--i); else return false; } } }; make_states = function(BgL_sc_nbzd2toks_50zd2, BgL_sc_nbzd2confs_51zd2) { var v; var i; var sc_states_52; { (sc_states_52 = (sc_makeVector((BgL_sc_nbzd2toks_50zd2+(1)), false))); (i = BgL_sc_nbzd2toks_50zd2); while ((i>=(0))) { { (v = (sc_makeVector((BgL_sc_nbzd2confs_51zd2+(1)), false))); (v[(0)] = (-1)); (sc_states_52[i] = v); (--i); } } return sc_states_52; } }; BgL_sc_confzd2setzd2getza2_44za2 = function(state, BgL_sc_statezd2num_53zd2, sc_conf_54) { var conf_set; var BgL_sc_confzd2set_55zd2; return ((BgL_sc_confzd2set_55zd2 = (state[(sc_conf_54+(1))])), ((BgL_sc_confzd2set_55zd2!== false)?BgL_sc_confzd2set_55zd2:((conf_set = (sc_makeVector((BgL_sc_statezd2num_53zd2+(6)), false))), (conf_set[(1)] = (-3)), (conf_set[(2)] = (-1)), (conf_set[(3)] = (-1)), (conf_set[(4)] = (-1)), (state[(sc_conf_54+(1))] = conf_set), conf_set))); }; conf_set_merge_new_bang = function(conf_set) { return ((conf_set[((conf_set[(1)])+(5))] = (conf_set[(4)])), (conf_set[(1)] = (conf_set[(3)])), (conf_set[(3)] = (-1)), (conf_set[(4)] = (-1))); }; conf_set_adjoin = function(state, conf_set, sc_conf_56, i) { var tail; return ((tail = (conf_set[(3)])), (conf_set[(i+(5))] = (-1)), (conf_set[(tail+(5))] = i), (conf_set[(3)] = i), ((tail<(0))?((conf_set[(0)] = (state[(0)])), (state[(0)] = sc_conf_56)):undefined)); }; BgL_sc_confzd2setzd2adjoinza2_45za2 = function(sc_states_57, BgL_sc_statezd2num_58zd2, l, i) { var conf_set; var sc_conf_59; var l1; var state; { (state = (sc_states_57[BgL_sc_statezd2num_58zd2])); (l1 = l); while ((l1 instanceof sc_Pair)) { { (sc_conf_59 = (l1.car)); (conf_set = (BgL_sc_confzd2setzd2getza2_44za2(state, BgL_sc_statezd2num_58zd2, sc_conf_59))); if (((conf_set[(i+(5))])=== false)) { (conf_set_adjoin(state, conf_set, sc_conf_59, i)); (l1 = (l1.cdr)); } else (l1 = (l1.cdr)); } } return undefined; } }; BgL_sc_confzd2setzd2adjoinza2za2_46z00 = function(sc_states_60, BgL_sc_statesza2_61za2, BgL_sc_statezd2num_62zd2, sc_conf_63, i) { var BgL_sc_confzd2setza2_64z70; var BgL_sc_stateza2_65za2; var conf_set; var state; return ((state = (sc_states_60[BgL_sc_statezd2num_62zd2])), ((((conf_set = (state[(sc_conf_63+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)?((BgL_sc_stateza2_65za2 = (BgL_sc_statesza2_61za2[BgL_sc_statezd2num_62zd2])), (BgL_sc_confzd2setza2_64z70 = (BgL_sc_confzd2setzd2getza2_44za2(BgL_sc_stateza2_65za2, BgL_sc_statezd2num_62zd2, sc_conf_63))), (((BgL_sc_confzd2setza2_64z70[(i+(5))])=== false)?(conf_set_adjoin(BgL_sc_stateza2_65za2, BgL_sc_confzd2setza2_64z70, sc_conf_63, i)):undefined), true):false)); }; conf_set_union = function(state, conf_set, sc_conf_66, other_set) { var i; { (i = (other_set[(2)])); while ((i>=(0))) { if (((conf_set[(i+(5))])=== false)) { (conf_set_adjoin(state, conf_set, sc_conf_66, i)); (i = (other_set[(i+(5))])); } else (i = (other_set[(i+(5))])); } return undefined; } }; forw = function(sc_states_67, BgL_sc_statezd2num_68zd2, sc_starters_69, sc_enders_70, sc_predictors_71, sc_steps_72, sc_nts_73) { var next_set; var next; var conf_set; var ender; var l; var starter_set; var starter; var sc_l_74; var sc_loop1_75; var head; var BgL_sc_confzd2set_76zd2; var BgL_sc_statezd2num_77zd2; var state; var sc_states_78; var preds; var BgL_sc_confzd2set_79zd2; var step; var sc_conf_80; var BgL_sc_nbzd2nts_81zd2; var sc_state_82; { (sc_state_82 = (sc_states_67[BgL_sc_statezd2num_68zd2])); (BgL_sc_nbzd2nts_81zd2 = (sc_nts_73.length)); while (true) { { (sc_conf_80 = (sc_state_82[(0)])); if ((sc_conf_80>=(0))) { (step = (sc_steps_72[sc_conf_80])); (BgL_sc_confzd2set_79zd2 = (sc_state_82[(sc_conf_80+(1))])); (head = (BgL_sc_confzd2set_79zd2[(4)])); (sc_state_82[(0)] = (BgL_sc_confzd2set_79zd2[(0)])); (conf_set_merge_new_bang(BgL_sc_confzd2set_79zd2)); if ((step>=(0))) { (sc_l_74 = (sc_starters_69[step])); while ((sc_l_74 instanceof sc_Pair)) { { (starter = (sc_l_74.car)); (starter_set = (BgL_sc_confzd2setzd2getza2_44za2(sc_state_82, BgL_sc_statezd2num_68zd2, starter))); if (((starter_set[(BgL_sc_statezd2num_68zd2+(5))])=== false)) { (conf_set_adjoin(sc_state_82, starter_set, starter, BgL_sc_statezd2num_68zd2)); (sc_l_74 = (sc_l_74.cdr)); } else (sc_l_74 = (sc_l_74.cdr)); } } (l = (sc_enders_70[step])); while ((l instanceof sc_Pair)) { { (ender = (l.car)); if ((((conf_set = (sc_state_82[(ender+(1))])), ((conf_set!== false)?(conf_set[(BgL_sc_statezd2num_68zd2+(5))]):false))!== false)) { (next = (sc_conf_80+(1))); (next_set = (BgL_sc_confzd2setzd2getza2_44za2(sc_state_82, BgL_sc_statezd2num_68zd2, next))); (conf_set_union(sc_state_82, next_set, next, BgL_sc_confzd2set_79zd2)); (l = (l.cdr)); } else (l = (l.cdr)); } } } else { (preds = (sc_predictors_71[(step+BgL_sc_nbzd2nts_81zd2)])); (sc_states_78 = sc_states_67); (state = sc_state_82); (BgL_sc_statezd2num_77zd2 = BgL_sc_statezd2num_68zd2); (BgL_sc_confzd2set_76zd2 = BgL_sc_confzd2set_79zd2); sc_loop1_75 = function(l) { var sc_state_83; var BgL_sc_nextzd2set_84zd2; var sc_next_85; var pred_set; var i; var pred; if ((l instanceof sc_Pair)) { (pred = (l.car)); (i = head); while ((i>=(0))) { { (pred_set = ((sc_state_83 = (sc_states_78[i])), (sc_state_83[(pred+(1))]))); if ((pred_set!== false)) { (sc_next_85 = (pred+(1))); (BgL_sc_nextzd2set_84zd2 = (BgL_sc_confzd2setzd2getza2_44za2(state, BgL_sc_statezd2num_77zd2, sc_next_85))); (conf_set_union(state, BgL_sc_nextzd2set_84zd2, sc_next_85, pred_set)); } (i = (BgL_sc_confzd2set_76zd2[(i+(5))])); } } return (sc_loop1_75((l.cdr))); } else return undefined; }; (sc_loop1_75(preds)); } } else return undefined; } } } }; is_parsed = function(nt, i, j, sc_nts_86, sc_enders_87, sc_states_88) { var conf_set; var state; var sc_conf_89; var l; var BgL_sc_ntza2_90za2; { (BgL_sc_ntza2_90za2 = (sc_ind_43(nt, sc_nts_86))); if ((BgL_sc_ntza2_90za2!== false)) { (sc_nts_86.length); (l = (sc_enders_87[BgL_sc_ntza2_90za2])); while (true) { if ((l instanceof sc_Pair)) { (sc_conf_89 = (l.car)); if ((((state = (sc_states_88[j])), (conf_set = (state[(sc_conf_89+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)) return true; else (l = (l.cdr)); } else return false; } } else return false; } }; deriv_trees = function(sc_conf_91, i, j, sc_enders_92, sc_steps_93, sc_names_94, sc_toks_95, sc_states_96, BgL_sc_nbzd2nts_97zd2) { var sc_loop1_98; var prev; var name; return ((name = (sc_names_94[sc_conf_91])), ((name!== false)?((sc_conf_91=(0))) if (((k>=i)&&(((sc_state_99 = (sc_states_96[k])), (conf_set = (sc_state_99[(prev+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false))) { (prev_trees = (deriv_trees(prev, i, k, sc_enders_92, sc_steps_93, sc_names_94, sc_toks_95, sc_states_96, BgL_sc_nbzd2nts_97zd2))); (ender_trees = (deriv_trees(ender, k, j, sc_enders_92, sc_steps_93, sc_names_94, sc_toks_95, sc_states_96, BgL_sc_nbzd2nts_97zd2))); loop3 = function(l3, l2) { var l4; var sc_l2_100; var ender_tree; if ((l3 instanceof sc_Pair)) { (ender_tree = (sc_list((l3.car)))); (l4 = prev_trees); (sc_l2_100 = l2); while ((l4 instanceof sc_Pair)) { { (sc_l2_100 = (new sc_Pair((sc_append((l4.car), ender_tree)), sc_l2_100))); (l4 = (l4.cdr)); } } return (loop3((l3.cdr), sc_l2_100)); } else return (loop2((ender_set[(k+(5))]), l2)); }; return (loop3(ender_trees, l2)); } else (k = (ender_set[(k+(5))])); else return (sc_loop1_98((l1.cdr), l2)); } }; return (loop2((ender_set[(2)]), l2)); } else (l1 = (l1.cdr)); } else return l2; } }), (sc_loop1_98((sc_enders_92[(sc_steps_93[prev])]), null))))); }; BgL_sc_derivzd2treesza2_47z70 = function(nt, i, j, sc_nts_101, sc_enders_102, sc_steps_103, sc_names_104, sc_toks_105, sc_states_106) { var conf_set; var state; var sc_conf_107; var l; var trees; var BgL_sc_nbzd2nts_108zd2; var BgL_sc_ntza2_109za2; { (BgL_sc_ntza2_109za2 = (sc_ind_43(nt, sc_nts_101))); if ((BgL_sc_ntza2_109za2!== false)) { (BgL_sc_nbzd2nts_108zd2 = (sc_nts_101.length)); (l = (sc_enders_102[BgL_sc_ntza2_109za2])); (trees = null); while ((l instanceof sc_Pair)) { { (sc_conf_107 = (l.car)); if ((((state = (sc_states_106[j])), (conf_set = (state[(sc_conf_107+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)) { (l = (l.cdr)); (trees = (sc_append((deriv_trees(sc_conf_107, i, j, sc_enders_102, sc_steps_103, sc_names_104, sc_toks_105, sc_states_106, BgL_sc_nbzd2nts_108zd2)), trees))); } else (l = (l.cdr)); } } return trees; } else return false; } }; nb_deriv_trees = function(sc_conf_110, i, j, sc_enders_111, sc_steps_112, sc_toks_113, sc_states_114, BgL_sc_nbzd2nts_115zd2) { var sc_loop1_116; var tmp1124; var prev; return ((prev = (sc_conf_110-(1))), ((((tmp1124 = (sc_conf_110=(0))) { if (((k>=i)&&(((state = (sc_states_114[k])), (conf_set = (state[(prev+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false))) { (nb_prev_trees = (nb_deriv_trees(prev, i, k, sc_enders_111, sc_steps_112, sc_toks_113, sc_states_114, BgL_sc_nbzd2nts_115zd2))); (nb_ender_trees = (nb_deriv_trees(ender, k, j, sc_enders_111, sc_steps_112, sc_toks_113, sc_states_114, BgL_sc_nbzd2nts_115zd2))); (k = (ender_set[(k+(5))])); (n +=(nb_prev_trees*nb_ender_trees)); } else (k = (ender_set[(k+(5))])); } return (sc_loop1_116((l.cdr), n)); } else (l = (l.cdr)); } else return sc_n_118; } }), (sc_loop1_116((sc_enders_111[(sc_steps_112[prev])]), (0)))))); }; BgL_sc_nbzd2derivzd2treesza2_48za2 = function(nt, i, j, sc_nts_119, sc_enders_120, sc_steps_121, sc_toks_122, sc_states_123) { var conf_set; var state; var sc_conf_124; var l; var nb_trees; var BgL_sc_nbzd2nts_125zd2; var BgL_sc_ntza2_126za2; { (BgL_sc_ntza2_126za2 = (sc_ind_43(nt, sc_nts_119))); if ((BgL_sc_ntza2_126za2!== false)) { (BgL_sc_nbzd2nts_125zd2 = (sc_nts_119.length)); (l = (sc_enders_120[BgL_sc_ntza2_126za2])); (nb_trees = (0)); while ((l instanceof sc_Pair)) { { (sc_conf_124 = (l.car)); if ((((state = (sc_states_123[j])), (conf_set = (state[(sc_conf_124+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)) { (l = (l.cdr)); (nb_trees = ((nb_deriv_trees(sc_conf_124, i, j, sc_enders_120, sc_steps_121, sc_toks_122, sc_states_123, BgL_sc_nbzd2nts_125zd2))+nb_trees)); } else (l = (l.cdr)); } } return nb_trees; } else return false; } }; (lexer = (parser_descr[(0)])); (sc_nts_42 = (parser_descr[(1)])); (sc_starters_41 = (parser_descr[(2)])); (sc_enders_40 = (parser_descr[(3)])); (sc_predictors_39 = (parser_descr[(4)])); (sc_steps_38 = (parser_descr[(5)])); (sc_names_37 = (parser_descr[(6)])); (falseHead1128 = (new sc_Pair(null, null))); (L1125 = (lexer(input))); (tail1129 = falseHead1128); while (!(L1125 === null)) { { (tok = (L1125.car)); (l1 = (tok.cdr)); (l2 = null); while ((l1 instanceof sc_Pair)) { { (sc_i_29 = (sc_ind_43((l1.car), sc_nts_42))); if ((sc_i_29!== false)) { (l1 = (l1.cdr)); (l2 = (new sc_Pair(sc_i_29, l2))); } else (l1 = (l1.cdr)); } } (sc_optrOpnd_22 = (new sc_Pair((tok.car), (sc_reverse(l2))))); (sc_optrOpnd_21 = (new sc_Pair(sc_optrOpnd_22, null))); (tail1129.cdr = sc_optrOpnd_21); (tail1129 = (tail1129.cdr)); (L1125 = (L1125.cdr)); } } (sc_optrOpnd_20 = (falseHead1128.cdr)); (sc_toks_36 = (sc_list2vector(sc_optrOpnd_20))); (BgL_sc_nbzd2toks_35zd2 = (sc_toks_36.length)); (BgL_sc_nbzd2confs_34zd2 = (sc_steps_38.length)); (sc_states_33 = (make_states(BgL_sc_nbzd2toks_35zd2, BgL_sc_nbzd2confs_34zd2))); (goal_starters = (sc_starters_41[(0)])); (BgL_sc_confzd2setzd2adjoinza2_45za2(sc_states_33, (0), goal_starters, (0))); (forw(sc_states_33, (0), sc_starters_41, sc_enders_40, sc_predictors_39, sc_steps_38, sc_nts_42)); (sc_i_28 = (0)); while ((sc_i_28=(0))) { { (states = sc_states_33); (BgL_sc_statesza2_27za2 = BgL_sc_statesza2_30za2); (state_num = i); (sc_enders_26 = sc_enders_40); (sc_steps_25 = sc_steps_38); (BgL_sc_nbzd2nts_24zd2 = BgL_sc_nbzd2nts_31zd2); (toks = sc_toks_36); (BgL_sc_stateza2_23za2 = (BgL_sc_statesza2_30za2[i])); loop1 = function() { var sc_loop1_127; var prev; var BgL_sc_statesza2_128za2; var sc_states_129; var j; var i; var sc_i_130; var head; var conf_set; var sc_conf_131; { (sc_conf_131 = (BgL_sc_stateza2_23za2[(0)])); if ((sc_conf_131>=(0))) { (conf_set = (BgL_sc_stateza2_23za2[(sc_conf_131+(1))])); (head = (conf_set[(4)])); (BgL_sc_stateza2_23za2[(0)] = (conf_set[(0)])); (conf_set_merge_new_bang(conf_set)); (sc_i_130 = head); while ((sc_i_130>=(0))) { { (i = sc_i_130); (j = state_num); (sc_states_129 = states); (BgL_sc_statesza2_128za2 = BgL_sc_statesza2_27za2); (prev = (sc_conf_131-(1))); if (((sc_conf_131>=BgL_sc_nbzd2nts_24zd2)&&((sc_steps_25[prev])>=(0)))) { sc_loop1_127 = function(l) { var k; var ender_set; var state; var ender; var l; while (true) { if ((l instanceof sc_Pair)) { (ender = (l.car)); (ender_set = ((state = (sc_states_129[j])), (state[(ender+(1))]))); if ((ender_set!== false)) { (k = (ender_set[(2)])); while ((k>=(0))) { { if ((k>=i)) if (((BgL_sc_confzd2setzd2adjoinza2za2_46z00(sc_states_129, BgL_sc_statesza2_128za2, k, prev, i))!== false)) (BgL_sc_confzd2setzd2adjoinza2za2_46z00(sc_states_129, BgL_sc_statesza2_128za2, j, ender, k)); (k = (ender_set[(k+(5))])); } } return (sc_loop1_127((l.cdr))); } else (l = (l.cdr)); } else return undefined; } }; (sc_loop1_127((sc_enders_26[(sc_steps_25[prev])]))); } (sc_i_130 = (conf_set[(sc_i_130+(5))])); } } return (loop1()); } else return undefined; } }; (loop1()); (--i); } } (optrOpnd = BgL_sc_statesza2_30za2); return [sc_nts_42, sc_starters_41, sc_enders_40, sc_predictors_39, sc_steps_38, sc_names_37, sc_toks_36, optrOpnd, is_parsed, BgL_sc_derivzd2treesza2_47z70, BgL_sc_nbzd2derivzd2treesza2_48za2]; } }; } }; BgL_parsezd2ze3parsedzf3zc2 = function(parse, nt, i, j) { var is_parsed; var states; var enders; var nts; return ((nts = (parse[(0)])), (enders = (parse[(2)])), (states = (parse[(7)])), (is_parsed = (parse[(8)])), (is_parsed(nt, i, j, nts, enders, states))); }; BgL_parsezd2ze3treesz31 = function(parse, nt, i, j) { var BgL_sc_derivzd2treesza2_132z70; var states; var toks; var names; var steps; var enders; var nts; return ((nts = (parse[(0)])), (enders = (parse[(2)])), (steps = (parse[(4)])), (names = (parse[(5)])), (toks = (parse[(6)])), (states = (parse[(7)])), (BgL_sc_derivzd2treesza2_132z70 = (parse[(9)])), (BgL_sc_derivzd2treesza2_132z70(nt, i, j, nts, enders, steps, names, toks, states))); }; BgL_parsezd2ze3nbzd2treesze3 = function(parse, nt, i, j) { var BgL_sc_nbzd2derivzd2treesza2_133za2; var states; var toks; var steps; var enders; var nts; return ((nts = (parse[(0)])), (enders = (parse[(2)])), (steps = (parse[(4)])), (toks = (parse[(6)])), (states = (parse[(7)])), (BgL_sc_nbzd2derivzd2treesza2_133za2 = (parse[(10)])), (BgL_sc_nbzd2derivzd2treesza2_133za2(nt, i, j, nts, enders, steps, toks, states))); }; test = function(k) { var x; var p; return ((p = (BgL_makezd2parserzd2(const_earley, function(l) { var sc_x_134; var tail1134; var L1130; var falseHead1133; { (falseHead1133 = (new sc_Pair(null, null))); (tail1134 = falseHead1133); (L1130 = l); while (!(L1130 === null)) { { (tail1134.cdr = (new sc_Pair(((sc_x_134 = (L1130.car)), (sc_list(sc_x_134, sc_x_134))), null))); (tail1134 = (tail1134.cdr)); (L1130 = (L1130.cdr)); } } return (falseHead1133.cdr); } }))), (x = (p((sc_vector2list((sc_makeVector(k, "\u1E9Ca"))))))), (sc_length((BgL_parsezd2ze3treesz31(x, "\u1E9Cs", (0), k))))); }; BgL_earleyzd2benchmarkzd2 = function() { var args = null; for (var sc_tmp = arguments.length - 1; sc_tmp >= 0; sc_tmp--) { args = sc_cons(arguments[sc_tmp], args); } var k; return ((k = ((args === null)?(7):(args.car))), (BgL_runzd2benchmarkzd2("earley", (1), function() { return (test(k)); }, function(result) { return ((sc_display(result)), (sc_newline()), result == 132); }))); }; } /************* END OF GENERATED CODE *************/ // Invoke this function to run a benchmark. // The first argument is a string identifying the benchmark. // The second argument is the number of times to run the benchmark. // The third argument is a function that runs the benchmark. // The fourth argument is a unary function that warns if the result // returned by the benchmark is incorrect. // // Example: // RunBenchmark("new Array()", // 1, // function () { new Array(1000000); } // function (v) { // return (v instanceof Array) && (v.length == 1000000); // }); SC_DEFAULT_OUT = new sc_GenericOutputPort(function(s) {}); SC_ERROR_OUT = SC_DEFAULT_OUT; function RunBenchmark(name, count, run, warn) { for (var n = 0; n < count; ++n) { result = run(); if (!warn(result)) { throw new Error("Earley or Boyer did incorrect number of rewrites"); } } } var BgL_runzd2benchmarkzd2 = RunBenchmark; jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/benchmarks/v8/raytrace.js0000644000175000017500000007036611314263504031235 0ustar jamespagejamespage00000000000000// The ray tracer code in this file is written by Adam Burmister. It // is available in its original form from: // // http://labs.flog.nz.co/raytracer/ // // It has been modified slightly by Google to work as a standalone // benchmark, but the all the computational code remains // untouched. This file also contains a copy of parts of the Prototype // JavaScript framework which is used by the ray tracer. var RayTrace = new BenchmarkSuite('RayTrace', 932666, [ new Benchmark('RayTrace', renderScene) ]); // Variable used to hold a number that can be used to verify that // the scene was ray traced correctly. var checkNumber; // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // The following is a copy of parts of the Prototype JavaScript library: // Prototype JavaScript framework, version 1.5.0 // (c) 2005-2007 Sam Stephenson // // Prototype is freely distributable under the terms of an MIT-style license. // For details, see the Prototype web site: http://prototype.conio.net/ var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } }; Object.extend = function(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; }; // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // The rest of this file is the actual ray tracer written by Adam // Burmister. It's a concatenation of the following files: // // flog/color.js // flog/light.js // flog/vector.js // flog/ray.js // flog/scene.js // flog/material/basematerial.js // flog/material/solid.js // flog/material/chessboard.js // flog/shape/baseshape.js // flog/shape/sphere.js // flog/shape/plane.js // flog/intersectioninfo.js // flog/camera.js // flog/background.js // flog/engine.js /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Color = Class.create(); Flog.RayTracer.Color.prototype = { red : 0.0, green : 0.0, blue : 0.0, initialize : function(r, g, b) { if(!r) r = 0.0; if(!g) g = 0.0; if(!b) b = 0.0; this.red = r; this.green = g; this.blue = b; }, add : function(c1, c2){ var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red + c2.red; result.green = c1.green + c2.green; result.blue = c1.blue + c2.blue; return result; }, addScalar: function(c1, s){ var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red + s; result.green = c1.green + s; result.blue = c1.blue + s; result.limit(); return result; }, subtract: function(c1, c2){ var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red - c2.red; result.green = c1.green - c2.green; result.blue = c1.blue - c2.blue; return result; }, multiply : function(c1, c2) { var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red * c2.red; result.green = c1.green * c2.green; result.blue = c1.blue * c2.blue; return result; }, multiplyScalar : function(c1, f) { var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red * f; result.green = c1.green * f; result.blue = c1.blue * f; return result; }, divideFactor : function(c1, f) { var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red / f; result.green = c1.green / f; result.blue = c1.blue / f; return result; }, limit: function(){ this.red = (this.red > 0.0) ? ( (this.red > 1.0) ? 1.0 : this.red ) : 0.0; this.green = (this.green > 0.0) ? ( (this.green > 1.0) ? 1.0 : this.green ) : 0.0; this.blue = (this.blue > 0.0) ? ( (this.blue > 1.0) ? 1.0 : this.blue ) : 0.0; }, distance : function(color) { var d = Math.abs(this.red - color.red) + Math.abs(this.green - color.green) + Math.abs(this.blue - color.blue); return d; }, blend: function(c1, c2, w){ var result = new Flog.RayTracer.Color(0,0,0); result = Flog.RayTracer.Color.prototype.add( Flog.RayTracer.Color.prototype.multiplyScalar(c1, 1 - w), Flog.RayTracer.Color.prototype.multiplyScalar(c2, w) ); return result; }, brightness : function() { var r = Math.floor(this.red*255); var g = Math.floor(this.green*255); var b = Math.floor(this.blue*255); return (r * 77 + g * 150 + b * 29) >> 8; }, toString : function () { var r = Math.floor(this.red*255); var g = Math.floor(this.green*255); var b = Math.floor(this.blue*255); return "rgb("+ r +","+ g +","+ b +")"; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Light = Class.create(); Flog.RayTracer.Light.prototype = { position: null, color: null, intensity: 10.0, initialize : function(pos, color, intensity) { this.position = pos; this.color = color; this.intensity = (intensity ? intensity : 10.0); }, getIntensity: function(distance){ if(distance >= intensity) return 0; return Math.pow((intensity - distance) / strength, 0.2); }, toString : function () { return 'Light [' + this.position.x + ',' + this.position.y + ',' + this.position.z + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Vector = Class.create(); Flog.RayTracer.Vector.prototype = { x : 0.0, y : 0.0, z : 0.0, initialize : function(x, y, z) { this.x = (x ? x : 0); this.y = (y ? y : 0); this.z = (z ? z : 0); }, copy: function(vector){ this.x = vector.x; this.y = vector.y; this.z = vector.z; }, normalize : function() { var m = this.magnitude(); return new Flog.RayTracer.Vector(this.x / m, this.y / m, this.z / m); }, magnitude : function() { return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z)); }, cross : function(w) { return new Flog.RayTracer.Vector( -this.z * w.y + this.y * w.z, this.z * w.x - this.x * w.z, -this.y * w.x + this.x * w.y); }, dot : function(w) { return this.x * w.x + this.y * w.y + this.z * w.z; }, add : function(v, w) { return new Flog.RayTracer.Vector(w.x + v.x, w.y + v.y, w.z + v.z); }, subtract : function(v, w) { if(!w || !v) throw 'Vectors must be defined [' + v + ',' + w + ']'; return new Flog.RayTracer.Vector(v.x - w.x, v.y - w.y, v.z - w.z); }, multiplyVector : function(v, w) { return new Flog.RayTracer.Vector(v.x * w.x, v.y * w.y, v.z * w.z); }, multiplyScalar : function(v, w) { return new Flog.RayTracer.Vector(v.x * w, v.y * w, v.z * w); }, toString : function () { return 'Vector [' + this.x + ',' + this.y + ',' + this.z + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Ray = Class.create(); Flog.RayTracer.Ray.prototype = { position : null, direction : null, initialize : function(pos, dir) { this.position = pos; this.direction = dir; }, toString : function () { return 'Ray [' + this.position + ',' + this.direction + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Scene = Class.create(); Flog.RayTracer.Scene.prototype = { camera : null, shapes : [], lights : [], background : null, initialize : function() { this.camera = new Flog.RayTracer.Camera( new Flog.RayTracer.Vector(0,0,-5), new Flog.RayTracer.Vector(0,0,1), new Flog.RayTracer.Vector(0,1,0) ); this.shapes = new Array(); this.lights = new Array(); this.background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0,0,0.5), 0.2); } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; if(typeof(Flog.RayTracer.Material) == 'undefined') Flog.RayTracer.Material = {}; Flog.RayTracer.Material.BaseMaterial = Class.create(); Flog.RayTracer.Material.BaseMaterial.prototype = { gloss: 2.0, // [0...infinity] 0 = matt transparency: 0.0, // 0=opaque reflection: 0.0, // [0...infinity] 0 = no reflection refraction: 0.50, hasTexture: false, initialize : function() { }, getColor: function(u, v){ }, wrapUp: function(t){ t = t % 2.0; if(t < -1) t += 2.0; if(t >= 1) t -= 2.0; return t; }, toString : function () { return 'Material [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Material.Solid = Class.create(); Flog.RayTracer.Material.Solid.prototype = Object.extend( new Flog.RayTracer.Material.BaseMaterial(), { initialize : function(color, reflection, refraction, transparency, gloss) { this.color = color; this.reflection = reflection; this.transparency = transparency; this.gloss = gloss; this.hasTexture = false; }, getColor: function(u, v){ return this.color; }, toString : function () { return 'SolidMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; } } ); /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Material.Chessboard = Class.create(); Flog.RayTracer.Material.Chessboard.prototype = Object.extend( new Flog.RayTracer.Material.BaseMaterial(), { colorEven: null, colorOdd: null, density: 0.5, initialize : function(colorEven, colorOdd, reflection, transparency, gloss, density) { this.colorEven = colorEven; this.colorOdd = colorOdd; this.reflection = reflection; this.transparency = transparency; this.gloss = gloss; this.density = density; this.hasTexture = true; }, getColor: function(u, v){ var t = this.wrapUp(u * this.density) * this.wrapUp(v * this.density); if(t < 0.0) return this.colorEven; else return this.colorOdd; }, toString : function () { return 'ChessMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; } } ); /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {}; Flog.RayTracer.Shape.BaseShape = Class.create(); Flog.RayTracer.Shape.BaseShape.prototype = { position: null, material: null, initialize : function() { this.position = new Vector(0,0,0); this.material = new Flog.RayTracer.Material.SolidMaterial( new Flog.RayTracer.Color(1,0,1), 0, 0, 0 ); }, toString : function () { return 'Material [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {}; Flog.RayTracer.Shape.Sphere = Class.create(); Flog.RayTracer.Shape.Sphere.prototype = { initialize : function(pos, radius, material) { this.radius = radius; this.position = pos; this.material = material; }, intersect: function(ray){ var info = new Flog.RayTracer.IntersectionInfo(); info.shape = this; var dst = Flog.RayTracer.Vector.prototype.subtract(ray.position, this.position); var B = dst.dot(ray.direction); var C = dst.dot(dst) - (this.radius * this.radius); var D = (B * B) - C; if(D > 0){ // intersection! info.isHit = true; info.distance = (-B) - Math.sqrt(D); info.position = Flog.RayTracer.Vector.prototype.add( ray.position, Flog.RayTracer.Vector.prototype.multiplyScalar( ray.direction, info.distance ) ); info.normal = Flog.RayTracer.Vector.prototype.subtract( info.position, this.position ).normalize(); info.color = this.material.getColor(0,0); } else { info.isHit = false; } return info; }, toString : function () { return 'Sphere [position=' + this.position + ', radius=' + this.radius + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {}; Flog.RayTracer.Shape.Plane = Class.create(); Flog.RayTracer.Shape.Plane.prototype = { d: 0.0, initialize : function(pos, d, material) { this.position = pos; this.d = d; this.material = material; }, intersect: function(ray){ var info = new Flog.RayTracer.IntersectionInfo(); var Vd = this.position.dot(ray.direction); if(Vd == 0) return info; // no intersection var t = -(this.position.dot(ray.position) + this.d) / Vd; if(t <= 0) return info; info.shape = this; info.isHit = true; info.position = Flog.RayTracer.Vector.prototype.add( ray.position, Flog.RayTracer.Vector.prototype.multiplyScalar( ray.direction, t ) ); info.normal = this.position; info.distance = t; if(this.material.hasTexture){ var vU = new Flog.RayTracer.Vector(this.position.y, this.position.z, -this.position.x); var vV = vU.cross(this.position); var u = info.position.dot(vU); var v = info.position.dot(vV); info.color = this.material.getColor(u,v); } else { info.color = this.material.getColor(0,0); } return info; }, toString : function () { return 'Plane [' + this.position + ', d=' + this.d + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.IntersectionInfo = Class.create(); Flog.RayTracer.IntersectionInfo.prototype = { isHit: false, hitCount: 0, shape: null, position: null, normal: null, color: null, distance: null, initialize : function() { this.color = new Flog.RayTracer.Color(0,0,0); }, toString : function () { return 'Intersection [' + this.position + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Camera = Class.create(); Flog.RayTracer.Camera.prototype = { position: null, lookAt: null, equator: null, up: null, screen: null, initialize : function(pos, lookAt, up) { this.position = pos; this.lookAt = lookAt; this.up = up; this.equator = lookAt.normalize().cross(this.up); this.screen = Flog.RayTracer.Vector.prototype.add(this.position, this.lookAt); }, getRay: function(vx, vy){ var pos = Flog.RayTracer.Vector.prototype.subtract( this.screen, Flog.RayTracer.Vector.prototype.subtract( Flog.RayTracer.Vector.prototype.multiplyScalar(this.equator, vx), Flog.RayTracer.Vector.prototype.multiplyScalar(this.up, vy) ) ); pos.y = pos.y * -1; var dir = Flog.RayTracer.Vector.prototype.subtract( pos, this.position ); var ray = new Flog.RayTracer.Ray(pos, dir.normalize()); return ray; }, toString : function () { return 'Ray []'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Background = Class.create(); Flog.RayTracer.Background.prototype = { color : null, ambience : 0.0, initialize : function(color, ambience) { this.color = color; this.ambience = ambience; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Engine = Class.create(); Flog.RayTracer.Engine.prototype = { canvas: null, /* 2d context we can render to */ initialize: function(options){ this.options = Object.extend({ canvasHeight: 100, canvasWidth: 100, pixelWidth: 2, pixelHeight: 2, renderDiffuse: false, renderShadows: false, renderHighlights: false, renderReflections: false, rayDepth: 2 }, options || {}); this.options.canvasHeight /= this.options.pixelHeight; this.options.canvasWidth /= this.options.pixelWidth; /* TODO: dynamically include other scripts */ }, setPixel: function(x, y, color){ var pxW, pxH; pxW = this.options.pixelWidth; pxH = this.options.pixelHeight; if (this.canvas) { this.canvas.fillStyle = color.toString(); this.canvas.fillRect (x * pxW, y * pxH, pxW, pxH); } else { if (x === y) { checkNumber += color.brightness(); } // print(x * pxW, y * pxH, pxW, pxH); } }, renderScene: function(scene, canvas){ checkNumber = 0; /* Get canvas */ if (canvas) { this.canvas = canvas.getContext("2d"); } else { this.canvas = null; } var canvasHeight = this.options.canvasHeight; var canvasWidth = this.options.canvasWidth; for(var y=0; y < canvasHeight; y++){ for(var x=0; x < canvasWidth; x++){ var yp = y * 1.0 / canvasHeight * 2 - 1; var xp = x * 1.0 / canvasWidth * 2 - 1; var ray = scene.camera.getRay(xp, yp); var color = this.getPixelColor(ray, scene); this.setPixel(x, y, color); } } if (checkNumber !== 2321) { throw new Error("Scene rendered incorrectly"); } }, getPixelColor: function(ray, scene){ var info = this.testIntersection(ray, scene, null); if(info.isHit){ var color = this.rayTrace(info, ray, scene, 0); return color; } return scene.background.color; }, testIntersection: function(ray, scene, exclude){ var hits = 0; var best = new Flog.RayTracer.IntersectionInfo(); best.distance = 2000; for(var i=0; i= 0 && info.distance < best.distance){ best = info; hits++; } } } best.hitCount = hits; return best; }, getReflectionRay: function(P,N,V){ var c1 = -N.dot(V); var R1 = Flog.RayTracer.Vector.prototype.add( Flog.RayTracer.Vector.prototype.multiplyScalar(N, 2*c1), V ); return new Flog.RayTracer.Ray(P, R1); }, rayTrace: function(info, ray, scene, depth){ // Calc ambient var color = Flog.RayTracer.Color.prototype.multiplyScalar(info.color, scene.background.ambience); var oldColor = color; var shininess = Math.pow(10, info.shape.material.gloss + 1); for(var i=0; i 0.0){ color = Flog.RayTracer.Color.prototype.add( color, Flog.RayTracer.Color.prototype.multiply( info.color, Flog.RayTracer.Color.prototype.multiplyScalar( light.color, L ) ) ); } } // The greater the depth the more accurate the colours, but // this is exponentially (!) expensive if(depth <= this.options.rayDepth){ // calculate reflection ray if(this.options.renderReflections && info.shape.material.reflection > 0) { var reflectionRay = this.getReflectionRay(info.position, info.normal, ray.direction); var refl = this.testIntersection(reflectionRay, scene, info.shape); if (refl.isHit && refl.distance > 0){ refl.color = this.rayTrace(refl, reflectionRay, scene, depth + 1); } else { refl.color = scene.background.color; } color = Flog.RayTracer.Color.prototype.blend( color, refl.color, info.shape.material.reflection ); } // Refraction /* TODO */ } /* Render shadows and highlights */ var shadowInfo = new Flog.RayTracer.IntersectionInfo(); if(this.options.renderShadows){ var shadowRay = new Flog.RayTracer.Ray(info.position, v); shadowInfo = this.testIntersection(shadowRay, scene, info.shape); if(shadowInfo.isHit && shadowInfo.shape != info.shape /*&& shadowInfo.shape.type != 'PLANE'*/){ var vA = Flog.RayTracer.Color.prototype.multiplyScalar(color, 0.5); var dB = (0.5 * Math.pow(shadowInfo.shape.material.transparency, 0.5)); color = Flog.RayTracer.Color.prototype.addScalar(vA,dB); } } // Phong specular highlights if(this.options.renderHighlights && !shadowInfo.isHit && info.shape.material.gloss > 0){ var Lv = Flog.RayTracer.Vector.prototype.subtract( info.shape.position, light.position ).normalize(); var E = Flog.RayTracer.Vector.prototype.subtract( scene.camera.position, info.shape.position ).normalize(); var H = Flog.RayTracer.Vector.prototype.subtract( E, Lv ).normalize(); var glossWeight = Math.pow(Math.max(info.normal.dot(H), 0), shininess); color = Flog.RayTracer.Color.prototype.add( Flog.RayTracer.Color.prototype.multiplyScalar(light.color, glossWeight), color ); } } color.limit(); return color; } }; function renderScene(){ var scene = new Flog.RayTracer.Scene(); scene.camera = new Flog.RayTracer.Camera( new Flog.RayTracer.Vector(0, 0, -15), new Flog.RayTracer.Vector(-0.2, 0, 5), new Flog.RayTracer.Vector(0, 1, 0) ); scene.background = new Flog.RayTracer.Background( new Flog.RayTracer.Color(0.5, 0.5, 0.5), 0.4 ); var sphere = new Flog.RayTracer.Shape.Sphere( new Flog.RayTracer.Vector(-1.5, 1.5, 2), 1.5, new Flog.RayTracer.Material.Solid( new Flog.RayTracer.Color(0,0.5,0.5), 0.3, 0.0, 0.0, 2.0 ) ); var sphere1 = new Flog.RayTracer.Shape.Sphere( new Flog.RayTracer.Vector(1, 0.25, 1), 0.5, new Flog.RayTracer.Material.Solid( new Flog.RayTracer.Color(0.9,0.9,0.9), 0.1, 0.0, 0.0, 1.5 ) ); var plane = new Flog.RayTracer.Shape.Plane( new Flog.RayTracer.Vector(0.1, 0.9, -0.5).normalize(), 1.2, new Flog.RayTracer.Material.Chessboard( new Flog.RayTracer.Color(1,1,1), new Flog.RayTracer.Color(0,0,0), 0.2, 0.0, 1.0, 0.7 ) ); scene.shapes.push(plane); scene.shapes.push(sphere); scene.shapes.push(sphere1); var light = new Flog.RayTracer.Light( new Flog.RayTracer.Vector(5, 10, -1), new Flog.RayTracer.Color(0.8, 0.8, 0.8) ); var light1 = new Flog.RayTracer.Light( new Flog.RayTracer.Vector(-3, 5, -15), new Flog.RayTracer.Color(0.8, 0.8, 0.8), 100 ); scene.lights.push(light); scene.lights.push(light1); var imageWidth = 100; // $F('imageWidth'); var imageHeight = 100; // $F('imageHeight'); var pixelSize = "5,5".split(','); // $F('pixelSize').split(','); var renderDiffuse = true; // $F('renderDiffuse'); var renderShadows = true; // $F('renderShadows'); var renderHighlights = true; // $F('renderHighlights'); var renderReflections = true; // $F('renderReflections'); var rayDepth = 2;//$F('rayDepth'); var raytracer = new Flog.RayTracer.Engine( { canvasWidth: imageWidth, canvasHeight: imageHeight, pixelWidth: pixelSize[0], pixelHeight: pixelSize[1], "renderDiffuse": renderDiffuse, "renderHighlights": renderHighlights, "renderShadows": renderShadows, "renderReflections": renderReflections, "rayDepth": rayDepth } ); raytracer.renderScene(scene, null, 0); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/benchmarks/v8/richards.js0000644000175000017500000003664011314263504031217 0ustar jamespagejamespage00000000000000// Copyright 2006-2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This is a JavaScript implementation of the Richards // benchmark from: // // http://www.cl.cam.ac.uk/~mr10/Bench.html // // The benchmark was originally implemented in BCPL by // Martin Richards. var Richards = new BenchmarkSuite('Richards', 34886, [ new Benchmark("Richards", runRichards) ]); /** * The Richards benchmark simulates the task dispatcher of an * operating system. **/ function runRichards() { var scheduler = new Scheduler(); scheduler.addIdleTask(ID_IDLE, 0, null, COUNT); var queue = new Packet(null, ID_WORKER, KIND_WORK); queue = new Packet(queue, ID_WORKER, KIND_WORK); scheduler.addWorkerTask(ID_WORKER, 1000, queue); queue = new Packet(null, ID_DEVICE_A, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE); scheduler.addHandlerTask(ID_HANDLER_A, 2000, queue); queue = new Packet(null, ID_DEVICE_B, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE); scheduler.addHandlerTask(ID_HANDLER_B, 3000, queue); scheduler.addDeviceTask(ID_DEVICE_A, 4000, null); scheduler.addDeviceTask(ID_DEVICE_B, 5000, null); scheduler.schedule(); if (scheduler.queueCount != EXPECTED_QUEUE_COUNT || scheduler.holdCount != EXPECTED_HOLD_COUNT) { var msg = "Error during execution: queueCount = " + scheduler.queueCount + ", holdCount = " + scheduler.holdCount + "."; throw new Error(msg); } } var COUNT = 1000; /** * These two constants specify how many times a packet is queued and * how many times a task is put on hold in a correct run of richards. * They don't have any meaning a such but are characteristic of a * correct run so if the actual queue or hold count is different from * the expected there must be a bug in the implementation. **/ var EXPECTED_QUEUE_COUNT = 2322; var EXPECTED_HOLD_COUNT = 928; /** * A scheduler can be used to schedule a set of tasks based on their relative * priorities. Scheduling is done by maintaining a list of task control blocks * which holds tasks and the data queue they are processing. * @constructor */ function Scheduler() { this.queueCount = 0; this.holdCount = 0; this.blocks = new Array(NUMBER_OF_IDS); this.list = null; this.currentTcb = null; this.currentId = null; } var ID_IDLE = 0; var ID_WORKER = 1; var ID_HANDLER_A = 2; var ID_HANDLER_B = 3; var ID_DEVICE_A = 4; var ID_DEVICE_B = 5; var NUMBER_OF_IDS = 6; var KIND_DEVICE = 0; var KIND_WORK = 1; /** * Add an idle task to this scheduler. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task * @param {int} count the number of times to schedule the task */ Scheduler.prototype.addIdleTask = function (id, priority, queue, count) { this.addRunningTask(id, priority, queue, new IdleTask(this, 1, count)); }; /** * Add a work task to this scheduler. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task */ Scheduler.prototype.addWorkerTask = function (id, priority, queue) { this.addTask(id, priority, queue, new WorkerTask(this, ID_HANDLER_A, 0)); }; /** * Add a handler task to this scheduler. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task */ Scheduler.prototype.addHandlerTask = function (id, priority, queue) { this.addTask(id, priority, queue, new HandlerTask(this)); }; /** * Add a handler task to this scheduler. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task */ Scheduler.prototype.addDeviceTask = function (id, priority, queue) { this.addTask(id, priority, queue, new DeviceTask(this)) }; /** * Add the specified task and mark it as running. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task * @param {Task} task the task to add */ Scheduler.prototype.addRunningTask = function (id, priority, queue, task) { this.addTask(id, priority, queue, task); this.currentTcb.setRunning(); }; /** * Add the specified task to this scheduler. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task * @param {Task} task the task to add */ Scheduler.prototype.addTask = function (id, priority, queue, task) { this.currentTcb = new TaskControlBlock(this.list, id, priority, queue, task); this.list = this.currentTcb; this.blocks[id] = this.currentTcb; }; /** * Execute the tasks managed by this scheduler. */ Scheduler.prototype.schedule = function () { this.currentTcb = this.list; while (this.currentTcb != null) { if (this.currentTcb.isHeldOrSuspended()) { this.currentTcb = this.currentTcb.link; } else { this.currentId = this.currentTcb.id; this.currentTcb = this.currentTcb.run(); } } }; /** * Release a task that is currently blocked and return the next block to run. * @param {int} id the id of the task to suspend */ Scheduler.prototype.release = function (id) { var tcb = this.blocks[id]; if (tcb == null) return tcb; tcb.markAsNotHeld(); if (tcb.priority > this.currentTcb.priority) { return tcb; } else { return this.currentTcb; } }; /** * Block the currently executing task and return the next task control block * to run. The blocked task will not be made runnable until it is explicitly * released, even if new work is added to it. */ Scheduler.prototype.holdCurrent = function () { this.holdCount++; this.currentTcb.markAsHeld(); return this.currentTcb.link; }; /** * Suspend the currently executing task and return the next task control block * to run. If new work is added to the suspended task it will be made runnable. */ Scheduler.prototype.suspendCurrent = function () { this.currentTcb.markAsSuspended(); return this.currentTcb; }; /** * Add the specified packet to the end of the worklist used by the task * associated with the packet and make the task runnable if it is currently * suspended. * @param {Packet} packet the packet to add */ Scheduler.prototype.queue = function (packet) { var t = this.blocks[packet.id]; if (t == null) return t; this.queueCount++; packet.link = null; packet.id = this.currentId; return t.checkPriorityAdd(this.currentTcb, packet); }; /** * A task control block manages a task and the queue of work packages associated * with it. * @param {TaskControlBlock} link the preceding block in the linked block list * @param {int} id the id of this block * @param {int} priority the priority of this block * @param {Packet} queue the queue of packages to be processed by the task * @param {Task} task the task * @constructor */ function TaskControlBlock(link, id, priority, queue, task) { this.link = link; this.id = id; this.priority = priority; this.queue = queue; this.task = task; if (queue == null) { this.state = STATE_SUSPENDED; } else { this.state = STATE_SUSPENDED_RUNNABLE; } } /** * The task is running and is currently scheduled. */ var STATE_RUNNING = 0; /** * The task has packets left to process. */ var STATE_RUNNABLE = 1; /** * The task is not currently running. The task is not blocked as such and may * be started by the scheduler. */ var STATE_SUSPENDED = 2; /** * The task is blocked and cannot be run until it is explicitly released. */ var STATE_HELD = 4; var STATE_SUSPENDED_RUNNABLE = STATE_SUSPENDED | STATE_RUNNABLE; var STATE_NOT_HELD = ~STATE_HELD; TaskControlBlock.prototype.setRunning = function () { this.state = STATE_RUNNING; }; TaskControlBlock.prototype.markAsNotHeld = function () { this.state = this.state & STATE_NOT_HELD; }; TaskControlBlock.prototype.markAsHeld = function () { this.state = this.state | STATE_HELD; }; TaskControlBlock.prototype.isHeldOrSuspended = function () { return (this.state & STATE_HELD) != 0 || (this.state == STATE_SUSPENDED); }; TaskControlBlock.prototype.markAsSuspended = function () { this.state = this.state | STATE_SUSPENDED; }; TaskControlBlock.prototype.markAsRunnable = function () { this.state = this.state | STATE_RUNNABLE; }; /** * Runs this task, if it is ready to be run, and returns the next task to run. */ TaskControlBlock.prototype.run = function () { var packet; if (this.state == STATE_SUSPENDED_RUNNABLE) { packet = this.queue; this.queue = packet.link; if (this.queue == null) { this.state = STATE_RUNNING; } else { this.state = STATE_RUNNABLE; } } else { packet = null; } return this.task.run(packet); }; /** * Adds a packet to the worklist of this block's task, marks this as runnable if * necessary, and returns the next runnable object to run (the one * with the highest priority). */ TaskControlBlock.prototype.checkPriorityAdd = function (task, packet) { if (this.queue == null) { this.queue = packet; this.markAsRunnable(); if (this.priority > task.priority) return this; } else { this.queue = packet.addTo(this.queue); } return task; }; TaskControlBlock.prototype.toString = function () { return "tcb { " + this.task + "@" + this.state + " }"; }; /** * An idle task doesn't do any work itself but cycles control between the two * device tasks. * @param {Scheduler} scheduler the scheduler that manages this task * @param {int} v1 a seed value that controls how the device tasks are scheduled * @param {int} count the number of times this task should be scheduled * @constructor */ function IdleTask(scheduler, v1, count) { this.scheduler = scheduler; this.v1 = v1; this.count = count; } IdleTask.prototype.run = function (packet) { this.count--; if (this.count == 0) return this.scheduler.holdCurrent(); if ((this.v1 & 1) == 0) { this.v1 = this.v1 >> 1; return this.scheduler.release(ID_DEVICE_A); } else { this.v1 = (this.v1 >> 1) ^ 0xD008; return this.scheduler.release(ID_DEVICE_B); } }; IdleTask.prototype.toString = function () { return "IdleTask" }; /** * A task that suspends itself after each time it has been run to simulate * waiting for data from an external device. * @param {Scheduler} scheduler the scheduler that manages this task * @constructor */ function DeviceTask(scheduler) { this.scheduler = scheduler; this.v1 = null; } DeviceTask.prototype.run = function (packet) { if (packet == null) { if (this.v1 == null) return this.scheduler.suspendCurrent(); var v = this.v1; this.v1 = null; return this.scheduler.queue(v); } else { this.v1 = packet; return this.scheduler.holdCurrent(); } }; DeviceTask.prototype.toString = function () { return "DeviceTask"; }; /** * A task that manipulates work packets. * @param {Scheduler} scheduler the scheduler that manages this task * @param {int} v1 a seed used to specify how work packets are manipulated * @param {int} v2 another seed used to specify how work packets are manipulated * @constructor */ function WorkerTask(scheduler, v1, v2) { this.scheduler = scheduler; this.v1 = v1; this.v2 = v2; } WorkerTask.prototype.run = function (packet) { if (packet == null) { return this.scheduler.suspendCurrent(); } else { if (this.v1 == ID_HANDLER_A) { this.v1 = ID_HANDLER_B; } else { this.v1 = ID_HANDLER_A; } packet.id = this.v1; packet.a1 = 0; for (var i = 0; i < DATA_SIZE; i++) { this.v2++; if (this.v2 > 26) this.v2 = 1; packet.a2[i] = this.v2; } return this.scheduler.queue(packet); } }; WorkerTask.prototype.toString = function () { return "WorkerTask"; }; /** * A task that manipulates work packets and then suspends itself. * @param {Scheduler} scheduler the scheduler that manages this task * @constructor */ function HandlerTask(scheduler) { this.scheduler = scheduler; this.v1 = null; this.v2 = null; } HandlerTask.prototype.run = function (packet) { if (packet != null) { if (packet.kind == KIND_WORK) { this.v1 = packet.addTo(this.v1); } else { this.v2 = packet.addTo(this.v2); } } if (this.v1 != null) { var count = this.v1.a1; var v; if (count < DATA_SIZE) { if (this.v2 != null) { v = this.v2; this.v2 = this.v2.link; v.a1 = this.v1.a2[count]; this.v1.a1 = count + 1; return this.scheduler.queue(v); } } else { v = this.v1; this.v1 = this.v1.link; return this.scheduler.queue(v); } } return this.scheduler.suspendCurrent(); }; HandlerTask.prototype.toString = function () { return "HandlerTask"; }; /* --- * * P a c k e t * --- */ var DATA_SIZE = 4; /** * A simple package of data that is manipulated by the tasks. The exact layout * of the payload data carried by a packet is not importaint, and neither is the * nature of the work performed on packets by the tasks. * * Besides carrying data, packets form linked lists and are hence used both as * data and worklists. * @param {Packet} link the tail of the linked list of packets * @param {int} id an ID for this packet * @param {int} kind the type of this packet * @constructor */ function Packet(link, id, kind) { this.link = link; this.id = id; this.kind = kind; this.a1 = 0; this.a2 = new Array(DATA_SIZE); } /** * Add this packet to the end of a worklist, and return the worklist. * @param {Packet} queue the worklist to add this packet to */ Packet.prototype.addTo = function (queue) { this.link = null; if (queue == null) return this; var peek, next = queue; while ((peek = next.link) != null) next = peek; next.link = this; return queue; }; Packet.prototype.toString = function () { return "Packet"; }; jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/opt0.tests0000644000175000017500000015132011314263504026347 0ustar jamespagejamespage00000000000000e4x/Expressions/11.1.1.js e4x/Expressions/11.1.2.js e4x/Expressions/11.1.3.js e4x/Expressions/11.1.4-06.js e4x/Expressions/11.1.4-07.js e4x/Expressions/11.1.5.js e4x/Expressions/11.2.1.js e4x/Expressions/11.2.2.js e4x/Expressions/11.2.3.js e4x/Expressions/11.2.4.js e4x/Expressions/11.3.1.js e4x/Expressions/11.3.2.js e4x/Expressions/11.4.1.js e4x/Expressions/11.5.1.js e4x/Expressions/11.6.3.js e4x/Expressions/regress-301545.js e4x/Expressions/regress-302531.js e4x/Expressions/regress-340024.js e4x/GC/regress-292455.js e4x/GC/regress-313952-01.js e4x/GC/regress-324117.js e4x/Namespace/13.2.1.js e4x/Namespace/13.2.2.js e4x/Namespace/13.2.5.js e4x/Namespace/regress-283972.js e4x/Namespace/regress-292863.js e4x/Namespace/regress-350442.js e4x/QName/13.3.1.js e4x/QName/13.3.2.js e4x/QName/13.3.5.js e4x/QName/regress-373595-01.js e4x/QName/regress-373595-02.js e4x/QName/regress-373595-03.js e4x/Regress/regress-263935.js e4x/Regress/regress-263936.js e4x/Regress/regress-264369.js e4x/Regress/regress-271545.js e4x/Regress/regress-277650.js e4x/Regress/regress-277664.js e4x/Regress/regress-277683.js e4x/Regress/regress-277935.js e4x/Regress/regress-283349.js e4x/Regress/regress-290056.js e4x/Regress/regress-301573.js e4x/Regress/regress-301596.js e4x/Regress/regress-301692.js e4x/Regress/regress-313799.js e4x/Regress/regress-325425.js e4x/Regress/regress-327691-01.js e4x/Regress/regress-327691-02.js e4x/Regress/regress-327697.js e4x/Regress/regress-328249.js e4x/Regress/regress-329257.js e4x/Regress/regress-331664.js e4x/Regress/regress-350206-1.js e4x/Regress/regress-350206.js e4x/Regress/regress-352103.js e4x/Regress/regress-354145-01.js e4x/Regress/regress-354145-02.js e4x/Regress/regress-354145-03.js e4x/Regress/regress-354145-04.js e4x/Regress/regress-354145-05.js e4x/Regress/regress-354145-07.js e4x/Regress/regress-355474-02.js e4x/Regress/regress-356238-01.js e4x/Regress/regress-369032.js e4x/Regress/regress-369536.js e4x/Regress/regress-372564.js e4x/Regress/regress-374106.js e4x/Regress/regress-374112.js e4x/Regress/regress-374116.js e4x/Regress/regress-374160.js e4x/Regress/regress-378492.js e4x/Regress/regress-407323.js e4x/Statements/12.1.js e4x/Statements/12.2.js e4x/Statements/12.3-01.js e4x/TypeConversion/10.1.2.js e4x/TypeConversion/10.3.1.js e4x/TypeConversion/10.3.js e4x/TypeConversion/10.4.1.js e4x/TypeConversion/10.4.js e4x/Types/9.1.1.1.js e4x/Types/9.1.1.2.js e4x/Types/9.1.1.3.js e4x/Types/9.1.1.6.js e4x/Types/9.2.1.1.js e4x/Types/9.2.1.2.js e4x/Types/9.2.1.8.js e4x/XML/13.4.1.js e4x/XML/13.4.2.js e4x/XML/13.4.3.10.js e4x/XML/13.4.4.12-1.js e4x/XML/13.4.4.12.js e4x/XML/13.4.4.13.js e4x/XML/13.4.4.14.js e4x/XML/13.4.4.15.js e4x/XML/13.4.4.16.js e4x/XML/13.4.4.18.js e4x/XML/13.4.4.19.js e4x/XML/13.4.4.2.js e4x/XML/13.4.4.20.js e4x/XML/13.4.4.21.js e4x/XML/13.4.4.23.js e4x/XML/13.4.4.24.js e4x/XML/13.4.4.25.js e4x/XML/13.4.4.27.js e4x/XML/13.4.4.3.js e4x/XML/13.4.4.30.js e4x/XML/13.4.4.31.js e4x/XML/13.4.4.32-01.js e4x/XML/13.4.4.32.js e4x/XML/13.4.4.33.js e4x/XML/13.4.4.34.js e4x/XML/13.4.4.35.js e4x/XML/13.4.4.36.js e4x/XML/13.4.4.37.js e4x/XML/13.4.4.38.js e4x/XML/13.4.4.39.js e4x/XML/13.4.4.4.js e4x/XML/13.4.4.40.js e4x/XML/13.4.4.5.js e4x/XML/13.4.4.7.js e4x/XML/13.4.4.8.js e4x/XML/regress-291930.js e4x/XML/regress-324688.js e4x/XML/regress-336921.js e4x/XMLList/13.5.1.js e4x/XMLList/13.5.2.js e4x/XMLList/13.5.4.10.js e4x/XMLList/13.5.4.11.js e4x/XMLList/13.5.4.12.js e4x/XMLList/13.5.4.13.js e4x/XMLList/13.5.4.14.js e4x/XMLList/13.5.4.15.js e4x/XMLList/13.5.4.16.js e4x/XMLList/13.5.4.17.js e4x/XMLList/13.5.4.18.js e4x/XMLList/13.5.4.19.js e4x/XMLList/13.5.4.2.js e4x/XMLList/13.5.4.20.js e4x/XMLList/13.5.4.21.js e4x/XMLList/13.5.4.22.js e4x/XMLList/13.5.4.3.js e4x/XMLList/13.5.4.4.js e4x/XMLList/13.5.4.5.js e4x/XMLList/13.5.4.6.js e4x/XMLList/13.5.4.7.js e4x/XMLList/13.5.4.8.js e4x/XMLList/13.5.4.9.js e4x/decompilation/regress-349814.js e4x/decompilation/regress-349815.js e4x/decompilation/regress-349822.js e4x/decompilation/regress-349956.js e4x/decompilation/regress-355474-01.js e4x/decompilation/regress-373678.js e4x/extensions/regress-305335.js e4x/extensions/regress-321547.js e4x/extensions/regress-327534.js e4x/extensions/regress-327897.js e4x/extensions/regress-354145-06.js e4x/extensions/regress-354151-01.js ecma/Array/15.4-1.js ecma/Array/15.4-2.js ecma/Array/15.4.1.1.js ecma/Array/15.4.1.2.js ecma/Array/15.4.1.3.js ecma/Array/15.4.1.js ecma/Array/15.4.2.1-1.js ecma/Array/15.4.2.1-2.js ecma/Array/15.4.2.1-3.js ecma/Array/15.4.2.2-1.js ecma/Array/15.4.2.2-2.js ecma/Array/15.4.2.3.js ecma/Array/15.4.3.2.js ecma/Array/15.4.4.1.js ecma/Array/15.4.4.2.js ecma/Array/15.4.4.3-1.js ecma/Array/15.4.4.4-1.js ecma/Array/15.4.4.4-2.js ecma/Array/15.4.4.5-1.js ecma/Array/15.4.4.5-2.js ecma/Array/15.4.4.js ecma/Array/15.4.5.1-2.js ecma/Array/15.4.5.2-1.js ecma/Array/15.4.5.2-2.js ecma/Boolean/15.6.2.js ecma/Boolean/15.6.3.1-1.js ecma/Boolean/15.6.3.1-2.js ecma/Boolean/15.6.3.1.js ecma/Boolean/15.6.4-1.js ecma/Boolean/15.6.4.1.js ecma/Boolean/15.6.4.2-2.js ecma/Boolean/15.6.4.2-3.js ecma/Boolean/15.6.4.2-4-n.js ecma/Boolean/15.6.4.3-1.js ecma/Boolean/15.6.4.3-2.js ecma/Boolean/15.6.4.3-3.js ecma/Boolean/15.6.4.3-4-n.js ecma/Boolean/15.6.4.3.js ecma/Boolean/15.6.4.js ecma/Date/15.9.1.1-1.js ecma/Date/15.9.1.1-2.js ecma/Date/15.9.1.13-1.js ecma/Date/15.9.2.1.js ecma/Date/15.9.2.2-1.js ecma/Date/15.9.2.2-2.js ecma/Date/15.9.2.2-3.js ecma/Date/15.9.2.2-5.js ecma/Date/15.9.2.2-6.js ecma/Date/15.9.3.1-2.js ecma/Date/15.9.3.1-3.js ecma/Date/15.9.3.1-4.js ecma/Date/15.9.3.1-5.js ecma/Date/15.9.3.2-2.js ecma/Date/15.9.3.2-3.js ecma/Date/15.9.3.2-4.js ecma/Date/15.9.3.2-5.js ecma/Date/15.9.3.8-1.js ecma/Date/15.9.3.8-2.js ecma/Date/15.9.3.8-3.js ecma/Date/15.9.3.8-4.js ecma/Date/15.9.3.8-5.js ecma/Date/15.9.4.2.js ecma/Date/15.9.4.3.js ecma/Date/15.9.5.1.js ecma/Date/15.9.5.10-1.js ecma/Date/15.9.5.10-10.js ecma/Date/15.9.5.10-11.js ecma/Date/15.9.5.10-12.js ecma/Date/15.9.5.10-13.js ecma/Date/15.9.5.10-4.js ecma/Date/15.9.5.10-5.js ecma/Date/15.9.5.10-6.js ecma/Date/15.9.5.10-7.js ecma/Date/15.9.5.10-8.js ecma/Date/15.9.5.10-9.js ecma/Date/15.9.5.11-1.js ecma/Date/15.9.5.11-3.js ecma/Date/15.9.5.11-4.js ecma/Date/15.9.5.11-5.js ecma/Date/15.9.5.11-6.js ecma/Date/15.9.5.11-7.js ecma/Date/15.9.5.12-1.js ecma/Date/15.9.5.12-3.js ecma/Date/15.9.5.12-4.js ecma/Date/15.9.5.12-5.js ecma/Date/15.9.5.12-6.js ecma/Date/15.9.5.12-7.js ecma/Date/15.9.5.12-8.js ecma/Date/15.9.5.13-1.js ecma/Date/15.9.5.13-2.js ecma/Date/15.9.5.13-3.js ecma/Date/15.9.5.13-4.js ecma/Date/15.9.5.13-5.js ecma/Date/15.9.5.13-6.js ecma/Date/15.9.5.13-7.js ecma/Date/15.9.5.13-8.js ecma/Date/15.9.5.14.js ecma/Date/15.9.5.15.js ecma/Date/15.9.5.16.js ecma/Date/15.9.5.17.js ecma/Date/15.9.5.19.js ecma/Date/15.9.5.2-2-n.js ecma/Date/15.9.5.2.js ecma/Date/15.9.5.20.js ecma/Date/15.9.5.21-1.js ecma/Date/15.9.5.21-2.js ecma/Date/15.9.5.21-3.js ecma/Date/15.9.5.21-4.js ecma/Date/15.9.5.21-5.js ecma/Date/15.9.5.21-6.js ecma/Date/15.9.5.21-7.js ecma/Date/15.9.5.21-8.js ecma/Date/15.9.5.22-2.js ecma/Date/15.9.5.22-3.js ecma/Date/15.9.5.22-4.js ecma/Date/15.9.5.22-5.js ecma/Date/15.9.5.22-6.js ecma/Date/15.9.5.22-7.js ecma/Date/15.9.5.22-8.js ecma/Date/15.9.5.23-1.js ecma/Date/15.9.5.23-10.js ecma/Date/15.9.5.23-11.js ecma/Date/15.9.5.23-12.js ecma/Date/15.9.5.23-13.js ecma/Date/15.9.5.23-14.js ecma/Date/15.9.5.23-15.js ecma/Date/15.9.5.23-16.js ecma/Date/15.9.5.23-17.js ecma/Date/15.9.5.23-18.js ecma/Date/15.9.5.23-2.js ecma/Date/15.9.5.23-3-n.js ecma/Date/15.9.5.23-4.js ecma/Date/15.9.5.23-5.js ecma/Date/15.9.5.23-6.js ecma/Date/15.9.5.23-7.js ecma/Date/15.9.5.23-8.js ecma/Date/15.9.5.23-9.js ecma/Date/15.9.5.24-1.js ecma/Date/15.9.5.24-2.js ecma/Date/15.9.5.24-3.js ecma/Date/15.9.5.24-4.js ecma/Date/15.9.5.24-5.js ecma/Date/15.9.5.24-6.js ecma/Date/15.9.5.24-7.js ecma/Date/15.9.5.24-8.js ecma/Date/15.9.5.25-1.js ecma/Date/15.9.5.26-1.js ecma/Date/15.9.5.27-1.js ecma/Date/15.9.5.28-1.js ecma/Date/15.9.5.29-1.js ecma/Date/15.9.5.3-2.js ecma/Date/15.9.5.30-1.js ecma/Date/15.9.5.31-1.js ecma/Date/15.9.5.32-1.js ecma/Date/15.9.5.33-1.js ecma/Date/15.9.5.34-1.js ecma/Date/15.9.5.35-1.js ecma/Date/15.9.5.36-1.js ecma/Date/15.9.5.36-2.js ecma/Date/15.9.5.36-4.js ecma/Date/15.9.5.36-5.js ecma/Date/15.9.5.36-6.js ecma/Date/15.9.5.36-7.js ecma/Date/15.9.5.37-2.js ecma/Date/15.9.5.37-3.js ecma/Date/15.9.5.37-4.js ecma/Date/15.9.5.37-5.js ecma/Date/15.9.5.4-1.js ecma/Date/15.9.5.4-2-n.js ecma/Date/15.9.5.6.js ecma/Date/15.9.5.7.js ecma/Date/15.9.5.8.js ecma/Date/15.9.5.9.js ecma/Date/15.9.5.js ecma/ExecutionContexts/10.1.3-1.js ecma/ExecutionContexts/10.1.3-2.js ecma/ExecutionContexts/10.1.3.js ecma/ExecutionContexts/10.1.4-1.js ecma/ExecutionContexts/10.1.4-10.js ecma/ExecutionContexts/10.1.4-3.js ecma/ExecutionContexts/10.1.4-4.js ecma/ExecutionContexts/10.1.4-5.js ecma/ExecutionContexts/10.1.4-6.js ecma/ExecutionContexts/10.1.4-7.js ecma/ExecutionContexts/10.1.4-8.js ecma/ExecutionContexts/10.1.5-1.js ecma/ExecutionContexts/10.1.5-2.js ecma/ExecutionContexts/10.1.5-3.js ecma/ExecutionContexts/10.1.5-4.js ecma/ExecutionContexts/10.1.8-2.js ecma/ExecutionContexts/10.1.8-3.js ecma/ExecutionContexts/10.2.1.js ecma/ExecutionContexts/10.2.2-1.js ecma/ExecutionContexts/10.2.2-2.js ecma/ExecutionContexts/10.2.3-1.js ecma/ExecutionContexts/10.2.3-2.js ecma/Expressions/11.1.1.js ecma/Expressions/11.10-1.js ecma/Expressions/11.10-2.js ecma/Expressions/11.10-3.js ecma/Expressions/11.12-1.js ecma/Expressions/11.12-2-n.js ecma/Expressions/11.12-3.js ecma/Expressions/11.12-4.js ecma/Expressions/11.13.1.js ecma/Expressions/11.13.2-1.js ecma/Expressions/11.13.2-2.js ecma/Expressions/11.13.2-3.js ecma/Expressions/11.13.2-4.js ecma/Expressions/11.13.2-5.js ecma/Expressions/11.14-1.js ecma/Expressions/11.2.1-1.js ecma/Expressions/11.2.1-2.js ecma/Expressions/11.2.1-3-n.js ecma/Expressions/11.2.1-4-n.js ecma/Expressions/11.2.1-5.js ecma/Expressions/11.2.2-1-n.js ecma/Expressions/11.2.2-1.js ecma/Expressions/11.2.2-10-n.js ecma/Expressions/11.2.2-11.js ecma/Expressions/11.2.2-2-n.js ecma/Expressions/11.2.2-3-n.js ecma/Expressions/11.2.2-4-n.js ecma/Expressions/11.2.2-5-n.js ecma/Expressions/11.2.2-6-n.js ecma/Expressions/11.2.2-7-n.js ecma/Expressions/11.2.2-8-n.js ecma/Expressions/11.2.2-9-n.js ecma/Expressions/11.2.3-1.js ecma/Expressions/11.2.3-2-n.js ecma/Expressions/11.2.3-3-n.js ecma/Expressions/11.2.3-4-n.js ecma/Expressions/11.2.3-5.js ecma/Expressions/11.3.1.js ecma/Expressions/11.3.2.js ecma/Expressions/11.4.2.js ecma/Expressions/11.4.3.js ecma/Expressions/11.4.4.js ecma/Expressions/11.4.5.js ecma/Expressions/11.4.6.js ecma/Expressions/11.4.8.js ecma/Expressions/11.4.9.js ecma/Expressions/11.5.1.js ecma/Expressions/11.5.2.js ecma/Expressions/11.5.3.js ecma/Expressions/11.6.1-1.js ecma/Expressions/11.6.1-2.js ecma/Expressions/11.6.1-3.js ecma/Expressions/11.6.2-1.js ecma/Expressions/11.6.3.js ecma/Expressions/11.7.1.js ecma/Expressions/11.7.2.js ecma/Expressions/11.8.1.js ecma/Expressions/11.8.2.js ecma/Expressions/11.8.3.js ecma/Expressions/11.9.2.js ecma/Expressions/11.9.3.js ecma/FunctionObjects/15.3.1.1-1.js ecma/FunctionObjects/15.3.1.1-2.js ecma/FunctionObjects/15.3.1.1-3.js ecma/FunctionObjects/15.3.2.1-1.js ecma/FunctionObjects/15.3.2.1-2.js ecma/FunctionObjects/15.3.2.1-3.js ecma/FunctionObjects/15.3.3.1-2.js ecma/FunctionObjects/15.3.3.1-3.js ecma/FunctionObjects/15.3.3.1-4.js ecma/FunctionObjects/15.3.3.2.js ecma/FunctionObjects/15.3.4-1.js ecma/FunctionObjects/15.3.4.1.js ecma/FunctionObjects/15.3.4.js ecma/FunctionObjects/15.3.5-1.js ecma/FunctionObjects/15.3.5-2.js ecma/FunctionObjects/15.3.5.1.js ecma/FunctionObjects/15.3.5.3.js ecma/GlobalObject/15.1-1-n.js ecma/GlobalObject/15.1-2-n.js ecma/GlobalObject/15.1.1.1.js ecma/GlobalObject/15.1.1.2.js ecma/GlobalObject/15.1.2.1-2.js ecma/GlobalObject/15.1.2.2-1.js ecma/GlobalObject/15.1.2.2-2.js ecma/GlobalObject/15.1.2.3-1.js ecma/GlobalObject/15.1.2.3-2.js ecma/GlobalObject/15.1.2.4.js ecma/GlobalObject/15.1.2.5-1.js ecma/GlobalObject/15.1.2.5-2.js ecma/GlobalObject/15.1.2.5-3.js ecma/GlobalObject/15.1.2.7.js ecma/LexicalConventions/7.1-1.js ecma/LexicalConventions/7.1-2.js ecma/LexicalConventions/7.1-3.js ecma/LexicalConventions/7.2-1.js ecma/LexicalConventions/7.2-2-n.js ecma/LexicalConventions/7.2-3-n.js ecma/LexicalConventions/7.2-4-n.js ecma/LexicalConventions/7.2-5-n.js ecma/LexicalConventions/7.2-6.js ecma/LexicalConventions/7.3-1.js ecma/LexicalConventions/7.3-10.js ecma/LexicalConventions/7.3-11.js ecma/LexicalConventions/7.3-12.js ecma/LexicalConventions/7.3-13-n.js ecma/LexicalConventions/7.3-2.js ecma/LexicalConventions/7.3-3.js ecma/LexicalConventions/7.3-4.js ecma/LexicalConventions/7.3-5.js ecma/LexicalConventions/7.3-6.js ecma/LexicalConventions/7.3-8.js ecma/LexicalConventions/7.3-9.js ecma/LexicalConventions/7.4.1-1-n.js ecma/LexicalConventions/7.4.1-2-n.js ecma/LexicalConventions/7.4.1-3-n.js ecma/LexicalConventions/7.4.2-1-n.js ecma/LexicalConventions/7.4.2-10-n.js ecma/LexicalConventions/7.4.2-11-n.js ecma/LexicalConventions/7.4.2-12-n.js ecma/LexicalConventions/7.4.2-13-n.js ecma/LexicalConventions/7.4.2-14-n.js ecma/LexicalConventions/7.4.2-15-n.js ecma/LexicalConventions/7.4.2-16-n.js ecma/LexicalConventions/7.4.2-2-n.js ecma/LexicalConventions/7.4.2-3-n.js ecma/LexicalConventions/7.4.2-4-n.js ecma/LexicalConventions/7.4.2-5-n.js ecma/LexicalConventions/7.4.2-6-n.js ecma/LexicalConventions/7.4.2-7-n.js ecma/LexicalConventions/7.4.2-8-n.js ecma/LexicalConventions/7.4.3-1-n.js ecma/LexicalConventions/7.4.3-10-n.js ecma/LexicalConventions/7.4.3-11-n.js ecma/LexicalConventions/7.4.3-13-n.js ecma/LexicalConventions/7.4.3-15-n.js ecma/LexicalConventions/7.4.3-16-n.js ecma/LexicalConventions/7.4.3-2-n.js ecma/LexicalConventions/7.4.3-3-n.js ecma/LexicalConventions/7.4.3-4-n.js ecma/LexicalConventions/7.4.3-5-n.js ecma/LexicalConventions/7.4.3-6-n.js ecma/LexicalConventions/7.4.3-7-n.js ecma/LexicalConventions/7.4.3-8-n.js ecma/LexicalConventions/7.4.3-9-n.js ecma/LexicalConventions/7.5-1.js ecma/LexicalConventions/7.5-10-n.js ecma/LexicalConventions/7.5-2-n.js ecma/LexicalConventions/7.5-3-n.js ecma/LexicalConventions/7.5-4-n.js ecma/LexicalConventions/7.5-5-n.js ecma/LexicalConventions/7.5-6.js ecma/LexicalConventions/7.5-7.js ecma/LexicalConventions/7.5-8-n.js ecma/LexicalConventions/7.5-9-n.js ecma/LexicalConventions/7.6.js ecma/LexicalConventions/7.7.1.js ecma/LexicalConventions/7.7.2.js ecma/LexicalConventions/7.7.3-1.js ecma/LexicalConventions/7.7.3-2.js ecma/LexicalConventions/7.7.3.js ecma/LexicalConventions/7.7.4.js ecma/LexicalConventions/7.8.2-n.js ecma/Math/15.8-2-n.js ecma/Math/15.8-3-n.js ecma/Math/15.8.1.1-1.js ecma/Math/15.8.1.1-2.js ecma/Math/15.8.1.2-1.js ecma/Math/15.8.1.3-1.js ecma/Math/15.8.1.3-2.js ecma/Math/15.8.1.4-1.js ecma/Math/15.8.1.4-2.js ecma/Math/15.8.1.5-1.js ecma/Math/15.8.1.5-2.js ecma/Math/15.8.1.6-1.js ecma/Math/15.8.1.6-2.js ecma/Math/15.8.1.7-1.js ecma/Math/15.8.1.7-2.js ecma/Math/15.8.1.8-1.js ecma/Math/15.8.1.8-2.js ecma/Math/15.8.1.8-3.js ecma/Math/15.8.2.1.js ecma/Math/15.8.2.10.js ecma/Math/15.8.2.12.js ecma/Math/15.8.2.13.js ecma/Math/15.8.2.14.js ecma/Math/15.8.2.15.js ecma/Math/15.8.2.16.js ecma/Math/15.8.2.17.js ecma/Math/15.8.2.18.js ecma/Math/15.8.2.2.js ecma/Math/15.8.2.3.js ecma/Math/15.8.2.4.js ecma/Math/15.8.2.5.js ecma/Math/15.8.2.6.js ecma/Math/15.8.2.7.js ecma/Math/15.8.2.8.js ecma/Math/15.8.2.9.js ecma/Number/15.7.2.js ecma/Number/15.7.3.1-1.js ecma/Number/15.7.3.1-2.js ecma/Number/15.7.3.1-3.js ecma/Number/15.7.3.2-1.js ecma/Number/15.7.3.2-2.js ecma/Number/15.7.3.2-3.js ecma/Number/15.7.3.3-1.js ecma/Number/15.7.3.3-2.js ecma/Number/15.7.3.3-3.js ecma/Number/15.7.3.4-1.js ecma/Number/15.7.3.4-2.js ecma/Number/15.7.3.4-3.js ecma/Number/15.7.3.4-4.js ecma/Number/15.7.3.5-1.js ecma/Number/15.7.3.5-2.js ecma/Number/15.7.3.5-3.js ecma/Number/15.7.3.5-4.js ecma/Number/15.7.3.6-1.js ecma/Number/15.7.3.6-4.js ecma/Number/15.7.3.js ecma/Number/15.7.4-1.js ecma/Number/15.7.4.1.js ecma/Number/15.7.4.2-1.js ecma/Number/15.7.4.2-2-n.js ecma/Number/15.7.4.2-3-n.js ecma/Number/15.7.4.2-4.js ecma/Number/15.7.4.3-1.js ecma/Number/15.7.4.3-2.js ecma/ObjectObjects/15.2.1.2.js ecma/ObjectObjects/15.2.2.1.js ecma/ObjectObjects/15.2.2.2.js ecma/ObjectObjects/15.2.3.1-1.js ecma/ObjectObjects/15.2.3.1-2.js ecma/ObjectObjects/15.2.3.1-3.js ecma/ObjectObjects/15.2.3.1-4.js ecma/ObjectObjects/15.2.3.js ecma/ObjectObjects/15.2.4.1.js ecma/ObjectObjects/15.2.4.2.js ecma/ObjectObjects/15.2.4.3.js ecma/SourceText/6-1.js ecma/SourceText/6-2.js ecma/Statements/12.10-1.js ecma/Statements/12.10.js ecma/Statements/12.5-1.js ecma/Statements/12.5-2.js ecma/Statements/12.6.2-1.js ecma/Statements/12.6.2-2.js ecma/Statements/12.6.2-4.js ecma/Statements/12.6.2-5.js ecma/Statements/12.6.2-6.js ecma/Statements/12.6.2-7.js ecma/Statements/12.6.2-8.js ecma/Statements/12.6.2-9-n.js ecma/Statements/12.6.3-1.js ecma/Statements/12.6.3-10.js ecma/Statements/12.6.3-11.js ecma/Statements/12.6.3-12.js ecma/Statements/12.6.3-19.js ecma/Statements/12.6.3-2.js ecma/Statements/12.6.3-3.js ecma/Statements/12.6.3-4.js ecma/Statements/12.6.3-5-n.js ecma/Statements/12.6.3-6-n.js ecma/Statements/12.6.3-7-n.js ecma/Statements/12.6.3-9-n.js ecma/Statements/12.7-1-n.js ecma/Statements/12.8-1-n.js ecma/Statements/12.9-1-n.js ecma/String/15.5.1.js ecma/String/15.5.2.js ecma/String/15.5.3.1-1.js ecma/String/15.5.3.1-2.js ecma/String/15.5.3.1-3.js ecma/String/15.5.3.1-4.js ecma/String/15.5.3.2-1.js ecma/String/15.5.3.2-2.js ecma/String/15.5.3.2-3.js ecma/String/15.5.3.js ecma/String/15.5.4.1.js ecma/String/15.5.4.10-1.js ecma/String/15.5.4.11-1.js ecma/String/15.5.4.11-3.js ecma/String/15.5.4.11-4.js ecma/String/15.5.4.11-6.js ecma/String/15.5.4.12-2.js ecma/String/15.5.4.12-3.js ecma/String/15.5.4.2-1.js ecma/String/15.5.4.2-2-n.js ecma/String/15.5.4.2-3.js ecma/String/15.5.4.2.js ecma/String/15.5.4.3-1.js ecma/String/15.5.4.3-2.js ecma/String/15.5.4.3-3-n.js ecma/String/15.5.4.4-1.js ecma/String/15.5.4.4-2.js ecma/String/15.5.4.4-3.js ecma/String/15.5.4.4-4.js ecma/String/15.5.4.5-1.js ecma/String/15.5.4.5-2.js ecma/String/15.5.4.5-3.js ecma/String/15.5.4.5-4.js ecma/String/15.5.4.5-5.js ecma/String/15.5.4.6-1.js ecma/String/15.5.4.7-2.js ecma/String/15.5.4.8-1.js ecma/String/15.5.4.8-3.js ecma/String/15.5.4.9-1.js ecma/String/15.5.4.js ecma/String/15.5.5.1.js ecma/TypeConversion/9.2.js ecma/TypeConversion/9.3-1.js ecma/TypeConversion/9.3.1-1.js ecma/TypeConversion/9.3.1-2.js ecma/TypeConversion/9.3.1-3.js ecma/TypeConversion/9.3.js ecma/TypeConversion/9.4-1.js ecma/TypeConversion/9.4-2.js ecma/TypeConversion/9.5-2.js ecma/TypeConversion/9.6.js ecma/TypeConversion/9.7.js ecma/TypeConversion/9.8.1.js ecma/TypeConversion/9.9-1.js ecma/Types/8.1.js ecma/Types/8.4.js ecma/Types/8.6.2.1-1.js ecma/extensions/10.1.4-9.js ecma/extensions/10.1.6.js ecma/extensions/10.1.8-1.js ecma/extensions/11.6.1-1.js ecma/extensions/11.6.1-2.js ecma/extensions/11.6.1-3.js ecma/extensions/11.6.2-1.js ecma/extensions/15-2.js ecma/extensions/15.1.2.1-1.js ecma/extensions/15.2.1.1.js ecma/extensions/15.2.3-1.js ecma/extensions/15.2.4.js ecma/extensions/15.3.1.1-2.js ecma/extensions/15.3.2.1-1.js ecma/extensions/15.3.2.1-2.js ecma/extensions/15.4.3.js ecma/extensions/15.5.3.js ecma/extensions/15.5.4.2.js ecma/extensions/15.5.4.4-4.js ecma/extensions/15.5.4.5-6.js ecma/extensions/15.5.4.7-3.js ecma/extensions/15.6.3.1-5.js ecma/extensions/15.6.3.js ecma/extensions/15.6.4-2.js ecma/extensions/15.7.3.js ecma/extensions/15.7.4.js ecma/extensions/15.8-1.js ecma/extensions/15.9.5.js ecma/extensions/8.6.2.1-1.js ecma/extensions/9.9-1.js ecma/jsref.js ecma_2/Exceptions/boolean-001.js ecma_2/Exceptions/date-001.js ecma_2/Exceptions/date-002.js ecma_2/Exceptions/date-004.js ecma_2/Exceptions/exception-001.js ecma_2/Exceptions/exception-002.js ecma_2/Exceptions/exception-004.js ecma_2/Exceptions/exception-005.js ecma_2/Exceptions/exception-006.js ecma_2/Exceptions/exception-007.js ecma_2/Exceptions/exception-008.js ecma_2/Exceptions/exception-009.js ecma_2/Exceptions/exception-010-n.js ecma_2/Exceptions/exception-011-n.js ecma_2/Exceptions/expression-002.js ecma_2/Exceptions/expression-004.js ecma_2/Exceptions/expression-005.js ecma_2/Exceptions/expression-006.js ecma_2/Exceptions/expression-007.js ecma_2/Exceptions/expression-008.js ecma_2/Exceptions/expression-009.js ecma_2/Exceptions/expression-010.js ecma_2/Exceptions/expression-011.js ecma_2/Exceptions/expression-012.js ecma_2/Exceptions/expression-013.js ecma_2/Exceptions/expression-014.js ecma_2/Exceptions/expression-015.js ecma_2/Exceptions/expression-016.js ecma_2/Exceptions/expression-017.js ecma_2/Exceptions/global-001.js ecma_2/Exceptions/global-002.js ecma_2/Exceptions/lexical-001.js ecma_2/Exceptions/lexical-002.js ecma_2/Exceptions/lexical-003.js ecma_2/Exceptions/lexical-004.js ecma_2/Exceptions/lexical-005.js ecma_2/Exceptions/lexical-006.js ecma_2/Exceptions/lexical-007.js ecma_2/Exceptions/lexical-009.js ecma_2/Exceptions/lexical-010.js ecma_2/Exceptions/lexical-011.js ecma_2/Exceptions/lexical-012.js ecma_2/Exceptions/lexical-013.js ecma_2/Exceptions/lexical-014.js ecma_2/Exceptions/lexical-015.js ecma_2/Exceptions/lexical-016.js ecma_2/Exceptions/lexical-017.js ecma_2/Exceptions/lexical-018.js ecma_2/Exceptions/lexical-019.js ecma_2/Exceptions/lexical-020.js ecma_2/Exceptions/lexical-022.js ecma_2/Exceptions/lexical-023.js ecma_2/Exceptions/lexical-024.js ecma_2/Exceptions/lexical-025.js ecma_2/Exceptions/lexical-026.js ecma_2/Exceptions/lexical-027.js ecma_2/Exceptions/lexical-028.js ecma_2/Exceptions/lexical-029.js ecma_2/Exceptions/lexical-030.js ecma_2/Exceptions/lexical-031.js ecma_2/Exceptions/lexical-032.js ecma_2/Exceptions/lexical-033.js ecma_2/Exceptions/lexical-034.js ecma_2/Exceptions/lexical-035.js ecma_2/Exceptions/lexical-036.js ecma_2/Exceptions/lexical-037.js ecma_2/Exceptions/lexical-038.js ecma_2/Exceptions/lexical-039.js ecma_2/Exceptions/lexical-040.js ecma_2/Exceptions/lexical-041.js ecma_2/Exceptions/lexical-042.js ecma_2/Exceptions/lexical-047.js ecma_2/Exceptions/lexical-048.js ecma_2/Exceptions/lexical-049.js ecma_2/Exceptions/lexical-050.js ecma_2/Exceptions/lexical-051.js ecma_2/Exceptions/lexical-053.js ecma_2/Exceptions/lexical-054.js ecma_2/Exceptions/number-002.js ecma_2/Exceptions/number-003.js ecma_2/Exceptions/statement-001.js ecma_2/Exceptions/statement-002.js ecma_2/Exceptions/statement-003.js ecma_2/Exceptions/statement-004.js ecma_2/Exceptions/statement-005.js ecma_2/Exceptions/statement-006.js ecma_2/Exceptions/statement-007.js ecma_2/Exceptions/statement-008.js ecma_2/Exceptions/string-001.js ecma_2/Exceptions/string-002.js ecma_2/Expressions/StrictEquality-001.js ecma_2/FunctionObjects/apply-001-n.js ecma_2/FunctionObjects/call-1.js ecma_2/LexicalConventions/keywords-001.js ecma_2/LexicalConventions/regexp-literals-001.js ecma_2/LexicalConventions/regexp-literals-002.js ecma_2/RegExp/constructor-001.js ecma_2/RegExp/exec-002.js ecma_2/RegExp/function-001.js ecma_2/RegExp/hex-001.js ecma_2/RegExp/multiline-001.js ecma_2/RegExp/octal-001.js ecma_2/RegExp/octal-002.js ecma_2/RegExp/octal-003.js ecma_2/RegExp/properties-001.js ecma_2/RegExp/properties-002.js ecma_2/RegExp/regress-001.js ecma_2/RegExp/unicode-001.js ecma_2/Statements/dowhile-001.js ecma_2/Statements/dowhile-002.js ecma_2/Statements/dowhile-003.js ecma_2/Statements/dowhile-004.js ecma_2/Statements/dowhile-005.js ecma_2/Statements/dowhile-006.js ecma_2/Statements/dowhile-007.js ecma_2/Statements/forin-001.js ecma_2/Statements/forin-002.js ecma_2/Statements/if-001.js ecma_2/Statements/label-001.js ecma_2/Statements/label-002.js ecma_2/Statements/switch-002.js ecma_2/Statements/switch-003.js ecma_2/Statements/switch-004.js ecma_2/Statements/try-001.js ecma_2/Statements/try-003.js ecma_2/Statements/try-004.js ecma_2/Statements/try-005.js ecma_2/Statements/try-007.js ecma_2/Statements/try-008.js ecma_2/Statements/try-009.js ecma_2/Statements/try-012.js ecma_2/Statements/while-001.js ecma_2/Statements/while-002.js ecma_2/Statements/while-003.js ecma_2/Statements/while-004.js ecma_2/String/match-001.js ecma_2/String/match-002.js ecma_2/String/match-003.js ecma_2/String/match-004.js ecma_2/String/split-001.js ecma_2/String/split-002.js ecma_2/String/split-003.js ecma_2/extensions/constructor-001.js ecma_2/extensions/function-001.js ecma_2/extensions/instanceof-001.js ecma_2/extensions/instanceof-002.js ecma_2/extensions/instanceof-006.js ecma_2/instanceof/instanceof-001.js ecma_2/instanceof/instanceof-002.js ecma_2/instanceof/regress-7635.js ecma_2/jsref.js ecma_3/Array/15.4.4.11-01.js ecma_3/Array/15.4.4.3-1.js ecma_3/Array/15.4.4.4-001.js ecma_3/Array/regress-101488.js ecma_3/Array/regress-130451.js ecma_3/Array/regress-322135-01.js ecma_3/Date/15.9.4.3.js ecma_3/Date/15.9.5.3.js ecma_3/Date/15.9.5.4.js ecma_3/Date/15.9.5.5.js ecma_3/Date/15.9.5.6.js ecma_3/Date/15.9.5.7.js ecma_3/Exceptions/15.11.1.1.js ecma_3/Exceptions/15.11.4.4-1.js ecma_3/Exceptions/15.11.7.6-001.js ecma_3/Exceptions/15.11.7.6-002.js ecma_3/Exceptions/15.11.7.6-003.js ecma_3/Exceptions/binding-001.js ecma_3/Exceptions/regress-181654.js ecma_3/Exceptions/regress-181914.js ecma_3/Exceptions/regress-95101.js ecma_3/ExecutionContexts/10.1.3-1.js ecma_3/ExecutionContexts/10.1.3-2.js ecma_3/ExecutionContexts/10.1.3.js ecma_3/ExecutionContexts/10.1.4-1.js ecma_3/ExecutionContexts/10.6.1-01.js ecma_3/ExecutionContexts/regress-23346.js ecma_3/Expressions/11.10-01.js ecma_3/Expressions/11.10-03.js ecma_3/Expressions/11.6.1-1.js ecma_3/Expressions/11.7.1-01.js ecma_3/Expressions/11.7.2-01.js ecma_3/Expressions/11.7.3-01.js ecma_3/Expressions/11.9.6-1.js ecma_3/FunExpr/fe-001-n.js ecma_3/FunExpr/fe-001.js ecma_3/FunExpr/fe-002.js ecma_3/Function/15.3.4.3-1.js ecma_3/Function/15.3.4.4-1.js ecma_3/Function/arguments-001.js ecma_3/Function/arguments-002.js ecma_3/Function/call-001.js ecma_3/Function/regress-131964.js ecma_3/Function/regress-137181.js ecma_3/Function/regress-193555.js ecma_3/Function/regress-313570.js ecma_3/Function/regress-49286.js ecma_3/Function/regress-58274.js ecma_3/Function/regress-85880.js ecma_3/Function/regress-94506.js ecma_3/Function/regress-97921.js ecma_3/Function/scope-001.js ecma_3/Function/scope-002.js ecma_3/Number/15.7.4.5-1.js ecma_3/Number/15.7.4.6-1.js ecma_3/Number/15.7.4.7-1.js ecma_3/Number/15.7.4.7-2.js ecma_3/NumberFormatting/tostring-001.js ecma_3/Object/8.6.2.6-001.js ecma_3/Object/class-001.js ecma_3/Object/class-002.js ecma_3/Object/class-003.js ecma_3/Object/class-004.js ecma_3/Object/class-005.js ecma_3/Object/regress-361274.js ecma_3/Object/regress-385393-07.js ecma_3/Object/regress-72773.js ecma_3/Object/regress-79129-001.js ecma_3/Operators/11.13.1-001.js ecma_3/Operators/11.13.1-002.js ecma_3/Operators/11.4.1-001.js ecma_3/RegExp/15.10.2-1.js ecma_3/RegExp/15.10.2.12.js ecma_3/RegExp/15.10.3.1-1.js ecma_3/RegExp/15.10.3.1-2.js ecma_3/RegExp/15.10.4.1-1.js ecma_3/RegExp/15.10.4.1-2.js ecma_3/RegExp/15.10.4.1-3.js ecma_3/RegExp/15.10.4.1-4.js ecma_3/RegExp/15.10.4.1-5-n.js ecma_3/RegExp/15.10.6.2-1.js ecma_3/RegExp/15.10.6.2-2.js ecma_3/RegExp/octal-001.js ecma_3/RegExp/octal-002.js ecma_3/RegExp/perlstress-001.js ecma_3/RegExp/perlstress-002.js ecma_3/RegExp/regress-100199.js ecma_3/RegExp/regress-105972.js ecma_3/RegExp/regress-119909.js ecma_3/RegExp/regress-122076.js ecma_3/RegExp/regress-123437.js ecma_3/RegExp/regress-165353.js ecma_3/RegExp/regress-169497.js ecma_3/RegExp/regress-169534.js ecma_3/RegExp/regress-187133.js ecma_3/RegExp/regress-191479.js ecma_3/RegExp/regress-202564.js ecma_3/RegExp/regress-209067.js ecma_3/RegExp/regress-209919.js ecma_3/RegExp/regress-216591.js ecma_3/RegExp/regress-220367-001.js ecma_3/RegExp/regress-223273.js ecma_3/RegExp/regress-223535.js ecma_3/RegExp/regress-224676.js ecma_3/RegExp/regress-225289.js ecma_3/RegExp/regress-225343.js ecma_3/RegExp/regress-24712.js ecma_3/RegExp/regress-28686.js ecma_3/RegExp/regress-309840.js ecma_3/RegExp/regress-312351.js ecma_3/RegExp/regress-31316.js ecma_3/RegExp/regress-346090.js ecma_3/RegExp/regress-375715-02.js ecma_3/RegExp/regress-375715-03.js ecma_3/RegExp/regress-57572.js ecma_3/RegExp/regress-57631.js ecma_3/RegExp/regress-67773.js ecma_3/RegExp/regress-76683.js ecma_3/RegExp/regress-78156.js ecma_3/RegExp/regress-85721.js ecma_3/RegExp/regress-87231.js ecma_3/RegExp/regress-98306.js ecma_3/Statements/12.6.3.js ecma_3/Statements/regress-131348.js ecma_3/Statements/regress-157509.js ecma_3/Statements/regress-194364.js ecma_3/Statements/regress-226517.js ecma_3/Statements/regress-302439.js ecma_3/Statements/regress-324650.js ecma_3/Statements/regress-74474-001.js ecma_3/Statements/regress-74474-002.js ecma_3/Statements/regress-74474-003.js ecma_3/Statements/regress-83532-001.js ecma_3/Statements/regress-83532-002.js ecma_3/Statements/switch-001.js ecma_3/String/regress-104375.js ecma_3/String/regress-189898.js ecma_3/String/regress-313567.js ecma_3/String/regress-83293.js ecma_3/Unicode/uc-001-n.js ecma_3/Unicode/uc-001.js ecma_3/Unicode/uc-002-n.js ecma_3/Unicode/uc-002.js ecma_3/Unicode/uc-003.js ecma_3/Unicode/uc-004.js ecma_3/Unicode/uc-005.js ecma_3/extensions/regress-103087.js ecma_3/extensions/regress-188206-01.js ecma_3/extensions/regress-188206-02.js ecma_3/extensions/regress-220367-002.js ecma_3/extensions/regress-228087.js ecma_3/extensions/regress-320854.js ecma_3/extensions/regress-327170.js ecma_3/extensions/regress-385393-03.js js-test-driver-begin.js js-test-driver-end.js js1_1/jsref.js js1_2/Array/array_split_1.js js1_2/Array/general1.js js1_2/Array/general2.js js1_2/Array/slice.js js1_2/Array/splice1.js js1_2/Array/splice2.js js1_2/Array/tostring_1.js js1_2/Array/tostring_2.js js1_2/Objects/toString-001.js js1_2/String/charCodeAt.js js1_2/String/concat.js js1_2/String/match.js js1_2/String/slice.js js1_2/function/Number.js js1_2/function/String.js js1_2/function/definition-1.js js1_2/function/length.js js1_2/function/nesting-1.js js1_2/function/nesting.js js1_2/function/regexparg-2-n.js js1_2/jsref.js js1_2/operator/strictEquality.js js1_2/regexp/RegExp_dollar_number.js js1_2/regexp/RegExp_input.js js1_2/regexp/RegExp_input_as_array.js js1_2/regexp/RegExp_lastIndex.js js1_2/regexp/RegExp_lastMatch.js js1_2/regexp/RegExp_lastMatch_as_array.js js1_2/regexp/RegExp_lastParen.js js1_2/regexp/RegExp_lastParen_as_array.js js1_2/regexp/RegExp_leftContext.js js1_2/regexp/RegExp_leftContext_as_array.js js1_2/regexp/RegExp_multiline.js js1_2/regexp/RegExp_multiline_as_array.js js1_2/regexp/RegExp_object.js js1_2/regexp/RegExp_rightContext.js js1_2/regexp/RegExp_rightContext_as_array.js js1_2/regexp/alphanumeric.js js1_2/regexp/asterisk.js js1_2/regexp/backslash.js js1_2/regexp/backspace.js js1_2/regexp/beginLine.js js1_2/regexp/character_class.js js1_2/regexp/compile.js js1_2/regexp/control_characters.js js1_2/regexp/digit.js js1_2/regexp/dot.js js1_2/regexp/endLine.js js1_2/regexp/everything.js js1_2/regexp/exec.js js1_2/regexp/flags.js js1_2/regexp/global.js js1_2/regexp/hexadecimal.js js1_2/regexp/ignoreCase.js js1_2/regexp/interval.js js1_2/regexp/octal.js js1_2/regexp/parentheses.js js1_2/regexp/regress-6359.js js1_2/regexp/regress-9141.js js1_2/regexp/simple_form.js js1_2/regexp/source.js js1_2/regexp/special_characters.js js1_2/regexp/string_replace.js js1_2/regexp/string_search.js js1_2/regexp/string_split.js js1_2/regexp/test.js js1_2/regexp/toString.js js1_2/regexp/vertical_bar.js js1_2/regexp/whitespace.js js1_2/regexp/word_boundary.js js1_2/regress/regress-144834.js js1_2/regress/regress-7703.js js1_2/statements/break.js js1_2/statements/do_while.js js1_2/statements/switch.js js1_2/statements/switch2.js js1_2/version120/boolean-001.js js1_3/Boolean/boolean-001.js js1_3/Script/delete-001.js js1_3/Script/function-002.js js1_3/Script/new-001.js js1_3/Script/switch-001.js js1_3/extensions/proto_10.js js1_3/extensions/proto_2.js js1_3/extensions/proto_5.js js1_3/inherit/proto_1.js js1_3/inherit/proto_10.js js1_3/inherit/proto_11.js js1_3/inherit/proto_12.js js1_3/inherit/proto_3.js js1_3/inherit/proto_4.js js1_3/inherit/proto_6.js js1_3/inherit/proto_7.js js1_3/inherit/proto_8.js js1_3/inherit/proto_9.js js1_3/jsref.js js1_3/regress/delete-001.js js1_3/regress/function-002.js js1_3/regress/new-001.js js1_3/regress/switch-001.js js1_4/Eval/eval-001.js js1_4/Eval/eval-002.js js1_4/Eval/eval-003.js js1_4/Functions/function-001.js js1_4/Regress/date-001-n.js js1_4/Regress/function-001.js js1_4/Regress/function-002.js js1_4/Regress/function-003.js js1_4/Regress/function-004-n.js js1_4/Regress/regress-7224.js js1_4/Regress/toString-001-n.js js1_4/jsref.js js1_5/Array/11.1.4.js js1_5/Array/array-001.js js1_5/Array/regress-101964.js js1_5/Array/regress-107138.js js1_5/Array/regress-108440.js js1_5/Array/regress-154338.js js1_5/Array/regress-178722.js js1_5/Array/regress-255555.js js1_5/Array/regress-299644.js js1_5/Array/regress-300858.js js1_5/Array/regress-310351.js js1_5/Array/regress-311515.js js1_5/Array/regress-313153.js js1_5/Array/regress-315509-01.js js1_5/Array/regress-345961.js js1_5/Array/regress-348810.js js1_5/Array/regress-350256-01.js js1_5/Array/regress-350256-02.js js1_5/Array/regress-360681-01.js js1_5/Array/regress-360681-02.js js1_5/Array/regress-364104.js js1_5/Array/regress-94257.js js1_5/Date/regress-188211.js js1_5/Date/regress-301738-01.js js1_5/Date/regress-309925-01.js js1_5/Date/regress-346027.js js1_5/Exceptions/catchguard-002-n.js js1_5/Exceptions/catchguard-003-n.js js1_5/Exceptions/regress-123002.js js1_5/Exceptions/regress-232182.js js1_5/Exceptions/regress-273931.js js1_5/Exceptions/regress-347674.js js1_5/Exceptions/regress-350837.js js1_5/Expressions/regress-192288.js js1_5/Expressions/regress-96526-argsub.js js1_5/Expressions/regress-96526-noargsub.js js1_5/Function/10.1.6-01.js js1_5/Function/10.1.6.js js1_5/Function/15.3.4.4.js js1_5/Function/regress-123371.js js1_5/Function/regress-178389.js js1_5/Function/regress-292215.js js1_5/Function/regress-344052.js js1_5/GC/regress-104584.js js1_5/GC/regress-203278-2.js js1_5/GC/regress-203278-3.js js1_5/GC/regress-278725.js js1_5/GC/regress-306788.js js1_5/GC/regress-313276.js js1_5/GC/regress-313479.js js1_5/GC/regress-316885-02.js js1_5/GC/regress-316885-03.js js1_5/GC/regress-319980-01.js js1_5/GC/regress-331719.js js1_5/GC/regress-341877-01.js js1_5/GC/regress-341877-02.js js1_5/GC/regress-352606.js js1_5/GC/regress-383269-01.js js1_5/GC/regress-383269-02.js js1_5/GC/regress-390078.js js1_5/GetSet/regress-375976.js js1_5/LexicalConventions/lexical-001.js js1_5/LexicalConventions/regress-177314.js js1_5/Object/regress-137000.js js1_5/Object/regress-192105.js js1_5/Object/regress-338709.js js1_5/Object/regress-382503.js js1_5/Object/regress-382532.js js1_5/Object/regress-90596-003.js js1_5/Regress/regress-104077.js js1_5/Regress/regress-110286.js js1_5/Regress/regress-111557.js js1_5/Regress/regress-114491.js js1_5/Regress/regress-114493.js js1_5/Regress/regress-115436.js js1_5/Regress/regress-116228.js js1_5/Regress/regress-118849.js js1_5/Regress/regress-127243.js js1_5/Regress/regress-127557.js js1_5/Regress/regress-131510-001.js js1_5/Regress/regress-140852.js js1_5/Regress/regress-140974.js js1_5/Regress/regress-146596.js js1_5/Regress/regress-152646.js js1_5/Regress/regress-159334.js js1_5/Regress/regress-162392.js js1_5/Regress/regress-165201.js js1_5/Regress/regress-167658.js js1_5/Regress/regress-168347.js js1_5/Regress/regress-170193.js js1_5/Regress/regress-172699.js js1_5/Regress/regress-174709.js js1_5/Regress/regress-176125.js js1_5/Regress/regress-185165.js js1_5/Regress/regress-191633.js js1_5/Regress/regress-192414.js js1_5/Regress/regress-193418.js js1_5/Regress/regress-203402.js js1_5/Regress/regress-203841.js js1_5/Regress/regress-204210.js js1_5/Regress/regress-210682.js js1_5/Regress/regress-211590.js js1_5/Regress/regress-214761.js js1_5/Regress/regress-216320.js js1_5/Regress/regress-224956.js js1_5/Regress/regress-229006.js js1_5/Regress/regress-230216-1.js js1_5/Regress/regress-230216-2.js js1_5/Regress/regress-230216-3.js js1_5/Regress/regress-233483-2.js js1_5/Regress/regress-233483.js js1_5/Regress/regress-238881.js js1_5/Regress/regress-238945.js js1_5/Regress/regress-243174.js js1_5/Regress/regress-243389-n.js js1_5/Regress/regress-243869.js js1_5/Regress/regress-244470.js js1_5/Regress/regress-244619.js js1_5/Regress/regress-245113.js js1_5/Regress/regress-245308.js js1_5/Regress/regress-246911.js js1_5/Regress/regress-246964.js js1_5/Regress/regress-253150.js js1_5/Regress/regress-254296.js js1_5/Regress/regress-254974.js js1_5/Regress/regress-256501.js js1_5/Regress/regress-256617.js js1_5/Regress/regress-256798.js js1_5/Regress/regress-260541.js js1_5/Regress/regress-261887.js js1_5/Regress/regress-274888.js js1_5/Regress/regress-275378.js js1_5/Regress/regress-276103.js js1_5/Regress/regress-278873.js js1_5/Regress/regress-280769-3.js js1_5/Regress/regress-280769-4.js js1_5/Regress/regress-281487.js js1_5/Regress/regress-281930.js js1_5/Regress/regress-283477.js js1_5/Regress/regress-286216.js js1_5/Regress/regress-288688.js js1_5/Regress/regress-289094.js js1_5/Regress/regress-290656.js js1_5/Regress/regress-294191.js js1_5/Regress/regress-294195-01.js js1_5/Regress/regress-294195-02.js js1_5/Regress/regress-295052.js js1_5/Regress/regress-295666.js js1_5/Regress/regress-306633.js js1_5/Regress/regress-306727.js js1_5/Regress/regress-306794.js js1_5/Regress/regress-308566.js js1_5/Regress/regress-310295.js js1_5/Regress/regress-310607.js js1_5/Regress/regress-310993.js js1_5/Regress/regress-311071.js js1_5/Regress/regress-311629.js js1_5/Regress/regress-312260.js js1_5/Regress/regress-31255.js js1_5/Regress/regress-314401.js js1_5/Regress/regress-315990.js js1_5/Regress/regress-317476.js js1_5/Regress/regress-317714-02.js js1_5/Regress/regress-319384.js js1_5/Regress/regress-320032.js js1_5/Regress/regress-321757.js js1_5/Regress/regress-321874.js js1_5/Regress/regress-322430.js js1_5/Regress/regress-326467.js js1_5/Regress/regress-328012.js js1_5/Regress/regress-328897.js js1_5/Regress/regress-329383.js js1_5/Regress/regress-330951.js js1_5/Regress/regress-334807-01.js js1_5/Regress/regress-334807-03.js js1_5/Regress/regress-334807-05.js js1_5/Regress/regress-334807-06.js js1_5/Regress/regress-338307.js js1_5/Regress/regress-340369.js js1_5/Regress/regress-341360.js js1_5/Regress/regress-343966.js js1_5/Regress/regress-344804.js js1_5/Regress/regress-344959.js js1_5/Regress/regress-346801.js js1_5/Regress/regress-349482-02.js js1_5/Regress/regress-349592.js js1_5/Regress/regress-350253.js js1_5/Regress/regress-350312.js js1_5/Regress/regress-350415.js js1_5/Regress/regress-351116.js js1_5/Regress/regress-351515.js js1_5/Regress/regress-352009.js js1_5/Regress/regress-352208.js js1_5/Regress/regress-360969-01.js js1_5/Regress/regress-360969-02.js js1_5/Regress/regress-360969-03.js js1_5/Regress/regress-360969-04.js js1_5/Regress/regress-366468.js js1_5/Regress/regress-367561-01.js js1_5/Regress/regress-379245.js js1_5/Regress/regress-39309.js js1_5/Regress/regress-398609.js js1_5/Regress/regress-406769.js js1_5/Regress/regress-407024.js js1_5/Regress/regress-407323.js js1_5/Regress/regress-407957.js js1_5/Regress/regress-57043.js js1_5/Regress/regress-68498-001.js js1_5/Regress/regress-68498-002.js js1_5/Regress/regress-68498-004.js js1_5/Regress/regress-69607.js js1_5/Regress/regress-71107.js js1_5/Regress/regress-76054.js js1_5/Regress/regress-80981.js js1_5/Regress/regress-82306.js js1_5/Regress/regress-90445.js js1_5/Regress/regress-96526-001.js js1_5/Regress/regress-96526-003.js js1_5/Scope/regress-154693.js js1_5/Scope/regress-181834.js js1_5/Scope/regress-184107.js js1_5/Scope/regress-185485.js js1_5/Scope/regress-191276.js js1_5/Scope/regress-192226.js js1_5/Scope/regress-202678-001.js js1_5/Scope/regress-202678-002.js js1_5/Scope/regress-208496-001.js js1_5/Scope/regress-208496-002.js js1_5/Scope/regress-220362.js js1_5/Scope/regress-77578-001.js js1_5/Scope/scope-002.js js1_5/Scope/scope-003.js js1_5/String/regress-107771.js js1_5/String/regress-112626.js js1_5/String/regress-179068.js js1_5/String/regress-314890.js js1_5/decompilation/regress-344120.js js1_5/decompilation/regress-349489.js js1_5/decompilation/regress-349663.js js1_5/decompilation/regress-350670.js js1_5/decompilation/regress-351625.js js1_5/decompilation/regress-351626.js js1_5/decompilation/regress-351705.js js1_5/decompilation/regress-352022.js js1_5/decompilation/regress-352073.js js1_5/decompilation/regress-352312.js js1_5/decompilation/regress-352360.js js1_5/decompilation/regress-352873-01.js js1_5/decompilation/regress-352873-02.js js1_5/decompilation/regress-353120.js js1_5/decompilation/regress-354878.js js1_5/decompilation/regress-354910.js js1_5/decompilation/regress-371692.js js1_5/decompilation/regress-373678.js js1_5/decompilation/regress-375639.js js1_5/decompilation/regress-376564.js js1_5/decompilation/regress-383721.js js1_5/decompilation/regress-406555.js js1_5/extensions/catchguard-001.js js1_5/extensions/catchguard-002.js js1_5/extensions/catchguard-003.js js1_5/extensions/getset-004.js js1_5/extensions/getset-005.js js1_5/extensions/getset-006.js js1_5/extensions/no-such-method.js js1_5/extensions/regress-104077.js js1_5/extensions/regress-178722.js js1_5/extensions/regress-220584.js js1_5/extensions/regress-225831.js js1_5/extensions/regress-226078.js js1_5/extensions/regress-237461.js js1_5/extensions/regress-245795.js js1_5/extensions/regress-255245.js js1_5/extensions/regress-291213.js js1_5/extensions/regress-311161.js js1_5/extensions/regress-311583.js js1_5/extensions/regress-311792-01.js js1_5/extensions/regress-311792-02.js js1_5/extensions/regress-312278.js js1_5/extensions/regress-313500.js js1_5/extensions/regress-313630.js js1_5/extensions/regress-313763.js js1_5/extensions/regress-313803.js js1_5/extensions/regress-313938.js js1_5/extensions/regress-314874.js js1_5/extensions/regress-319683.js js1_5/extensions/regress-322957.js js1_5/extensions/regress-325269.js js1_5/extensions/regress-327608.js js1_5/extensions/regress-328556.js js1_5/extensions/regress-338804-01.js js1_5/extensions/regress-338804-03.js js1_5/extensions/regress-339685.js js1_5/extensions/regress-340199.js js1_5/extensions/regress-341956-02.js js1_5/extensions/regress-341956-03.js js1_5/extensions/regress-346494-01.js js1_5/extensions/regress-347306-02.js js1_5/extensions/regress-350312-01.js js1_5/extensions/regress-350312-02.js js1_5/extensions/regress-350312-03.js js1_5/extensions/regress-351102-01.js js1_5/extensions/regress-351102-02.js js1_5/extensions/regress-351102-06.js js1_5/extensions/regress-351973.js js1_5/extensions/regress-352261.js js1_5/extensions/regress-352281.js js1_5/extensions/regress-354297.js js1_5/extensions/regress-354541-01.js js1_5/extensions/regress-354541-03.js js1_5/extensions/regress-355982.js js1_5/extensions/regress-356402.js js1_5/extensions/regress-363988.js js1_5/extensions/regress-365527.js js1_5/extensions/regress-365692.js js1_5/extensions/regress-366288.js js1_5/extensions/regress-366292.js js1_5/extensions/regress-366396.js js1_5/extensions/regress-367118-01.js js1_5/extensions/regress-367118-02.js js1_5/extensions/regress-367120-01.js js1_5/extensions/regress-367120-02.js js1_5/extensions/regress-367121.js js1_5/extensions/regress-367501-01.js js1_5/extensions/regress-367501-02.js js1_5/extensions/regress-367501-03.js js1_5/extensions/regress-367589.js js1_5/extensions/regress-369404.js js1_5/extensions/regress-374589.js js1_5/extensions/regress-375183.js js1_5/extensions/regress-380889.js js1_5/extensions/regress-385134.js js1_5/extensions/regress-394967.js js1_5/extensions/regress-396326.js js1_5/extensions/regress-407501.js js1_5/extensions/regress-44009.js js1_5/extensions/regress-90596-001.js js1_5/extensions/regress-90596-002.js js1_5/extensions/regress-96284-001.js js1_5/extensions/regress-96284-002.js js1_5/extensions/scope-001.js js1_6/Array/filter.js js1_6/Array/regress-304828.js js1_6/Array/regress-305002.js js1_6/Array/regress-310425-01.js js1_6/Array/regress-310425-02.js js1_6/Array/regress-320887.js js1_6/Array/regress-352742-01.js js1_6/Array/regress-352742-02.js js1_6/Array/regress-415451.js js1_6/Array/regress-415540.js js1_6/Regress/regress-301574.js js1_6/Regress/regress-311157-01.js js1_6/Regress/regress-311157-02.js js1_6/Regress/regress-314887.js js1_6/Regress/regress-351795.js js1_6/Regress/regress-352271.js js1_6/Regress/regress-378492.js js1_6/decompilation/regress-352084.js js1_6/extensions/regress-385393-08.js js1_7/GC/regress-341675.js js1_7/block/order-of-operation.js js1_7/block/regress-341939.js js1_7/block/regress-344139.js js1_7/block/regress-344370.js js1_7/block/regress-345542.js js1_7/block/regress-348685.js js1_7/block/regress-349283.js js1_7/block/regress-349298.js js1_7/block/regress-349507.js js1_7/block/regress-349653.js js1_7/block/regress-349962.js js1_7/block/regress-350279.js js1_7/block/regress-350730.js js1_7/block/regress-350793-01.js js1_7/block/regress-351497.js js1_7/block/regress-351606.js js1_7/block/regress-352092.js js1_7/block/regress-352185.js js1_7/block/regress-352212.js js1_7/block/regress-352267.js js1_7/block/regress-352616.js js1_7/block/regress-352624.js js1_7/block/regress-352907.js js1_7/block/regress-357754.js js1_7/block/regress-376410.js js1_7/block/regress-396900.js js1_7/block/regress-411279.js js1_7/decompilation/regress-349633.js js1_7/decompilation/regress-350810.js js1_7/decompilation/regress-352015.js js1_7/decompilation/regress-352025.js js1_7/decompilation/regress-352269.js js1_7/decompilation/regress-352272.js js1_7/decompilation/regress-352283.js js1_7/decompilation/regress-352732.js js1_7/decompilation/regress-355635.js js1_7/decompilation/regress-355786.js js1_7/decompilation/regress-375794.js js1_7/decompilation/regress-380506.js js1_7/expressions/destructuring-scope.js js1_7/expressions/regress-346203.js js1_7/expressions/regress-346645-01.js js1_7/expressions/regress-346645-02.js js1_7/expressions/regress-346645-03.js js1_7/expressions/regress-349624.js js1_7/expressions/regress-349818.js js1_7/extensions/basic-Iterator.js js1_7/extensions/basic-for-in.js js1_7/extensions/destructuring-order.js js1_7/extensions/iterator-ctor.js js1_7/extensions/regress-346021.js js1_7/extensions/regress-346642-02.js js1_7/extensions/regress-346773.js js1_7/extensions/regress-349619.js js1_7/extensions/regress-350312.js js1_7/extensions/regress-351070-02.js js1_7/extensions/regress-352797-01.js js1_7/extensions/regress-352885-01.js js1_7/extensions/regress-352885-02.js js1_7/extensions/regress-353214-02.js js1_7/extensions/regress-354499-01.js js1_7/extensions/regress-354499-02.js js1_7/extensions/regress-354945-01.js js1_7/extensions/regress-355052-01.js js1_7/extensions/regress-355052-02.js js1_7/extensions/regress-355052-03.js js1_7/extensions/regress-355410.js js1_7/extensions/regress-355512.js js1_7/extensions/regress-355578.js js1_7/extensions/regress-355583.js js1_7/extensions/regress-363040-01.js js1_7/extensions/regress-363040-02.js js1_7/extensions/regress-366668-01.js js1_7/extensions/regress-366668-02.js js1_7/extensions/regress-387955-01.js js1_7/extensions/regress-392308.js js1_7/extensions/regress-396326.js js1_7/geniter/326466-01.js js1_7/geniter/builtin-Iterator-function.js js1_7/geniter/evens.js js1_7/geniter/fibonacci-matrix-generator.js js1_7/geniter/iterator-toString.js js1_7/geniter/message-value-passing.js js1_7/geniter/multiple-close.js js1_7/geniter/nested-yield.js js1_7/geniter/pi-generator.js js1_7/geniter/regress-345736.js js1_7/geniter/regress-345855.js js1_7/geniter/regress-345879-01.js js1_7/geniter/regress-347593.js js1_7/geniter/regress-349012-02.js js1_7/geniter/regress-349012-03.js js1_7/geniter/regress-349012-04.js js1_7/geniter/regress-349012-05.js js1_7/geniter/regress-349023-01.js js1_7/geniter/regress-349023-02.js js1_7/geniter/regress-349023-03.js js1_7/geniter/regress-349362.js js1_7/geniter/regress-349851.js js1_7/geniter/regress-350621.js js1_7/geniter/regress-350809.js js1_7/geniter/regress-351120.js js1_7/geniter/regress-352197.js js1_7/geniter/regress-352876.js js1_7/geniter/regress-355834.js js1_7/geniter/regress-359062.js js1_7/geniter/regress-366941.js js1_7/geniter/regress-382335.js js1_7/geniter/regress-390918.js js1_7/geniter/send-no-rhs.js js1_7/geniter/sequential-yields.js js1_7/geniter/throw-after-close.js js1_7/geniter/throw-forever.js js1_7/geniter/unreachable-yield.js js1_7/geniter/yield-undefined.js js1_7/iterable/regress-341499.js js1_7/iterable/regress-341510.js js1_7/iterable/regress-341815.js js1_7/iterable/regress-341821.js js1_7/iterable/regress-354750-01.js js1_7/iterable/regress-355025.js js1_7/iterable/regress-355075-01.js js1_7/iterable/regress-355090.js js1_7/iterable/regress-412467.js js1_7/lexical/regress-346642-04.js js1_7/regress/regress-352640-01.js js1_7/regress/regress-352640-02.js js1_7/regress/regress-352640-03.js js1_7/regress/regress-352640-04.js js1_7/regress/regress-352797-02.js js1_7/regress/regress-352870-03.js js1_7/regress/regress-353079.js js1_7/regress/regress-355023.js js1_7/regress/regress-355832-01.js js1_7/regress/regress-361566.js js1_7/regress/regress-369666-01.js js1_7/regress/regress-369666-02.js js1_7/regress/regress-372331.js js1_7/regress/regress-373827-01.js js1_7/regress/regress-373827-02.js js1_7/regress/regress-373828.js js1_7/regress/regress-379442.js js1_7/regress/regress-385393-05.js js1_7/regress/regress-407727-01.js js1_7/regress/regress-407727-02.js js1_7/regress/regress-407957.js js1_7/regress/regress-414553.js lc2/Arrays/array-001.js lc2/Arrays/array-002.js lc2/Arrays/array-003.js lc2/Arrays/array-004.js lc2/Arrays/array-005.js lc2/Arrays/array-006-n.js lc2/Arrays/array-007-n.js lc2/Arrays/array-008-n.js lc2/Classes/class-001.js lc2/Classes/class-002.js lc2/JSToJava/character-001.js lc2/JSToJava/double-001.js lc2/JSToJava/double-002.js lc2/JSToJava/float-001.js lc2/JSToJava/float-002.js lc2/JSToJava/integer-001.js lc2/JSToJava/integer-002.js lc2/JSToJava/long-001.js lc2/JSToJava/long-002.js lc2/JSToJava/long-003-n.js lc2/JSToJava/short-001.js lc2/JSToJava/short-002.js lc2/JSToJava/short-003-n.js lc2/JavaToJS/String-001.js lc2/JavaToJS/boolean-001.js lc2/JavaToJS/boolean-003.js lc2/JavaToJS/boolean-004.js lc2/JavaToJS/boolean-005.js lc2/JavaToJS/char-001.js lc2/JavaToJS/char-002.js lc2/JavaToJS/enum-001.js lc2/JavaToJS/enum-002.js lc2/JavaToJS/null-001.js lc2/JavaToJS/number-001.js lc2/JavaToJS/number-002.js lc2/Methods/method-001.js lc2/Methods/method-002.js lc2/Methods/method-003.js lc2/Methods/method-004-n.js lc2/Methods/method-005.js lc2/Methods/method-006-n.js lc2/Methods/println-001.js lc2/Objects/object-001.js lc2/Objects/object-002.js lc2/Objects/object-003.js lc2/Objects/object-004.js lc2/Objects/object-005.js lc2/Objects/object-006.js lc2/Packages/package-001.js lc2/Packages/package-002.js lc2/Packages/package-003.js lc2/Packages/package-005.js lc2/Packages/package-006.js lc2/Packages/package-007-n.js lc2/Packages/package-008-n.js lc2/misc/constructor.js lc3/ArrayMethods/byte-002.js lc3/ConvertBoolean/boolean-005-n.js lc3/ConvertBoolean/boolean-006-n.js lc3/ConvertBoolean/boolean-007-n.js lc3/ConvertBoolean/boolean-008-n.js lc3/ConvertBoolean/boolean-009-n.js lc3/ConvertBoolean/boolean-010-n.js lc3/ConvertBoolean/boolean-011-n.js lc3/ConvertBoolean/boolean-012-n.js lc3/ConvertBoolean/boolean-013-n.js lc3/ConvertNull/null-002.js lc3/ConvertNull/null-003-n.js lc3/ConvertNull/null-004-n.js lc3/ConvertNull/null-006-n.js lc3/ConvertString/string-004-n.js lc3/ConvertString/string-005-n.js lc3/ConvertString/string-007-n.js lc3/ConvertUndefined/undefined-001-n.js lc3/JSBoolean/boolean-002-n.js lc3/JSBoolean/boolean-003-n.js lc3/JSBoolean/boolean-004-n.js lc3/JSBoolean/boolean-005-n.js lc3/JSBoolean/boolean-006-n.js lc3/JSBoolean/boolean-007-n.js lc3/JSBoolean/boolean-008-n.js lc3/JSNull/ToBoolean-001-n.js lc3/JSNull/ToLong-001-n.js lc3/JSNull/ToNumber-001-n.js lc3/JSNumber/ToByte-002-n.js lc3/JSNumber/ToByte-003-n.js lc3/JSNumber/ToByte-005-n.js lc3/JSNumber/ToChar-002-n.js lc3/JSNumber/ToChar-003-n.js lc3/JSNumber/ToChar-005-n.js lc3/JSNumber/ToChar-006-n.js lc3/JSNumber/ToInt-002-n.js lc3/JSNumber/ToInt-003-n.js lc3/JSNumber/ToLong-002-n.js lc3/JSNumber/ToLong-003-n.js lc3/JSNumber/ToLong-004-n.js lc3/JSNumber/ToLong-005-n.js lc3/JSNumber/ToLong-006-n.js lc3/JSNumber/ToLong-007-n.js lc3/JSNumber/ToLong-008-n.js lc3/JSNumber/ToLong-009-n.js lc3/JSNumber/ToLong-010-n.js lc3/JSNumber/ToLong-011-n.js lc3/JSNumber/ToShort-003-n.js lc3/JSNumber/ToShort-005-n.js lc3/JSObject/ToDouble-002-n.js lc3/JSObject/ToDouble-003-n.js lc3/JSObject/ToFloat-002-n.js lc3/JSObject/ToFloat-003-n.js lc3/JSUndefined/undefined-002-n.js lc3/JSUndefined/undefined-003-n.js lc3/JSUndefined/undefined-004-n.js lc3/JSUndefined/undefined-005-n.js lc3/JSUndefined/undefined-006-n.js lc3/JSUndefined/undefined-008-n.js lc3/JSUndefined/undefined-009-n.js lc3/JSUndefined/undefined-010-n.js lc3/JavaArray/ToArray-002-n.js lc3/JavaArray/ToBoolean-001-n.js lc3/JavaObject/JavaObjectToBoolean-002-n.js lc3/JavaObject/JavaObjectToByte-002-n.js lc3/JavaObject/JavaObjectToByte-007-n.js lc3/JavaObject/JavaObjectToByte-008-n.js lc3/JavaObject/JavaObjectToChar-003-n.js lc3/JavaObject/JavaObjectToChar-005-n.js lc3/JavaObject/JavaObjectToChar-006-n.js lc3/JavaObject/JavaObjectToInt-002-n.js lc3/JavaObject/JavaObjectToInt-003-n.js lc3/JavaObject/JavaObjectToInt-004-n.js lc3/JavaObject/JavaObjectToLong-002-n.js lc3/JavaObject/JavaObjectToLong-003-n.js lc3/JavaObject/JavaObjectToLong-004-n.js lc3/JavaObject/JavaObjectToLong-006-n.js lc3/JavaObject/JavaObjectToShort-002-n.js lc3/JavaObject/JavaObjectToShort-003-n.js lc3/JavaObject/JavaObjectToShort-004-n.js lc3/StringMethods/string-001.js lc3/StringMethods/string-001.js jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/build.xml0000644000175000017500000001473211314263504026227 0ustar jamespagejamespage00000000000000 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/opt-1.tests0000644000175000017500000015172411314263504026435 0ustar jamespagejamespage00000000000000e4x/Expressions/11.1.1.js e4x/Expressions/11.1.2.js e4x/Expressions/11.1.3.js e4x/Expressions/11.1.4-06.js e4x/Expressions/11.1.4-07.js e4x/Expressions/11.1.5.js e4x/Expressions/11.2.1.js e4x/Expressions/11.2.2.js e4x/Expressions/11.2.3.js e4x/Expressions/11.2.4.js e4x/Expressions/11.3.1.js e4x/Expressions/11.3.2.js e4x/Expressions/11.4.1.js e4x/Expressions/11.5.1.js e4x/Expressions/11.6.3.js e4x/Expressions/regress-301545.js e4x/Expressions/regress-302531.js e4x/Expressions/regress-340024.js e4x/GC/regress-292455.js e4x/GC/regress-313952-01.js e4x/GC/regress-324117.js e4x/Namespace/13.2.1.js e4x/Namespace/13.2.2.js e4x/Namespace/13.2.5.js e4x/Namespace/regress-283972.js e4x/Namespace/regress-292863.js e4x/Namespace/regress-350442.js e4x/QName/13.3.1.js e4x/QName/13.3.2.js e4x/QName/13.3.5.js e4x/QName/regress-373595-01.js e4x/QName/regress-373595-02.js e4x/QName/regress-373595-03.js e4x/Regress/regress-263935.js e4x/Regress/regress-263936.js e4x/Regress/regress-264369.js e4x/Regress/regress-271545.js e4x/Regress/regress-277650.js e4x/Regress/regress-277664.js e4x/Regress/regress-277683.js e4x/Regress/regress-277935.js e4x/Regress/regress-283349.js e4x/Regress/regress-290056.js e4x/Regress/regress-301573.js e4x/Regress/regress-301596.js e4x/Regress/regress-301692.js e4x/Regress/regress-313799.js e4x/Regress/regress-325425.js e4x/Regress/regress-327691-01.js e4x/Regress/regress-327691-02.js e4x/Regress/regress-327697.js e4x/Regress/regress-328249.js e4x/Regress/regress-329257.js e4x/Regress/regress-331664.js e4x/Regress/regress-350206-1.js e4x/Regress/regress-350206.js e4x/Regress/regress-352103.js e4x/Regress/regress-354145-01.js e4x/Regress/regress-354145-02.js e4x/Regress/regress-354145-03.js e4x/Regress/regress-354145-04.js e4x/Regress/regress-354145-05.js e4x/Regress/regress-354145-07.js e4x/Regress/regress-355474-02.js e4x/Regress/regress-356238-01.js e4x/Regress/regress-369032.js e4x/Regress/regress-369536.js e4x/Regress/regress-372564.js e4x/Regress/regress-374106.js e4x/Regress/regress-374112.js e4x/Regress/regress-374116.js e4x/Regress/regress-374160.js e4x/Regress/regress-378492.js e4x/Regress/regress-407323.js e4x/Statements/12.1.js e4x/Statements/12.2.js e4x/Statements/12.3-01.js e4x/TypeConversion/10.1.2.js e4x/TypeConversion/10.3.1.js e4x/TypeConversion/10.3.js e4x/TypeConversion/10.4.1.js e4x/TypeConversion/10.4.js e4x/Types/9.1.1.1.js e4x/Types/9.1.1.2.js e4x/Types/9.1.1.3.js e4x/Types/9.1.1.6.js e4x/Types/9.2.1.1.js e4x/Types/9.2.1.2.js e4x/Types/9.2.1.8.js e4x/XML/13.4.1.js e4x/XML/13.4.2.js e4x/XML/13.4.3.10.js e4x/XML/13.4.4.12-1.js e4x/XML/13.4.4.12.js e4x/XML/13.4.4.13.js e4x/XML/13.4.4.14.js e4x/XML/13.4.4.15.js e4x/XML/13.4.4.16.js e4x/XML/13.4.4.18.js e4x/XML/13.4.4.19.js e4x/XML/13.4.4.2.js e4x/XML/13.4.4.20.js e4x/XML/13.4.4.21.js e4x/XML/13.4.4.23.js e4x/XML/13.4.4.24.js e4x/XML/13.4.4.25.js e4x/XML/13.4.4.27.js e4x/XML/13.4.4.3.js e4x/XML/13.4.4.30.js e4x/XML/13.4.4.31.js e4x/XML/13.4.4.32-01.js e4x/XML/13.4.4.32.js e4x/XML/13.4.4.33.js e4x/XML/13.4.4.34.js e4x/XML/13.4.4.35.js e4x/XML/13.4.4.36.js e4x/XML/13.4.4.37.js e4x/XML/13.4.4.38.js e4x/XML/13.4.4.39.js e4x/XML/13.4.4.4.js e4x/XML/13.4.4.40.js e4x/XML/13.4.4.5.js e4x/XML/13.4.4.7.js e4x/XML/13.4.4.8.js e4x/XML/regress-291930.js e4x/XML/regress-324688.js e4x/XML/regress-336921.js e4x/XMLList/13.5.1.js e4x/XMLList/13.5.2.js e4x/XMLList/13.5.4.10.js e4x/XMLList/13.5.4.11.js e4x/XMLList/13.5.4.12.js e4x/XMLList/13.5.4.13.js e4x/XMLList/13.5.4.14.js e4x/XMLList/13.5.4.15.js e4x/XMLList/13.5.4.16.js e4x/XMLList/13.5.4.17.js e4x/XMLList/13.5.4.18.js e4x/XMLList/13.5.4.19.js e4x/XMLList/13.5.4.2.js e4x/XMLList/13.5.4.20.js e4x/XMLList/13.5.4.21.js e4x/XMLList/13.5.4.22.js e4x/XMLList/13.5.4.3.js e4x/XMLList/13.5.4.4.js e4x/XMLList/13.5.4.5.js e4x/XMLList/13.5.4.6.js e4x/XMLList/13.5.4.7.js e4x/XMLList/13.5.4.8.js e4x/XMLList/13.5.4.9.js e4x/decompilation/regress-349814.js e4x/decompilation/regress-349815.js e4x/decompilation/regress-349822.js e4x/decompilation/regress-349956.js e4x/decompilation/regress-355474-01.js e4x/decompilation/regress-373678.js e4x/extensions/regress-305335.js e4x/extensions/regress-321547.js e4x/extensions/regress-327534.js e4x/extensions/regress-327897.js e4x/extensions/regress-354145-06.js e4x/extensions/regress-354151-01.js ecma/Array/15.4-1.js ecma/Array/15.4-2.js ecma/Array/15.4.1.1.js ecma/Array/15.4.1.2.js ecma/Array/15.4.1.3.js ecma/Array/15.4.1.js ecma/Array/15.4.2.1-1.js ecma/Array/15.4.2.1-2.js ecma/Array/15.4.2.1-3.js ecma/Array/15.4.2.2-1.js ecma/Array/15.4.2.2-2.js ecma/Array/15.4.2.3.js ecma/Array/15.4.3.2.js ecma/Array/15.4.4.1.js ecma/Array/15.4.4.2.js ecma/Array/15.4.4.3-1.js ecma/Array/15.4.4.4-1.js ecma/Array/15.4.4.4-2.js ecma/Array/15.4.4.5-1.js ecma/Array/15.4.4.5-2.js ecma/Array/15.4.4.js ecma/Array/15.4.5.1-2.js ecma/Array/15.4.5.2-1.js ecma/Array/15.4.5.2-2.js ecma/Boolean/15.6.2.js ecma/Boolean/15.6.3.1-1.js ecma/Boolean/15.6.3.1-2.js ecma/Boolean/15.6.3.1.js ecma/Boolean/15.6.4-1.js ecma/Boolean/15.6.4.1.js ecma/Boolean/15.6.4.2-2.js ecma/Boolean/15.6.4.2-3.js ecma/Boolean/15.6.4.2-4-n.js ecma/Boolean/15.6.4.3-1.js ecma/Boolean/15.6.4.3-2.js ecma/Boolean/15.6.4.3-3.js ecma/Boolean/15.6.4.3-4-n.js ecma/Boolean/15.6.4.3.js ecma/Boolean/15.6.4.js ecma/Date/15.9.1.1-1.js ecma/Date/15.9.1.1-2.js ecma/Date/15.9.1.13-1.js ecma/Date/15.9.2.1.js ecma/Date/15.9.2.2-1.js ecma/Date/15.9.2.2-2.js ecma/Date/15.9.2.2-3.js ecma/Date/15.9.2.2-5.js ecma/Date/15.9.2.2-6.js ecma/Date/15.9.3.1-2.js ecma/Date/15.9.3.1-3.js ecma/Date/15.9.3.1-4.js ecma/Date/15.9.3.1-5.js ecma/Date/15.9.3.2-2.js ecma/Date/15.9.3.2-3.js ecma/Date/15.9.3.2-4.js ecma/Date/15.9.3.2-5.js ecma/Date/15.9.3.8-1.js ecma/Date/15.9.3.8-2.js ecma/Date/15.9.3.8-3.js ecma/Date/15.9.3.8-4.js ecma/Date/15.9.3.8-5.js ecma/Date/15.9.4.2.js ecma/Date/15.9.4.3.js ecma/Date/15.9.5.1.js ecma/Date/15.9.5.10-1.js ecma/Date/15.9.5.10-10.js ecma/Date/15.9.5.10-11.js ecma/Date/15.9.5.10-12.js ecma/Date/15.9.5.10-13.js ecma/Date/15.9.5.10-4.js ecma/Date/15.9.5.10-5.js ecma/Date/15.9.5.10-6.js ecma/Date/15.9.5.10-7.js ecma/Date/15.9.5.10-8.js ecma/Date/15.9.5.10-9.js ecma/Date/15.9.5.11-1.js ecma/Date/15.9.5.11-3.js ecma/Date/15.9.5.11-4.js ecma/Date/15.9.5.11-5.js ecma/Date/15.9.5.11-6.js ecma/Date/15.9.5.11-7.js ecma/Date/15.9.5.12-1.js ecma/Date/15.9.5.12-3.js ecma/Date/15.9.5.12-4.js ecma/Date/15.9.5.12-5.js ecma/Date/15.9.5.12-6.js ecma/Date/15.9.5.12-7.js ecma/Date/15.9.5.12-8.js ecma/Date/15.9.5.13-1.js ecma/Date/15.9.5.13-2.js ecma/Date/15.9.5.13-3.js ecma/Date/15.9.5.13-4.js ecma/Date/15.9.5.13-5.js ecma/Date/15.9.5.13-6.js ecma/Date/15.9.5.13-7.js ecma/Date/15.9.5.13-8.js ecma/Date/15.9.5.14.js ecma/Date/15.9.5.15.js ecma/Date/15.9.5.16.js ecma/Date/15.9.5.17.js ecma/Date/15.9.5.19.js ecma/Date/15.9.5.2-2-n.js ecma/Date/15.9.5.2.js ecma/Date/15.9.5.20.js ecma/Date/15.9.5.21-1.js ecma/Date/15.9.5.21-2.js ecma/Date/15.9.5.21-3.js ecma/Date/15.9.5.21-4.js ecma/Date/15.9.5.21-5.js ecma/Date/15.9.5.21-6.js ecma/Date/15.9.5.21-7.js ecma/Date/15.9.5.21-8.js ecma/Date/15.9.5.22-2.js ecma/Date/15.9.5.22-3.js ecma/Date/15.9.5.22-4.js ecma/Date/15.9.5.22-5.js ecma/Date/15.9.5.22-6.js ecma/Date/15.9.5.22-7.js ecma/Date/15.9.5.22-8.js ecma/Date/15.9.5.23-1.js ecma/Date/15.9.5.23-10.js ecma/Date/15.9.5.23-11.js ecma/Date/15.9.5.23-12.js ecma/Date/15.9.5.23-13.js ecma/Date/15.9.5.23-14.js ecma/Date/15.9.5.23-15.js ecma/Date/15.9.5.23-16.js ecma/Date/15.9.5.23-17.js ecma/Date/15.9.5.23-18.js ecma/Date/15.9.5.23-2.js ecma/Date/15.9.5.23-3-n.js ecma/Date/15.9.5.23-4.js ecma/Date/15.9.5.23-5.js ecma/Date/15.9.5.23-6.js ecma/Date/15.9.5.23-7.js ecma/Date/15.9.5.23-8.js ecma/Date/15.9.5.23-9.js ecma/Date/15.9.5.24-1.js ecma/Date/15.9.5.24-2.js ecma/Date/15.9.5.24-3.js ecma/Date/15.9.5.24-4.js ecma/Date/15.9.5.24-5.js ecma/Date/15.9.5.24-6.js ecma/Date/15.9.5.24-7.js ecma/Date/15.9.5.24-8.js ecma/Date/15.9.5.25-1.js ecma/Date/15.9.5.26-1.js ecma/Date/15.9.5.27-1.js ecma/Date/15.9.5.28-1.js ecma/Date/15.9.5.29-1.js ecma/Date/15.9.5.3-2.js ecma/Date/15.9.5.30-1.js ecma/Date/15.9.5.31-1.js ecma/Date/15.9.5.32-1.js ecma/Date/15.9.5.33-1.js ecma/Date/15.9.5.34-1.js ecma/Date/15.9.5.35-1.js ecma/Date/15.9.5.36-1.js ecma/Date/15.9.5.36-2.js ecma/Date/15.9.5.36-4.js ecma/Date/15.9.5.36-5.js ecma/Date/15.9.5.36-6.js ecma/Date/15.9.5.36-7.js ecma/Date/15.9.5.37-2.js ecma/Date/15.9.5.37-3.js ecma/Date/15.9.5.37-4.js ecma/Date/15.9.5.37-5.js ecma/Date/15.9.5.4-1.js ecma/Date/15.9.5.4-2-n.js ecma/Date/15.9.5.6.js ecma/Date/15.9.5.7.js ecma/Date/15.9.5.8.js ecma/Date/15.9.5.9.js ecma/Date/15.9.5.js ecma/ExecutionContexts/10.1.3-1.js ecma/ExecutionContexts/10.1.3-2.js ecma/ExecutionContexts/10.1.3.js ecma/ExecutionContexts/10.1.4-1.js ecma/ExecutionContexts/10.1.4-10.js ecma/ExecutionContexts/10.1.4-3.js ecma/ExecutionContexts/10.1.4-4.js ecma/ExecutionContexts/10.1.4-5.js ecma/ExecutionContexts/10.1.4-6.js ecma/ExecutionContexts/10.1.4-7.js ecma/ExecutionContexts/10.1.4-8.js ecma/ExecutionContexts/10.1.5-1.js ecma/ExecutionContexts/10.1.5-2.js ecma/ExecutionContexts/10.1.5-3.js ecma/ExecutionContexts/10.1.5-4.js ecma/ExecutionContexts/10.1.8-2.js ecma/ExecutionContexts/10.1.8-3.js ecma/ExecutionContexts/10.2.1.js ecma/ExecutionContexts/10.2.2-1.js ecma/ExecutionContexts/10.2.2-2.js ecma/ExecutionContexts/10.2.3-1.js ecma/ExecutionContexts/10.2.3-2.js ecma/Expressions/11.1.1.js ecma/Expressions/11.10-1.js ecma/Expressions/11.10-2.js ecma/Expressions/11.10-3.js ecma/Expressions/11.12-1.js ecma/Expressions/11.12-2-n.js ecma/Expressions/11.12-3.js ecma/Expressions/11.12-4.js ecma/Expressions/11.13.1.js ecma/Expressions/11.13.2-1.js ecma/Expressions/11.13.2-2.js ecma/Expressions/11.13.2-3.js ecma/Expressions/11.13.2-4.js ecma/Expressions/11.13.2-5.js ecma/Expressions/11.14-1.js ecma/Expressions/11.2.1-1.js ecma/Expressions/11.2.1-2.js ecma/Expressions/11.2.1-3-n.js ecma/Expressions/11.2.1-4-n.js ecma/Expressions/11.2.1-5.js ecma/Expressions/11.2.2-1-n.js ecma/Expressions/11.2.2-1.js ecma/Expressions/11.2.2-10-n.js ecma/Expressions/11.2.2-11.js ecma/Expressions/11.2.2-2-n.js ecma/Expressions/11.2.2-3-n.js ecma/Expressions/11.2.2-4-n.js ecma/Expressions/11.2.2-5-n.js ecma/Expressions/11.2.2-6-n.js ecma/Expressions/11.2.2-7-n.js ecma/Expressions/11.2.2-8-n.js ecma/Expressions/11.2.2-9-n.js ecma/Expressions/11.2.3-1.js ecma/Expressions/11.2.3-2-n.js ecma/Expressions/11.2.3-3-n.js ecma/Expressions/11.2.3-4-n.js ecma/Expressions/11.2.3-5.js ecma/Expressions/11.3.1.js ecma/Expressions/11.3.2.js ecma/Expressions/11.4.2.js ecma/Expressions/11.4.3.js ecma/Expressions/11.4.4.js ecma/Expressions/11.4.5.js ecma/Expressions/11.4.6.js ecma/Expressions/11.4.8.js ecma/Expressions/11.4.9.js ecma/Expressions/11.5.1.js ecma/Expressions/11.5.2.js ecma/Expressions/11.5.3.js ecma/Expressions/11.6.1-1.js ecma/Expressions/11.6.1-2.js ecma/Expressions/11.6.1-3.js ecma/Expressions/11.6.2-1.js ecma/Expressions/11.6.3.js ecma/Expressions/11.7.1.js ecma/Expressions/11.7.2.js ecma/Expressions/11.8.1.js ecma/Expressions/11.8.2.js ecma/Expressions/11.8.3.js ecma/Expressions/11.9.2.js ecma/Expressions/11.9.3.js ecma/FunctionObjects/15.3.1.1-1.js ecma/FunctionObjects/15.3.1.1-2.js ecma/FunctionObjects/15.3.1.1-3.js ecma/FunctionObjects/15.3.2.1-1.js ecma/FunctionObjects/15.3.2.1-2.js ecma/FunctionObjects/15.3.2.1-3.js ecma/FunctionObjects/15.3.3.1-2.js ecma/FunctionObjects/15.3.3.1-3.js ecma/FunctionObjects/15.3.3.1-4.js ecma/FunctionObjects/15.3.3.2.js ecma/FunctionObjects/15.3.4-1.js ecma/FunctionObjects/15.3.4.1.js ecma/FunctionObjects/15.3.4.js ecma/FunctionObjects/15.3.5-1.js ecma/FunctionObjects/15.3.5-2.js ecma/FunctionObjects/15.3.5.1.js ecma/FunctionObjects/15.3.5.3.js ecma/GlobalObject/15.1-1-n.js ecma/GlobalObject/15.1-2-n.js ecma/GlobalObject/15.1.1.1.js ecma/GlobalObject/15.1.1.2.js ecma/GlobalObject/15.1.2.1-2.js ecma/GlobalObject/15.1.2.2-1.js ecma/GlobalObject/15.1.2.2-2.js ecma/GlobalObject/15.1.2.3-1.js ecma/GlobalObject/15.1.2.3-2.js ecma/GlobalObject/15.1.2.4.js ecma/GlobalObject/15.1.2.5-1.js ecma/GlobalObject/15.1.2.5-2.js ecma/GlobalObject/15.1.2.5-3.js ecma/GlobalObject/15.1.2.7.js ecma/LexicalConventions/7.1-1.js ecma/LexicalConventions/7.1-2.js ecma/LexicalConventions/7.1-3.js ecma/LexicalConventions/7.2-1.js ecma/LexicalConventions/7.2-2-n.js ecma/LexicalConventions/7.2-3-n.js ecma/LexicalConventions/7.2-4-n.js ecma/LexicalConventions/7.2-5-n.js ecma/LexicalConventions/7.2-6.js ecma/LexicalConventions/7.3-1.js ecma/LexicalConventions/7.3-10.js ecma/LexicalConventions/7.3-11.js ecma/LexicalConventions/7.3-12.js ecma/LexicalConventions/7.3-13-n.js ecma/LexicalConventions/7.3-2.js ecma/LexicalConventions/7.3-3.js ecma/LexicalConventions/7.3-4.js ecma/LexicalConventions/7.3-5.js ecma/LexicalConventions/7.3-6.js ecma/LexicalConventions/7.3-8.js ecma/LexicalConventions/7.3-9.js ecma/LexicalConventions/7.4.1-1-n.js ecma/LexicalConventions/7.4.1-2-n.js ecma/LexicalConventions/7.4.1-3-n.js ecma/LexicalConventions/7.4.2-1-n.js ecma/LexicalConventions/7.4.2-10-n.js ecma/LexicalConventions/7.4.2-11-n.js ecma/LexicalConventions/7.4.2-12-n.js ecma/LexicalConventions/7.4.2-13-n.js ecma/LexicalConventions/7.4.2-14-n.js ecma/LexicalConventions/7.4.2-15-n.js ecma/LexicalConventions/7.4.2-16-n.js ecma/LexicalConventions/7.4.2-2-n.js ecma/LexicalConventions/7.4.2-3-n.js ecma/LexicalConventions/7.4.2-4-n.js ecma/LexicalConventions/7.4.2-5-n.js ecma/LexicalConventions/7.4.2-6-n.js ecma/LexicalConventions/7.4.2-7-n.js ecma/LexicalConventions/7.4.2-8-n.js ecma/LexicalConventions/7.4.3-1-n.js ecma/LexicalConventions/7.4.3-10-n.js ecma/LexicalConventions/7.4.3-11-n.js ecma/LexicalConventions/7.4.3-13-n.js ecma/LexicalConventions/7.4.3-15-n.js ecma/LexicalConventions/7.4.3-16-n.js ecma/LexicalConventions/7.4.3-2-n.js ecma/LexicalConventions/7.4.3-3-n.js ecma/LexicalConventions/7.4.3-4-n.js ecma/LexicalConventions/7.4.3-5-n.js ecma/LexicalConventions/7.4.3-6-n.js ecma/LexicalConventions/7.4.3-7-n.js ecma/LexicalConventions/7.4.3-8-n.js ecma/LexicalConventions/7.4.3-9-n.js ecma/LexicalConventions/7.5-1.js ecma/LexicalConventions/7.5-10-n.js ecma/LexicalConventions/7.5-2-n.js ecma/LexicalConventions/7.5-3-n.js ecma/LexicalConventions/7.5-4-n.js ecma/LexicalConventions/7.5-5-n.js ecma/LexicalConventions/7.5-6.js ecma/LexicalConventions/7.5-7.js ecma/LexicalConventions/7.5-8-n.js ecma/LexicalConventions/7.5-9-n.js ecma/LexicalConventions/7.6.js ecma/LexicalConventions/7.7.1.js ecma/LexicalConventions/7.7.2.js ecma/LexicalConventions/7.7.3-1.js ecma/LexicalConventions/7.7.3-2.js ecma/LexicalConventions/7.7.3.js ecma/LexicalConventions/7.7.4.js ecma/LexicalConventions/7.8.2-n.js ecma/Math/15.8-2-n.js ecma/Math/15.8-3-n.js ecma/Math/15.8.1.1-1.js ecma/Math/15.8.1.1-2.js ecma/Math/15.8.1.2-1.js ecma/Math/15.8.1.3-1.js ecma/Math/15.8.1.3-2.js ecma/Math/15.8.1.4-1.js ecma/Math/15.8.1.4-2.js ecma/Math/15.8.1.5-1.js ecma/Math/15.8.1.5-2.js ecma/Math/15.8.1.6-1.js ecma/Math/15.8.1.6-2.js ecma/Math/15.8.1.7-1.js ecma/Math/15.8.1.7-2.js ecma/Math/15.8.1.8-1.js ecma/Math/15.8.1.8-2.js ecma/Math/15.8.1.8-3.js ecma/Math/15.8.2.1.js ecma/Math/15.8.2.10.js ecma/Math/15.8.2.12.js ecma/Math/15.8.2.13.js ecma/Math/15.8.2.14.js ecma/Math/15.8.2.15.js ecma/Math/15.8.2.16.js ecma/Math/15.8.2.17.js ecma/Math/15.8.2.18.js ecma/Math/15.8.2.2.js ecma/Math/15.8.2.3.js ecma/Math/15.8.2.4.js ecma/Math/15.8.2.5.js ecma/Math/15.8.2.6.js ecma/Math/15.8.2.7.js ecma/Math/15.8.2.8.js ecma/Math/15.8.2.9.js ecma/Number/15.7.2.js ecma/Number/15.7.3.1-1.js ecma/Number/15.7.3.1-2.js ecma/Number/15.7.3.1-3.js ecma/Number/15.7.3.2-1.js ecma/Number/15.7.3.2-2.js ecma/Number/15.7.3.2-3.js ecma/Number/15.7.3.3-1.js ecma/Number/15.7.3.3-2.js ecma/Number/15.7.3.3-3.js ecma/Number/15.7.3.4-1.js ecma/Number/15.7.3.4-2.js ecma/Number/15.7.3.4-3.js ecma/Number/15.7.3.4-4.js ecma/Number/15.7.3.5-1.js ecma/Number/15.7.3.5-2.js ecma/Number/15.7.3.5-3.js ecma/Number/15.7.3.5-4.js ecma/Number/15.7.3.6-1.js ecma/Number/15.7.3.6-4.js ecma/Number/15.7.3.js ecma/Number/15.7.4-1.js ecma/Number/15.7.4.1.js ecma/Number/15.7.4.2-1.js ecma/Number/15.7.4.2-2-n.js ecma/Number/15.7.4.2-3-n.js ecma/Number/15.7.4.2-4.js ecma/Number/15.7.4.3-1.js ecma/Number/15.7.4.3-2.js ecma/ObjectObjects/15.2.1.2.js ecma/ObjectObjects/15.2.2.1.js ecma/ObjectObjects/15.2.2.2.js ecma/ObjectObjects/15.2.3.1-1.js ecma/ObjectObjects/15.2.3.1-2.js ecma/ObjectObjects/15.2.3.1-3.js ecma/ObjectObjects/15.2.3.1-4.js ecma/ObjectObjects/15.2.3.js ecma/ObjectObjects/15.2.4.1.js ecma/ObjectObjects/15.2.4.2.js ecma/ObjectObjects/15.2.4.3.js ecma/SourceText/6-1.js ecma/SourceText/6-2.js ecma/Statements/12.10-1.js ecma/Statements/12.10.js ecma/Statements/12.5-1.js ecma/Statements/12.5-2.js ecma/Statements/12.6.2-1.js ecma/Statements/12.6.2-2.js ecma/Statements/12.6.2-4.js ecma/Statements/12.6.2-5.js ecma/Statements/12.6.2-6.js ecma/Statements/12.6.2-7.js ecma/Statements/12.6.2-8.js ecma/Statements/12.6.2-9-n.js ecma/Statements/12.6.3-1.js ecma/Statements/12.6.3-10.js ecma/Statements/12.6.3-11.js ecma/Statements/12.6.3-12.js ecma/Statements/12.6.3-19.js ecma/Statements/12.6.3-2.js ecma/Statements/12.6.3-3.js ecma/Statements/12.6.3-4.js ecma/Statements/12.6.3-5-n.js ecma/Statements/12.6.3-6-n.js ecma/Statements/12.6.3-7-n.js ecma/Statements/12.6.3-9-n.js ecma/Statements/12.7-1-n.js ecma/Statements/12.8-1-n.js ecma/Statements/12.9-1-n.js ecma/String/15.5.1.js ecma/String/15.5.2.js ecma/String/15.5.3.1-1.js ecma/String/15.5.3.1-2.js ecma/String/15.5.3.1-3.js ecma/String/15.5.3.1-4.js ecma/String/15.5.3.2-1.js ecma/String/15.5.3.2-2.js ecma/String/15.5.3.2-3.js ecma/String/15.5.3.js ecma/String/15.5.4.1.js ecma/String/15.5.4.10-1.js ecma/String/15.5.4.11-1.js ecma/String/15.5.4.11-3.js ecma/String/15.5.4.11-4.js ecma/String/15.5.4.11-6.js ecma/String/15.5.4.12-2.js ecma/String/15.5.4.12-3.js ecma/String/15.5.4.2-1.js ecma/String/15.5.4.2-2-n.js ecma/String/15.5.4.2-3.js ecma/String/15.5.4.2.js ecma/String/15.5.4.3-1.js ecma/String/15.5.4.3-2.js ecma/String/15.5.4.3-3-n.js ecma/String/15.5.4.4-1.js ecma/String/15.5.4.4-2.js ecma/String/15.5.4.4-3.js ecma/String/15.5.4.4-4.js ecma/String/15.5.4.5-1.js ecma/String/15.5.4.5-2.js ecma/String/15.5.4.5-3.js ecma/String/15.5.4.5-4.js ecma/String/15.5.4.5-5.js ecma/String/15.5.4.6-1.js ecma/String/15.5.4.7-2.js ecma/String/15.5.4.8-1.js ecma/String/15.5.4.8-3.js ecma/String/15.5.4.9-1.js ecma/String/15.5.4.js ecma/String/15.5.5.1.js ecma/TypeConversion/9.2.js ecma/TypeConversion/9.3-1.js ecma/TypeConversion/9.3.1-1.js ecma/TypeConversion/9.3.1-2.js ecma/TypeConversion/9.3.1-3.js ecma/TypeConversion/9.3.js ecma/TypeConversion/9.4-1.js ecma/TypeConversion/9.4-2.js ecma/TypeConversion/9.5-2.js ecma/TypeConversion/9.6.js ecma/TypeConversion/9.7.js ecma/TypeConversion/9.8.1.js ecma/TypeConversion/9.9-1.js ecma/Types/8.1.js ecma/Types/8.4.js ecma/Types/8.6.2.1-1.js ecma/extensions/10.1.4-9.js ecma/extensions/10.1.6.js ecma/extensions/10.1.8-1.js ecma/extensions/11.6.1-1.js ecma/extensions/11.6.1-2.js ecma/extensions/11.6.1-3.js ecma/extensions/11.6.2-1.js ecma/extensions/15-2.js ecma/extensions/15.1.2.1-1.js ecma/extensions/15.2.1.1.js ecma/extensions/15.2.3-1.js ecma/extensions/15.2.4.js ecma/extensions/15.3.1.1-2.js ecma/extensions/15.3.2.1-1.js ecma/extensions/15.3.2.1-2.js ecma/extensions/15.4.3.js ecma/extensions/15.5.3.js ecma/extensions/15.5.4.2.js ecma/extensions/15.5.4.4-4.js ecma/extensions/15.5.4.5-6.js ecma/extensions/15.5.4.7-3.js ecma/extensions/15.6.3.1-5.js ecma/extensions/15.6.3.js ecma/extensions/15.6.4-2.js ecma/extensions/15.7.3.js ecma/extensions/15.7.4.js ecma/extensions/15.8-1.js ecma/extensions/15.9.5.js ecma/extensions/8.6.2.1-1.js ecma/extensions/9.9-1.js ecma/jsref.js ecma_2/Exceptions/boolean-001.js ecma_2/Exceptions/date-001.js ecma_2/Exceptions/date-002.js ecma_2/Exceptions/date-004.js ecma_2/Exceptions/exception-001.js ecma_2/Exceptions/exception-002.js ecma_2/Exceptions/exception-004.js ecma_2/Exceptions/exception-005.js ecma_2/Exceptions/exception-006.js ecma_2/Exceptions/exception-007.js ecma_2/Exceptions/exception-008.js ecma_2/Exceptions/exception-009.js ecma_2/Exceptions/exception-010-n.js ecma_2/Exceptions/exception-011-n.js ecma_2/Exceptions/expression-002.js ecma_2/Exceptions/expression-004.js ecma_2/Exceptions/expression-005.js ecma_2/Exceptions/expression-006.js ecma_2/Exceptions/expression-007.js ecma_2/Exceptions/expression-008.js ecma_2/Exceptions/expression-009.js ecma_2/Exceptions/expression-010.js ecma_2/Exceptions/expression-011.js ecma_2/Exceptions/expression-012.js ecma_2/Exceptions/expression-013.js ecma_2/Exceptions/expression-014.js ecma_2/Exceptions/expression-015.js ecma_2/Exceptions/expression-016.js ecma_2/Exceptions/expression-017.js ecma_2/Exceptions/global-001.js ecma_2/Exceptions/global-002.js ecma_2/Exceptions/lexical-001.js ecma_2/Exceptions/lexical-002.js ecma_2/Exceptions/lexical-003.js ecma_2/Exceptions/lexical-004.js ecma_2/Exceptions/lexical-005.js ecma_2/Exceptions/lexical-006.js ecma_2/Exceptions/lexical-007.js ecma_2/Exceptions/lexical-009.js ecma_2/Exceptions/lexical-010.js ecma_2/Exceptions/lexical-011.js ecma_2/Exceptions/lexical-012.js ecma_2/Exceptions/lexical-013.js ecma_2/Exceptions/lexical-014.js ecma_2/Exceptions/lexical-015.js ecma_2/Exceptions/lexical-016.js ecma_2/Exceptions/lexical-017.js ecma_2/Exceptions/lexical-018.js ecma_2/Exceptions/lexical-019.js ecma_2/Exceptions/lexical-020.js ecma_2/Exceptions/lexical-022.js ecma_2/Exceptions/lexical-023.js ecma_2/Exceptions/lexical-024.js ecma_2/Exceptions/lexical-025.js ecma_2/Exceptions/lexical-026.js ecma_2/Exceptions/lexical-027.js ecma_2/Exceptions/lexical-028.js ecma_2/Exceptions/lexical-029.js ecma_2/Exceptions/lexical-030.js ecma_2/Exceptions/lexical-031.js ecma_2/Exceptions/lexical-032.js ecma_2/Exceptions/lexical-033.js ecma_2/Exceptions/lexical-034.js ecma_2/Exceptions/lexical-035.js ecma_2/Exceptions/lexical-036.js ecma_2/Exceptions/lexical-037.js ecma_2/Exceptions/lexical-038.js ecma_2/Exceptions/lexical-039.js ecma_2/Exceptions/lexical-040.js ecma_2/Exceptions/lexical-041.js ecma_2/Exceptions/lexical-042.js ecma_2/Exceptions/lexical-047.js ecma_2/Exceptions/lexical-048.js ecma_2/Exceptions/lexical-049.js ecma_2/Exceptions/lexical-050.js ecma_2/Exceptions/lexical-051.js ecma_2/Exceptions/lexical-053.js ecma_2/Exceptions/lexical-054.js ecma_2/Exceptions/number-002.js ecma_2/Exceptions/number-003.js ecma_2/Exceptions/statement-001.js ecma_2/Exceptions/statement-002.js ecma_2/Exceptions/statement-003.js ecma_2/Exceptions/statement-004.js ecma_2/Exceptions/statement-005.js ecma_2/Exceptions/statement-006.js ecma_2/Exceptions/statement-007.js ecma_2/Exceptions/statement-008.js ecma_2/Exceptions/string-001.js ecma_2/Exceptions/string-002.js ecma_2/Expressions/StrictEquality-001.js ecma_2/FunctionObjects/apply-001-n.js ecma_2/FunctionObjects/call-1.js ecma_2/LexicalConventions/keywords-001.js ecma_2/LexicalConventions/regexp-literals-001.js ecma_2/LexicalConventions/regexp-literals-002.js ecma_2/RegExp/constructor-001.js ecma_2/RegExp/exec-002.js ecma_2/RegExp/function-001.js ecma_2/RegExp/hex-001.js ecma_2/RegExp/multiline-001.js ecma_2/RegExp/octal-001.js ecma_2/RegExp/octal-002.js ecma_2/RegExp/octal-003.js ecma_2/RegExp/properties-001.js ecma_2/RegExp/properties-002.js ecma_2/RegExp/regress-001.js ecma_2/RegExp/unicode-001.js ecma_2/Statements/dowhile-001.js ecma_2/Statements/dowhile-002.js ecma_2/Statements/dowhile-003.js ecma_2/Statements/dowhile-004.js ecma_2/Statements/dowhile-005.js ecma_2/Statements/dowhile-006.js ecma_2/Statements/dowhile-007.js ecma_2/Statements/forin-001.js ecma_2/Statements/forin-002.js ecma_2/Statements/if-001.js ecma_2/Statements/label-001.js ecma_2/Statements/label-002.js ecma_2/Statements/switch-002.js ecma_2/Statements/switch-003.js ecma_2/Statements/switch-004.js ecma_2/Statements/try-001.js ecma_2/Statements/try-003.js ecma_2/Statements/try-004.js ecma_2/Statements/try-005.js ecma_2/Statements/try-007.js ecma_2/Statements/try-008.js ecma_2/Statements/try-009.js ecma_2/Statements/try-012.js ecma_2/Statements/while-001.js ecma_2/Statements/while-002.js ecma_2/Statements/while-003.js ecma_2/Statements/while-004.js ecma_2/String/match-001.js ecma_2/String/match-002.js ecma_2/String/match-003.js ecma_2/String/match-004.js ecma_2/String/split-001.js ecma_2/String/split-002.js ecma_2/String/split-003.js ecma_2/extensions/constructor-001.js ecma_2/extensions/function-001.js ecma_2/extensions/instanceof-001.js ecma_2/extensions/instanceof-002.js ecma_2/extensions/instanceof-006.js ecma_2/instanceof/instanceof-001.js ecma_2/instanceof/instanceof-002.js ecma_2/instanceof/regress-7635.js ecma_2/jsref.js ecma_3/Array/15.4.4.11-01.js ecma_3/Array/15.4.4.3-1.js ecma_3/Array/15.4.4.4-001.js ecma_3/Array/regress-101488.js ecma_3/Array/regress-130451.js ecma_3/Array/regress-322135-01.js ecma_3/Date/15.9.4.3.js ecma_3/Date/15.9.5.3.js ecma_3/Date/15.9.5.4.js ecma_3/Date/15.9.5.6.js ecma_3/Date/15.9.5.7.js ecma_3/Exceptions/15.11.1.1.js ecma_3/Exceptions/15.11.4.4-1.js ecma_3/Exceptions/15.11.7.6-001.js ecma_3/Exceptions/15.11.7.6-002.js ecma_3/Exceptions/15.11.7.6-003.js ecma_3/Exceptions/binding-001.js ecma_3/Exceptions/regress-181654.js ecma_3/Exceptions/regress-181914.js ecma_3/Exceptions/regress-95101.js ecma_3/ExecutionContexts/10.1.3-1.js ecma_3/ExecutionContexts/10.1.3-2.js ecma_3/ExecutionContexts/10.1.3.js ecma_3/ExecutionContexts/10.1.4-1.js ecma_3/ExecutionContexts/10.6.1-01.js ecma_3/ExecutionContexts/regress-23346.js ecma_3/Expressions/11.10-01.js ecma_3/Expressions/11.10-03.js ecma_3/Expressions/11.6.1-1.js ecma_3/Expressions/11.7.1-01.js ecma_3/Expressions/11.7.2-01.js ecma_3/Expressions/11.7.3-01.js ecma_3/Expressions/11.9.6-1.js ecma_3/FunExpr/fe-001-n.js ecma_3/FunExpr/fe-001.js ecma_3/FunExpr/fe-002.js ecma_3/Function/15.3.4.3-1.js ecma_3/Function/15.3.4.4-1.js ecma_3/Function/arguments-001.js ecma_3/Function/arguments-002.js ecma_3/Function/call-001.js ecma_3/Function/regress-131964.js ecma_3/Function/regress-137181.js ecma_3/Function/regress-193555.js ecma_3/Function/regress-313570.js ecma_3/Function/regress-49286.js ecma_3/Function/regress-58274.js ecma_3/Function/regress-85880.js ecma_3/Function/regress-94506.js ecma_3/Function/regress-97921.js ecma_3/Function/scope-001.js ecma_3/Function/scope-002.js ecma_3/Number/15.7.4.5-1.js ecma_3/Number/15.7.4.6-1.js ecma_3/Number/15.7.4.7-1.js ecma_3/Number/15.7.4.7-2.js ecma_3/NumberFormatting/tostring-001.js ecma_3/Object/8.6.2.6-001.js ecma_3/Object/class-001.js ecma_3/Object/class-002.js ecma_3/Object/class-003.js ecma_3/Object/class-004.js ecma_3/Object/class-005.js ecma_3/Object/regress-361274.js ecma_3/Object/regress-385393-07.js ecma_3/Object/regress-72773.js ecma_3/Object/regress-79129-001.js ecma_3/Operators/11.13.1-001.js ecma_3/Operators/11.13.1-002.js ecma_3/Operators/11.4.1-001.js ecma_3/RegExp/15.10.2-1.js ecma_3/RegExp/15.10.2.12.js ecma_3/RegExp/15.10.3.1-1.js ecma_3/RegExp/15.10.3.1-2.js ecma_3/RegExp/15.10.4.1-1.js ecma_3/RegExp/15.10.4.1-2.js ecma_3/RegExp/15.10.4.1-3.js ecma_3/RegExp/15.10.4.1-4.js ecma_3/RegExp/15.10.4.1-5-n.js ecma_3/RegExp/15.10.6.2-1.js ecma_3/RegExp/15.10.6.2-2.js ecma_3/RegExp/octal-001.js ecma_3/RegExp/octal-002.js ecma_3/RegExp/perlstress-001.js ecma_3/RegExp/perlstress-002.js ecma_3/RegExp/regress-100199.js ecma_3/RegExp/regress-105972.js ecma_3/RegExp/regress-119909.js ecma_3/RegExp/regress-122076.js ecma_3/RegExp/regress-123437.js ecma_3/RegExp/regress-165353.js ecma_3/RegExp/regress-169497.js ecma_3/RegExp/regress-169534.js ecma_3/RegExp/regress-187133.js ecma_3/RegExp/regress-191479.js ecma_3/RegExp/regress-202564.js ecma_3/RegExp/regress-209067.js ecma_3/RegExp/regress-209919.js ecma_3/RegExp/regress-216591.js ecma_3/RegExp/regress-220367-001.js ecma_3/RegExp/regress-223273.js ecma_3/RegExp/regress-223535.js ecma_3/RegExp/regress-224676.js ecma_3/RegExp/regress-225289.js ecma_3/RegExp/regress-225343.js ecma_3/RegExp/regress-24712.js ecma_3/RegExp/regress-28686.js ecma_3/RegExp/regress-309840.js ecma_3/RegExp/regress-312351.js ecma_3/RegExp/regress-31316.js ecma_3/RegExp/regress-346090.js ecma_3/RegExp/regress-375715-02.js ecma_3/RegExp/regress-375715-03.js ecma_3/RegExp/regress-57572.js ecma_3/RegExp/regress-57631.js ecma_3/RegExp/regress-67773.js ecma_3/RegExp/regress-76683.js ecma_3/RegExp/regress-78156.js ecma_3/RegExp/regress-85721.js ecma_3/RegExp/regress-87231.js ecma_3/RegExp/regress-98306.js ecma_3/Statements/12.6.3.js ecma_3/Statements/regress-131348.js ecma_3/Statements/regress-157509.js ecma_3/Statements/regress-194364.js ecma_3/Statements/regress-226517.js ecma_3/Statements/regress-302439.js ecma_3/Statements/regress-324650.js ecma_3/Statements/regress-74474-001.js ecma_3/Statements/regress-74474-002.js ecma_3/Statements/regress-74474-003.js ecma_3/Statements/regress-83532-001.js ecma_3/Statements/regress-83532-002.js ecma_3/Statements/switch-001.js ecma_3/String/regress-104375.js ecma_3/String/regress-189898.js ecma_3/String/regress-313567.js ecma_3/String/regress-83293.js ecma_3/Unicode/uc-001-n.js ecma_3/Unicode/uc-001.js ecma_3/Unicode/uc-002-n.js ecma_3/Unicode/uc-002.js ecma_3/Unicode/uc-003.js ecma_3/Unicode/uc-004.js ecma_3/Unicode/uc-005.js ecma_3/extensions/regress-103087.js ecma_3/extensions/regress-188206-01.js ecma_3/extensions/regress-188206-02.js ecma_3/extensions/regress-220367-002.js ecma_3/extensions/regress-228087.js ecma_3/extensions/regress-320854.js ecma_3/extensions/regress-327170.js ecma_3/extensions/regress-385393-03.js js-test-driver-begin.js js-test-driver-end.js js1_1/jsref.js js1_2/Array/array_split_1.js js1_2/Array/general1.js js1_2/Array/general2.js js1_2/Array/slice.js js1_2/Array/splice1.js js1_2/Array/splice2.js js1_2/Array/tostring_1.js js1_2/Array/tostring_2.js js1_2/Objects/toString-001.js js1_2/String/charCodeAt.js js1_2/String/concat.js js1_2/String/match.js js1_2/String/slice.js js1_2/function/Number.js js1_2/function/String.js js1_2/function/definition-1.js js1_2/function/length.js js1_2/function/nesting-1.js js1_2/function/nesting.js js1_2/function/regexparg-2-n.js js1_2/jsref.js js1_2/operator/strictEquality.js js1_2/regexp/RegExp_dollar_number.js js1_2/regexp/RegExp_input.js js1_2/regexp/RegExp_input_as_array.js js1_2/regexp/RegExp_lastIndex.js js1_2/regexp/RegExp_lastMatch.js js1_2/regexp/RegExp_lastMatch_as_array.js js1_2/regexp/RegExp_lastParen.js js1_2/regexp/RegExp_lastParen_as_array.js js1_2/regexp/RegExp_leftContext.js js1_2/regexp/RegExp_leftContext_as_array.js js1_2/regexp/RegExp_multiline.js js1_2/regexp/RegExp_multiline_as_array.js js1_2/regexp/RegExp_object.js js1_2/regexp/RegExp_rightContext.js js1_2/regexp/RegExp_rightContext_as_array.js js1_2/regexp/alphanumeric.js js1_2/regexp/asterisk.js js1_2/regexp/backslash.js js1_2/regexp/backspace.js js1_2/regexp/beginLine.js js1_2/regexp/character_class.js js1_2/regexp/compile.js js1_2/regexp/control_characters.js js1_2/regexp/digit.js js1_2/regexp/dot.js js1_2/regexp/endLine.js js1_2/regexp/everything.js js1_2/regexp/exec.js js1_2/regexp/flags.js js1_2/regexp/global.js js1_2/regexp/hexadecimal.js js1_2/regexp/ignoreCase.js js1_2/regexp/interval.js js1_2/regexp/octal.js js1_2/regexp/parentheses.js js1_2/regexp/regress-6359.js js1_2/regexp/regress-9141.js js1_2/regexp/simple_form.js js1_2/regexp/source.js js1_2/regexp/special_characters.js js1_2/regexp/string_replace.js js1_2/regexp/string_search.js js1_2/regexp/string_split.js js1_2/regexp/test.js js1_2/regexp/toString.js js1_2/regexp/vertical_bar.js js1_2/regexp/whitespace.js js1_2/regexp/word_boundary.js js1_2/regress/regress-144834.js js1_2/regress/regress-7703.js js1_2/statements/break.js js1_2/statements/do_while.js js1_2/statements/switch.js js1_2/statements/switch2.js js1_2/version120/boolean-001.js js1_3/Boolean/boolean-001.js js1_3/Script/delete-001.js js1_3/Script/function-002.js js1_3/Script/new-001.js js1_3/Script/switch-001.js js1_3/extensions/proto_10.js js1_3/extensions/proto_2.js js1_3/extensions/proto_5.js js1_3/inherit/proto_1.js js1_3/inherit/proto_10.js js1_3/inherit/proto_11.js js1_3/inherit/proto_12.js js1_3/inherit/proto_3.js js1_3/inherit/proto_4.js js1_3/inherit/proto_6.js js1_3/inherit/proto_7.js js1_3/inherit/proto_8.js js1_3/inherit/proto_9.js js1_3/jsref.js js1_3/regress/delete-001.js js1_3/regress/function-002.js js1_3/regress/new-001.js js1_3/regress/switch-001.js js1_4/Eval/eval-001.js js1_4/Eval/eval-002.js js1_4/Eval/eval-003.js js1_4/Functions/function-001.js js1_4/Regress/date-001-n.js js1_4/Regress/function-001.js js1_4/Regress/function-002.js js1_4/Regress/function-003.js js1_4/Regress/function-004-n.js js1_4/Regress/regress-7224.js js1_4/Regress/toString-001-n.js js1_4/jsref.js js1_5/Array/11.1.4.js js1_5/Array/array-001.js js1_5/Array/regress-101964.js js1_5/Array/regress-107138.js js1_5/Array/regress-108440.js js1_5/Array/regress-154338.js js1_5/Array/regress-178722.js js1_5/Array/regress-255555.js js1_5/Array/regress-299644.js js1_5/Array/regress-300858.js js1_5/Array/regress-310351.js js1_5/Array/regress-311515.js js1_5/Array/regress-313153.js js1_5/Array/regress-315509-01.js js1_5/Array/regress-345961.js js1_5/Array/regress-348810.js js1_5/Array/regress-350256-01.js js1_5/Array/regress-350256-02.js js1_5/Array/regress-360681-01.js js1_5/Array/regress-360681-02.js js1_5/Array/regress-364104.js js1_5/Array/regress-94257.js js1_5/Date/regress-188211.js js1_5/Date/regress-301738-01.js js1_5/Date/regress-309925-01.js js1_5/Date/regress-346027.js js1_5/Exceptions/catchguard-002-n.js js1_5/Exceptions/catchguard-003-n.js js1_5/Exceptions/regress-123002.js js1_5/Exceptions/regress-232182.js js1_5/Exceptions/regress-257751.js js1_5/Exceptions/regress-273931.js js1_5/Exceptions/regress-347674.js js1_5/Exceptions/regress-350837.js js1_5/Expressions/regress-192288.js js1_5/Expressions/regress-96526-argsub.js js1_5/Expressions/regress-96526-noargsub.js js1_5/Function/10.1.6-01.js js1_5/Function/10.1.6.js js1_5/Function/15.3.4.4.js js1_5/Function/regress-123371.js js1_5/Function/regress-178389.js js1_5/Function/regress-292215.js js1_5/Function/regress-344052.js js1_5/GC/regress-104584.js js1_5/GC/regress-203278-2.js js1_5/GC/regress-203278-3.js js1_5/GC/regress-278725.js js1_5/GC/regress-306788.js js1_5/GC/regress-313276.js js1_5/GC/regress-313479.js js1_5/GC/regress-316885-02.js js1_5/GC/regress-316885-03.js js1_5/GC/regress-319980-01.js js1_5/GC/regress-324278.js js1_5/GC/regress-331719.js js1_5/GC/regress-341877-01.js js1_5/GC/regress-341877-02.js js1_5/GC/regress-352606.js js1_5/GC/regress-383269-01.js js1_5/GC/regress-383269-02.js js1_5/GC/regress-390078.js js1_5/GetSet/regress-375976.js js1_5/LexicalConventions/lexical-001.js js1_5/LexicalConventions/regress-177314.js js1_5/Object/regress-137000.js js1_5/Object/regress-192105.js js1_5/Object/regress-338709.js js1_5/Object/regress-382503.js js1_5/Object/regress-382532.js js1_5/Object/regress-90596-003.js js1_5/Regress/regress-104077.js js1_5/Regress/regress-110286.js js1_5/Regress/regress-111557.js js1_5/Regress/regress-114491.js js1_5/Regress/regress-114493.js js1_5/Regress/regress-115436.js js1_5/Regress/regress-116228.js js1_5/Regress/regress-118849.js js1_5/Regress/regress-127243.js js1_5/Regress/regress-127557.js js1_5/Regress/regress-131510-001.js js1_5/Regress/regress-140852.js js1_5/Regress/regress-140974.js js1_5/Regress/regress-146596.js js1_5/Regress/regress-152646.js js1_5/Regress/regress-155081-2.js js1_5/Regress/regress-155081.js js1_5/Regress/regress-159334.js js1_5/Regress/regress-162392.js js1_5/Regress/regress-165201.js js1_5/Regress/regress-167328.js js1_5/Regress/regress-167658.js js1_5/Regress/regress-168347.js js1_5/Regress/regress-170193.js js1_5/Regress/regress-172699.js js1_5/Regress/regress-174709.js js1_5/Regress/regress-176125.js js1_5/Regress/regress-185165.js js1_5/Regress/regress-191633.js js1_5/Regress/regress-192414.js js1_5/Regress/regress-193418.js js1_5/Regress/regress-203402.js js1_5/Regress/regress-203841.js js1_5/Regress/regress-204210.js js1_5/Regress/regress-210682.js js1_5/Regress/regress-211590.js js1_5/Regress/regress-214761.js js1_5/Regress/regress-216320.js js1_5/Regress/regress-224956.js js1_5/Regress/regress-229006.js js1_5/Regress/regress-230216-1.js js1_5/Regress/regress-230216-2.js js1_5/Regress/regress-230216-3.js js1_5/Regress/regress-233483-2.js js1_5/Regress/regress-233483.js js1_5/Regress/regress-238881.js js1_5/Regress/regress-238945.js js1_5/Regress/regress-243174.js js1_5/Regress/regress-243389-n.js js1_5/Regress/regress-243869.js js1_5/Regress/regress-244470.js js1_5/Regress/regress-244619.js js1_5/Regress/regress-245113.js js1_5/Regress/regress-245308.js js1_5/Regress/regress-246911.js js1_5/Regress/regress-246964.js js1_5/Regress/regress-253150.js js1_5/Regress/regress-254296.js js1_5/Regress/regress-254974.js js1_5/Regress/regress-256501.js js1_5/Regress/regress-256617.js js1_5/Regress/regress-256798.js js1_5/Regress/regress-260541.js js1_5/Regress/regress-261887.js js1_5/Regress/regress-274888.js js1_5/Regress/regress-275378.js js1_5/Regress/regress-276103.js js1_5/Regress/regress-278873.js js1_5/Regress/regress-280769-3.js js1_5/Regress/regress-280769-4.js js1_5/Regress/regress-281487.js js1_5/Regress/regress-281930.js js1_5/Regress/regress-283477.js js1_5/Regress/regress-286216.js js1_5/Regress/regress-288688.js js1_5/Regress/regress-289094.js js1_5/Regress/regress-290656.js js1_5/Regress/regress-294191.js js1_5/Regress/regress-294195-01.js js1_5/Regress/regress-294195-02.js js1_5/Regress/regress-295052.js js1_5/Regress/regress-295666.js js1_5/Regress/regress-306633.js js1_5/Regress/regress-306727.js js1_5/Regress/regress-306794.js js1_5/Regress/regress-308566.js js1_5/Regress/regress-310295.js js1_5/Regress/regress-310607.js js1_5/Regress/regress-310993.js js1_5/Regress/regress-311071.js js1_5/Regress/regress-311629.js js1_5/Regress/regress-312260.js js1_5/Regress/regress-31255.js js1_5/Regress/regress-314401.js js1_5/Regress/regress-315990.js js1_5/Regress/regress-317476.js js1_5/Regress/regress-317714-02.js js1_5/Regress/regress-319384.js js1_5/Regress/regress-320032.js js1_5/Regress/regress-321757.js js1_5/Regress/regress-321874.js js1_5/Regress/regress-322430.js js1_5/Regress/regress-326467.js js1_5/Regress/regress-328012.js js1_5/Regress/regress-328897.js js1_5/Regress/regress-329383.js js1_5/Regress/regress-330951.js js1_5/Regress/regress-334807-01.js js1_5/Regress/regress-334807-03.js js1_5/Regress/regress-334807-05.js js1_5/Regress/regress-334807-06.js js1_5/Regress/regress-338307.js js1_5/Regress/regress-340369.js js1_5/Regress/regress-341360.js js1_5/Regress/regress-343966.js js1_5/Regress/regress-344804.js js1_5/Regress/regress-344959.js js1_5/Regress/regress-346801.js js1_5/Regress/regress-349482-01.js js1_5/Regress/regress-349482-02.js js1_5/Regress/regress-349592.js js1_5/Regress/regress-350253.js js1_5/Regress/regress-350312.js js1_5/Regress/regress-350415.js js1_5/Regress/regress-351116.js js1_5/Regress/regress-351515.js js1_5/Regress/regress-352009.js js1_5/Regress/regress-352208.js js1_5/Regress/regress-360969-01.js js1_5/Regress/regress-360969-02.js js1_5/Regress/regress-360969-03.js js1_5/Regress/regress-360969-04.js js1_5/Regress/regress-366468.js js1_5/Regress/regress-367561-01.js js1_5/Regress/regress-379245.js js1_5/Regress/regress-39309.js js1_5/Regress/regress-398609.js js1_5/Regress/regress-406769.js js1_5/Regress/regress-407024.js js1_5/Regress/regress-407323.js js1_5/Regress/regress-407957.js js1_5/Regress/regress-57043.js js1_5/Regress/regress-68498-001.js js1_5/Regress/regress-68498-002.js js1_5/Regress/regress-68498-004.js js1_5/Regress/regress-69607.js js1_5/Regress/regress-71107.js js1_5/Regress/regress-76054.js js1_5/Regress/regress-80981.js js1_5/Regress/regress-82306.js js1_5/Regress/regress-90445.js js1_5/Regress/regress-96526-001.js js1_5/Regress/regress-96526-003.js js1_5/Scope/regress-154693.js js1_5/Scope/regress-181834.js js1_5/Scope/regress-184107.js js1_5/Scope/regress-185485.js js1_5/Scope/regress-191276.js js1_5/Scope/regress-192226.js js1_5/Scope/regress-202678-001.js js1_5/Scope/regress-202678-002.js js1_5/Scope/regress-208496-001.js js1_5/Scope/regress-208496-002.js js1_5/Scope/regress-220362.js js1_5/Scope/regress-77578-001.js js1_5/Scope/scope-002.js js1_5/Scope/scope-003.js js1_5/String/regress-107771.js js1_5/String/regress-112626.js js1_5/String/regress-179068.js js1_5/String/regress-314890.js js1_5/decompilation/regress-344120.js js1_5/decompilation/regress-349489.js js1_5/decompilation/regress-349663.js js1_5/decompilation/regress-350670.js js1_5/decompilation/regress-351625.js js1_5/decompilation/regress-351626.js js1_5/decompilation/regress-351705.js js1_5/decompilation/regress-352022.js js1_5/decompilation/regress-352073.js js1_5/decompilation/regress-352312.js js1_5/decompilation/regress-352360.js js1_5/decompilation/regress-352873-01.js js1_5/decompilation/regress-352873-02.js js1_5/decompilation/regress-353120.js js1_5/decompilation/regress-354878.js js1_5/decompilation/regress-354910.js js1_5/decompilation/regress-371692.js js1_5/decompilation/regress-373678.js js1_5/decompilation/regress-375639.js js1_5/decompilation/regress-376564.js js1_5/decompilation/regress-383721.js js1_5/decompilation/regress-406555.js js1_5/extensions/catchguard-001.js js1_5/extensions/catchguard-002.js js1_5/extensions/catchguard-003.js js1_5/extensions/getset-004.js js1_5/extensions/getset-005.js js1_5/extensions/getset-006.js js1_5/extensions/no-such-method.js js1_5/extensions/regress-104077.js js1_5/extensions/regress-178722.js js1_5/extensions/regress-220584.js js1_5/extensions/regress-225831.js js1_5/extensions/regress-226078.js js1_5/extensions/regress-226507.js js1_5/extensions/regress-237461.js js1_5/extensions/regress-245795.js js1_5/extensions/regress-255245.js js1_5/extensions/regress-291213.js js1_5/extensions/regress-311161.js js1_5/extensions/regress-311583.js js1_5/extensions/regress-311792-01.js js1_5/extensions/regress-311792-02.js js1_5/extensions/regress-312278.js js1_5/extensions/regress-313500.js js1_5/extensions/regress-313630.js js1_5/extensions/regress-313763.js js1_5/extensions/regress-313803.js js1_5/extensions/regress-313938.js js1_5/extensions/regress-314874.js js1_5/extensions/regress-319683.js js1_5/extensions/regress-322957.js js1_5/extensions/regress-325269.js js1_5/extensions/regress-327608.js js1_5/extensions/regress-328556.js js1_5/extensions/regress-338804-01.js js1_5/extensions/regress-338804-03.js js1_5/extensions/regress-339685.js js1_5/extensions/regress-340199.js js1_5/extensions/regress-341956-02.js js1_5/extensions/regress-341956-03.js js1_5/extensions/regress-346494-01.js js1_5/extensions/regress-347306-02.js js1_5/extensions/regress-350312-01.js js1_5/extensions/regress-350312-02.js js1_5/extensions/regress-350312-03.js js1_5/extensions/regress-351102-01.js js1_5/extensions/regress-351102-02.js js1_5/extensions/regress-351102-06.js js1_5/extensions/regress-351973.js js1_5/extensions/regress-352261.js js1_5/extensions/regress-352281.js js1_5/extensions/regress-354297.js js1_5/extensions/regress-354541-01.js js1_5/extensions/regress-354541-03.js js1_5/extensions/regress-355982.js js1_5/extensions/regress-356402.js js1_5/extensions/regress-363988.js js1_5/extensions/regress-365527.js js1_5/extensions/regress-365692.js js1_5/extensions/regress-366288.js js1_5/extensions/regress-366292.js js1_5/extensions/regress-366396.js js1_5/extensions/regress-367118-01.js js1_5/extensions/regress-367118-02.js js1_5/extensions/regress-367120-01.js js1_5/extensions/regress-367120-02.js js1_5/extensions/regress-367121.js js1_5/extensions/regress-367501-01.js js1_5/extensions/regress-367501-02.js js1_5/extensions/regress-367501-03.js js1_5/extensions/regress-367589.js js1_5/extensions/regress-369404.js js1_5/extensions/regress-374589.js js1_5/extensions/regress-375183.js js1_5/extensions/regress-380889.js js1_5/extensions/regress-385134.js js1_5/extensions/regress-394967.js js1_5/extensions/regress-396326.js js1_5/extensions/regress-407501.js js1_5/extensions/regress-44009.js js1_5/extensions/regress-50447.js js1_5/extensions/regress-90596-001.js js1_5/extensions/regress-90596-002.js js1_5/extensions/regress-96284-001.js js1_5/extensions/regress-96284-002.js js1_5/extensions/scope-001.js js1_6/Array/filter.js js1_6/Array/regress-304828.js js1_6/Array/regress-305002.js js1_6/Array/regress-310425-01.js js1_6/Array/regress-310425-02.js js1_6/Array/regress-320887.js js1_6/Array/regress-352742-01.js js1_6/Array/regress-352742-02.js js1_6/Array/regress-415451.js js1_6/Array/regress-415540.js js1_6/Regress/regress-301574.js js1_6/Regress/regress-311157-01.js js1_6/Regress/regress-311157-02.js js1_6/Regress/regress-314887.js js1_6/Regress/regress-351795.js js1_6/Regress/regress-352271.js js1_6/Regress/regress-378492.js js1_6/decompilation/regress-352084.js js1_6/extensions/regress-385393-08.js js1_7/GC/regress-341675.js js1_7/block/order-of-operation.js js1_7/block/regress-341939.js js1_7/block/regress-344139.js js1_7/block/regress-344370.js js1_7/block/regress-345542.js js1_7/block/regress-348685.js js1_7/block/regress-349283.js js1_7/block/regress-349298.js js1_7/block/regress-349507.js js1_7/block/regress-349653.js js1_7/block/regress-349962.js js1_7/block/regress-350279.js js1_7/block/regress-350730.js js1_7/block/regress-350793-01.js js1_7/block/regress-351497.js js1_7/block/regress-351606.js js1_7/block/regress-352092.js js1_7/block/regress-352185.js js1_7/block/regress-352212.js js1_7/block/regress-352267.js js1_7/block/regress-352616.js js1_7/block/regress-352624.js js1_7/block/regress-352907.js js1_7/block/regress-357754.js js1_7/block/regress-376410.js js1_7/block/regress-396900.js js1_7/block/regress-411279.js js1_7/decompilation/regress-349633.js js1_7/decompilation/regress-350810.js js1_7/decompilation/regress-352015.js js1_7/decompilation/regress-352025.js js1_7/decompilation/regress-352269.js js1_7/decompilation/regress-352272.js js1_7/decompilation/regress-352283.js js1_7/decompilation/regress-352732.js js1_7/decompilation/regress-355635.js js1_7/decompilation/regress-355786.js js1_7/decompilation/regress-375794.js js1_7/decompilation/regress-380506.js js1_7/expressions/destructuring-scope.js js1_7/expressions/regress-346203.js js1_7/expressions/regress-346645-01.js js1_7/expressions/regress-346645-02.js js1_7/expressions/regress-346645-03.js js1_7/expressions/regress-349624.js js1_7/expressions/regress-349818.js js1_7/extensions/basic-Iterator.js js1_7/extensions/basic-for-in.js js1_7/extensions/destructuring-order.js js1_7/extensions/iterator-ctor.js js1_7/extensions/regress-346021.js js1_7/extensions/regress-346642-02.js js1_7/extensions/regress-346773.js js1_7/extensions/regress-349619.js js1_7/extensions/regress-350312.js js1_7/extensions/regress-351070-02.js js1_7/extensions/regress-352797-01.js js1_7/extensions/regress-352885-01.js js1_7/extensions/regress-352885-02.js js1_7/extensions/regress-353214-02.js js1_7/extensions/regress-354499-01.js js1_7/extensions/regress-354499-02.js js1_7/extensions/regress-354945-01.js js1_7/extensions/regress-355052-01.js js1_7/extensions/regress-355052-02.js js1_7/extensions/regress-355052-03.js js1_7/extensions/regress-355410.js js1_7/extensions/regress-355512.js js1_7/extensions/regress-355578.js js1_7/extensions/regress-355583.js js1_7/extensions/regress-363040-01.js js1_7/extensions/regress-363040-02.js js1_7/extensions/regress-366668-01.js js1_7/extensions/regress-366668-02.js js1_7/extensions/regress-387955-01.js js1_7/extensions/regress-392308.js js1_7/extensions/regress-396326.js js1_7/geniter/326466-01.js js1_7/geniter/builtin-Iterator-function.js js1_7/geniter/evens.js js1_7/geniter/fibonacci-matrix-generator.js js1_7/geniter/iterator-toString.js js1_7/geniter/message-value-passing.js js1_7/geniter/multiple-close.js js1_7/geniter/nested-yield.js js1_7/geniter/pi-generator.js js1_7/geniter/regress-345736.js js1_7/geniter/regress-345855.js js1_7/geniter/regress-345879-01.js js1_7/geniter/regress-347593.js js1_7/geniter/regress-349012-02.js js1_7/geniter/regress-349012-03.js js1_7/geniter/regress-349012-04.js js1_7/geniter/regress-349012-05.js js1_7/geniter/regress-349023-01.js js1_7/geniter/regress-349023-02.js js1_7/geniter/regress-349023-03.js js1_7/geniter/regress-349362.js js1_7/geniter/regress-349851.js js1_7/geniter/regress-350621.js js1_7/geniter/regress-350809.js js1_7/geniter/regress-351120.js js1_7/geniter/regress-352197.js js1_7/geniter/regress-352876.js js1_7/geniter/regress-355834.js js1_7/geniter/regress-359062.js js1_7/geniter/regress-366941.js js1_7/geniter/regress-382335.js js1_7/geniter/regress-390918.js js1_7/geniter/send-no-rhs.js js1_7/geniter/sequential-yields.js js1_7/geniter/throw-after-close.js js1_7/geniter/throw-forever.js js1_7/geniter/unreachable-yield.js js1_7/geniter/yield-undefined.js js1_7/iterable/regress-341499.js js1_7/iterable/regress-341510.js js1_7/iterable/regress-341815.js js1_7/iterable/regress-341821.js js1_7/iterable/regress-354750-01.js js1_7/iterable/regress-355025.js js1_7/iterable/regress-355075-01.js js1_7/iterable/regress-355090.js js1_7/iterable/regress-412467.js js1_7/lexical/regress-346642-04.js js1_7/regress/regress-352640-01.js js1_7/regress/regress-352640-02.js js1_7/regress/regress-352640-03.js js1_7/regress/regress-352640-04.js js1_7/regress/regress-352797-02.js js1_7/regress/regress-352870-03.js js1_7/regress/regress-353079.js js1_7/regress/regress-355023.js js1_7/regress/regress-355832-01.js js1_7/regress/regress-361566.js js1_7/regress/regress-369666-01.js js1_7/regress/regress-369666-02.js js1_7/regress/regress-372331.js js1_7/regress/regress-373827-01.js js1_7/regress/regress-373827-02.js js1_7/regress/regress-373828.js js1_7/regress/regress-379442.js js1_7/regress/regress-385393-05.js js1_7/regress/regress-407727-01.js js1_7/regress/regress-407727-02.js js1_7/regress/regress-407957.js js1_7/regress/regress-414553.js lc2/Arrays/array-001.js lc2/Arrays/array-002.js lc2/Arrays/array-003.js lc2/Arrays/array-004.js lc2/Arrays/array-005.js lc2/Arrays/array-006-n.js lc2/Arrays/array-007-n.js lc2/Arrays/array-008-n.js lc2/Classes/class-001.js lc2/Classes/class-002.js lc2/JSToJava/character-001.js lc2/JSToJava/double-001.js lc2/JSToJava/double-002.js lc2/JSToJava/float-001.js lc2/JSToJava/float-002.js lc2/JSToJava/integer-001.js lc2/JSToJava/integer-002.js lc2/JSToJava/long-001.js lc2/JSToJava/long-002.js lc2/JSToJava/long-003-n.js lc2/JSToJava/short-001.js lc2/JSToJava/short-002.js lc2/JSToJava/short-003-n.js lc2/JavaToJS/String-001.js lc2/JavaToJS/boolean-001.js lc2/JavaToJS/boolean-003.js lc2/JavaToJS/boolean-004.js lc2/JavaToJS/boolean-005.js lc2/JavaToJS/char-001.js lc2/JavaToJS/char-002.js lc2/JavaToJS/enum-001.js lc2/JavaToJS/enum-002.js lc2/JavaToJS/null-001.js lc2/JavaToJS/number-001.js lc2/JavaToJS/number-002.js lc2/Methods/method-001.js lc2/Methods/method-002.js lc2/Methods/method-003.js lc2/Methods/method-004-n.js lc2/Methods/method-005.js lc2/Methods/method-006-n.js lc2/Methods/println-001.js lc2/Objects/object-001.js lc2/Objects/object-002.js lc2/Objects/object-003.js lc2/Objects/object-004.js lc2/Objects/object-005.js lc2/Objects/object-006.js lc2/Packages/package-001.js lc2/Packages/package-002.js lc2/Packages/package-003.js lc2/Packages/package-005.js lc2/Packages/package-006.js lc2/Packages/package-007-n.js lc2/Packages/package-008-n.js lc2/misc/constructor.js lc2/misc/wrapUnwrap.js lc3/ArrayMethods/byte-001.js lc3/ArrayMethods/byte-002.js lc3/ConvertBoolean/boolean-005-n.js lc3/ConvertBoolean/boolean-006-n.js lc3/ConvertBoolean/boolean-007-n.js lc3/ConvertBoolean/boolean-008-n.js lc3/ConvertBoolean/boolean-009-n.js lc3/ConvertBoolean/boolean-010-n.js lc3/ConvertBoolean/boolean-011-n.js lc3/ConvertBoolean/boolean-012-n.js lc3/ConvertBoolean/boolean-013-n.js lc3/ConvertNull/null-002.js lc3/ConvertNull/null-003-n.js lc3/ConvertNull/null-004-n.js lc3/ConvertNull/null-006-n.js lc3/ConvertString/string-004-n.js lc3/ConvertString/string-005-n.js lc3/ConvertString/string-007-n.js lc3/ConvertUndefined/undefined-001-n.js lc3/JSBoolean/boolean-002-n.js lc3/JSBoolean/boolean-003-n.js lc3/JSBoolean/boolean-004-n.js lc3/JSBoolean/boolean-005-n.js lc3/JSBoolean/boolean-006-n.js lc3/JSBoolean/boolean-007-n.js lc3/JSBoolean/boolean-008-n.js lc3/JSNull/ToBoolean-001-n.js lc3/JSNull/ToLong-001-n.js lc3/JSNull/ToNumber-001-n.js lc3/JSNumber/ToByte-002-n.js lc3/JSNumber/ToByte-003-n.js lc3/JSNumber/ToByte-005-n.js lc3/JSNumber/ToChar-002-n.js lc3/JSNumber/ToChar-003-n.js lc3/JSNumber/ToChar-005-n.js lc3/JSNumber/ToChar-006-n.js lc3/JSNumber/ToInt-002-n.js lc3/JSNumber/ToInt-003-n.js lc3/JSNumber/ToLong-002-n.js lc3/JSNumber/ToLong-003-n.js lc3/JSNumber/ToLong-004-n.js lc3/JSNumber/ToLong-005-n.js lc3/JSNumber/ToLong-006-n.js lc3/JSNumber/ToLong-007-n.js lc3/JSNumber/ToLong-008-n.js lc3/JSNumber/ToLong-009-n.js lc3/JSNumber/ToLong-010-n.js lc3/JSNumber/ToLong-011-n.js lc3/JSNumber/ToShort-003-n.js lc3/JSNumber/ToShort-005-n.js lc3/JSObject/ToDouble-002-n.js lc3/JSObject/ToDouble-003-n.js lc3/JSObject/ToFloat-002-n.js lc3/JSObject/ToFloat-003-n.js lc3/JSUndefined/undefined-002-n.js lc3/JSUndefined/undefined-003-n.js lc3/JSUndefined/undefined-004-n.js lc3/JSUndefined/undefined-005-n.js lc3/JSUndefined/undefined-006-n.js lc3/JSUndefined/undefined-008-n.js lc3/JSUndefined/undefined-009-n.js lc3/JSUndefined/undefined-010-n.js lc3/JavaArray/ToArray-002-n.js lc3/JavaArray/ToBoolean-001-n.js lc3/JavaObject/JavaObjectToBoolean-002-n.js lc3/JavaObject/JavaObjectToByte-002-n.js lc3/JavaObject/JavaObjectToByte-007-n.js lc3/JavaObject/JavaObjectToByte-008-n.js lc3/JavaObject/JavaObjectToChar-003-n.js lc3/JavaObject/JavaObjectToChar-005-n.js lc3/JavaObject/JavaObjectToChar-006-n.js lc3/JavaObject/JavaObjectToInt-002-n.js lc3/JavaObject/JavaObjectToInt-003-n.js lc3/JavaObject/JavaObjectToInt-004-n.js lc3/JavaObject/JavaObjectToLong-002-n.js lc3/JavaObject/JavaObjectToLong-003-n.js lc3/JavaObject/JavaObjectToLong-004-n.js lc3/JavaObject/JavaObjectToLong-006-n.js lc3/JavaObject/JavaObjectToShort-002-n.js lc3/JavaObject/JavaObjectToShort-003-n.js lc3/JavaObject/JavaObjectToShort-004-n.js lc3/StringMethods/string-001.js jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/0000755000175000017500000000000011537630013025166 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/0000755000175000017500000000000011537630013026635 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/0000755000175000017500000000000011537630013031003 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/testing/0000755000175000017500000000000011537630013032460 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000015200000000000011213 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/testing/TestErrorReporter.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/testing/TestErrorReporter0000644000175000017500000000425711314263504036067 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.testing; import org.mozilla.javascript.ErrorReporter; import org.mozilla.javascript.EvaluatorException; import junit.framework.Assert; /** *

An error reporter for testing that verifies that messages reported to the * reporter are expected.

* *

Sample use

*
 * TestErrorReporter e =
 *   new TestErrorReporter(null, new String[] { "first warning" });
 * ...
 * assertTrue(e.hasEncounteredAllWarnings());
 * 
* * @author Pascal-Louis Perez */ public final class TestErrorReporter extends Assert implements ErrorReporter { private final String[] errors; private final String[] warnings; private int errorsIndex = 0; private int warningsIndex = 0; public TestErrorReporter(String[] errors, String[] warnings) { this.errors = errors; this.warnings = warnings; } public void error(String message, String sourceName, int line, String lineSource, int lineOffset) { if (errors != null && errorsIndex < errors.length) { assertEquals(errors[errorsIndex++], message); } else { fail("extra error: " + message); } } public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) { if (warnings != null && warningsIndex < warnings.length) { assertEquals(warnings[warningsIndex++], message); } else { fail("extra warning: " + message); } } public EvaluatorException runtimeError( String message, String sourceName, int line, String lineSource, int lineOffset) { throw new UnsupportedOperationException(); } /** * Returns whether all warnings were reported to this reporter. */ public boolean hasEncounteredAllWarnings() { return (warnings == null) ? warningsIndex == 0 : warnings.length == warningsIndex; } /** * Returns whether all errors were reported to this reporter. */ public boolean hasEncounteredAllErrors() { return (errors == null) ? errorsIndex == 0 : errors.length == errorsIndex; } }jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/0000755000175000017500000000000011537630013032145 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000016000000000000011212 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ClassShutterExceptionTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ClassShutterExcepti0000755000175000017500000000465411314263504036052 0ustar jamespagejamespage00000000000000/** * */ package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ClassShutter; import org.mozilla.javascript.RhinoException; import org.mozilla.javascript.EvaluatorException; /** * @author Norris Boyd */ public class ClassShutterExceptionTest extends TestCase { private static Context.ClassShutterSetter classShutterSetter; /** * Define a ClassShutter that prevents access to all Java classes. */ static class OpaqueShutter implements ClassShutter { public boolean visibleToScripts(String name) { return false; } } public void helper(String source) { Context cx = Context.enter(); Context.ClassShutterSetter setter = cx.getClassShutterSetter(); try { Scriptable globalScope = cx.initStandardObjects(); if (setter == null) { setter = classShutterSetter; } else { classShutterSetter = setter; } setter.setClassShutter(new OpaqueShutter()); cx.evaluateString(globalScope, source, "test source", 1, null); } finally { setter.setClassShutter(null); Context.exit(); } } public void testClassShutterException() { try { helper("java.lang.System.out.println('hi');"); fail(); } catch (RhinoException e) { // OpaqueShutter should prevent access to java.lang... return; } } public void testThrowingException() { // JavaScript exceptions with no reference to Java // should not be affected by the ClassShutter helper("try { throw 3; } catch (e) { }"); } public void testThrowingEcmaError() { try { // JavaScript exceptions with no reference to Java // should not be affected by the ClassShutter helper("friggin' syntax error!"); fail("Should have thrown an exception"); } catch (EvaluatorException e) { // should have thrown an exception for syntax error } } public void testThrowingEvaluatorException() { // JavaScript exceptions with no reference to Java // should not be affected by the ClassShutter helper("try { eval('for;if;else'); } catch (e) { }"); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/Bug448816Test.java0000644000175000017500000000634611314263504035075 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.Context; import junit.framework.TestCase; import java.util.*; /** * See https://bugzilla.mozilla.org/show_bug.cgi?id=448816 * @author Hannes Wallnoefer */ public class Bug448816Test extends TestCase { Map map, reference; protected void setUp() { // set up a reference map reference = new LinkedHashMap(); reference.put("a", "a"); reference.put("b", Boolean.TRUE); reference.put("c", new HashMap()); reference.put(new Integer(1), new Integer(42)); // get a js object as map Context context = Context.enter(); ScriptableObject scope = context.initStandardObjects(); map = (Map) context.evaluateString(scope, "({ a: 'a', b: true, c: new java.util.HashMap(), 1: 42});", "testsrc", 1, null); Context.exit(); } public void testEqual() { // FIXME we do not override equals() and hashCode() in ScriptableObject // so calling this with swapped argument fails. This breaks symmetry // of equals(), but overriding these methods might be risky. assertEquals(reference, map); } public void testBasicAccess() { assertTrue(map.size() == 4); assertEquals(map.get("a"), reference.get("a")); assertEquals(map.get("b"), reference.get("b")); assertEquals(map.get("c"), reference.get("c")); assertEquals(map.get(new Integer(1)), reference.get(new Integer(1))); assertEquals(map.get("notfound"), reference.get("notfound")); assertTrue(map.containsKey("b")); assertTrue(map.containsValue(Boolean.TRUE)); assertFalse(map.containsKey("x")); assertFalse(map.containsValue(Boolean.FALSE)); assertFalse(map.containsValue(null)); } public void testCollections() { assertEquals(map.keySet(), reference.keySet()); assertEquals(map.entrySet(), reference.entrySet()); // java.util.Collection does not imply overriding equals(), so: assertTrue(map.values().containsAll(reference.values())); assertTrue(reference.values().containsAll(map.values())); } public void testRemoval() { // the only update we implement is removal assertTrue(map.size() == 4); assertEquals(map.remove("b"), Boolean.TRUE); reference.remove("b"); assertTrue(map.size() == 3); assertEquals(reference, map); testCollections(); } public void testKeyIterator() { compareIterators(map.keySet().iterator(), reference.keySet().iterator()); } public void testEntryIterator() { compareIterators(map.entrySet().iterator(), reference.entrySet().iterator()); } public void testValueIterator() { compareIterators(map.values().iterator(), reference.values().iterator()); } private void compareIterators(Iterator it1, Iterator it2) { assertTrue(map.size() == 4); while (it1.hasNext()) { assertEquals(it1.next(), it2.next()); it1.remove(); it2.remove(); } assertTrue(map.isEmpty()); } } ././@LongLink0000000000000000000000000000014700000000000011217 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/NativeStringTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/NativeStringTest.ja0000644000175000017500000000240111314263504035733 0ustar jamespagejamespage00000000000000/** * */ package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.Scriptable; /** * @author Marc Guillemot */ public class NativeStringTest extends TestCase { /** * Test for bug #492359 * https://bugzilla.mozilla.org/show_bug.cgi?id=492359 * Calling generic String or Array functions without arguments was causing ArrayIndexOutOfBoundsException * in 1.7R2 */ public void testtoLowerCaseApply() { assertEvaluates("hello", "var x = String.toLowerCase; x.apply('HELLO')"); assertEvaluates("hello", "String.toLowerCase('HELLO')"); // first patch proposed to #492359 was breaking this } private void assertEvaluates(final Object expected, final String source) { final ContextAction action = new ContextAction() { public Object run(Context cx) { final Scriptable scope = cx.initStandardObjects(); final Object rep = cx.evaluateString(scope, source, "test.js", 0, null); assertEquals(expected, rep); return null; } }; Utils.runWithAllOptimizationLevels(action); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/Bug496585.java0000755000175000017500000000213011314263504034231 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import org.mozilla.javascript.Function; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.Context; import org.junit.Test; public class Bug496585 { public void method(String one, Function function) { System.out.println("string+function"); } public void method(String... strings) { System.out.println("string[]"); } @Test public void callOverloadedFunction() { new ContextFactory().call(new ContextAction() { public Object run(Context cx) { cx.evaluateString( cx.initStandardObjects(), "new org.mozilla.javascript.tests.Bug496585().method('one', 'two', 'three')", "", 1, null); cx.evaluateString( cx.initStandardObjects(), "new org.mozilla.javascript.tests.Bug496585().method('one', function() {})", "", 1, null); return null; } }); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/Bug492525Test.java0000644000175000017500000000072211314263504035061 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import org.mozilla.javascript.NativeArray; public class Bug492525Test { @Test public void getAllIdsShouldIncludeArrayIndices() { NativeArray array = new NativeArray(new String[]{"a", "b"}); Object[] expectedIds = new Object[] {0, 1, "length"}; Object[] actualIds = array.getAllIds(); assertArrayEquals(expectedIds, actualIds); } } ././@LongLink0000000000000000000000000000016200000000000011214 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ObserveInstructionCountTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ObserveInstructionC0000644000175000017500000000675711314263504036061 0ustar jamespagejamespage00000000000000/** * */ package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.Callable; import org.mozilla.javascript.drivers.TestUtils; /** * @author Norris Boyd */ public class ObserveInstructionCountTest extends TestCase { // Custom Context to store execution time. static class MyContext extends Context { MyContext(ContextFactory factory) { super(factory); } int quota; } static class QuotaExceeded extends RuntimeException { private static final long serialVersionUID = -8018441873635071899L; } @Override protected void setUp() { TestUtils.setGlobalContextFactory(new MyFactory()); } @Override protected void tearDown() { TestUtils.setGlobalContextFactory(null); } static class MyFactory extends ContextFactory { @Override protected Context makeContext() { MyContext cx = new MyContext(this); // Make Rhino runtime call observeInstructionCount // each 500 bytecode instructions (if we're really enforcing // a quota of 2000, we could set this closer to 2000) cx.setInstructionObserverThreshold(500); return cx; } @Override protected void observeInstructionCount(Context cx, int instructionCount) { MyContext mcx = (MyContext)cx; mcx.quota -= instructionCount; if (mcx.quota <= 0) { throw new QuotaExceeded(); } } @Override protected Object doTopCall(Callable callable, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { MyContext mcx = (MyContext)cx; mcx.quota = 2000; return super.doTopCall(callable, cx, scope, thisObj, args); } } private void baseCase(int optimizationLevel, String source) { ContextFactory factory = new MyFactory(); Context cx = factory.enterContext(); cx.setOptimizationLevel(optimizationLevel); assertTrue(cx instanceof MyContext); try { Scriptable globalScope = cx.initStandardObjects(); cx.evaluateString(globalScope, source, "test source", 1, null); fail(); } catch (QuotaExceeded e) { // expected } catch (RuntimeException e) { fail(e.toString()); } finally { Context.exit(); } } public void testWhileTrueInGlobal() { String source = "var i=0; while (true) i++;"; baseCase(-1, source); // interpreted mode baseCase(1, source); // compiled mode } public void testWhileTrueNoCounterInGlobal() { String source = "while (true);"; baseCase(-1, source); // interpreted mode baseCase(1, source); // compiled mode } public void testWhileTrueInFunction() { String source = "var i=0; function f() { while (true) i++; } f();"; baseCase(-1, source); // interpreted mode baseCase(1, source); // compiled mode } public void testForever() { String source = "for(;;);"; baseCase(-1, source); // interpreted mode baseCase(1, source); // compiled mode } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/TypeOfTest.java0000644000175000017500000000677711314263504035077 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.BaseFunction; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Function; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; /** * Takes care that it's possible to customize the result of the typeof operator. * See https://bugzilla.mozilla.org/show_bug.cgi?id=463996 * Includes fix and test for https://bugzilla.mozilla.org/show_bug.cgi?id=453360 * @author Marc Guillemot */ public class TypeOfTest extends TestCase { public static class Foo extends ScriptableObject { private static final long serialVersionUID = -8771045033217033529L; private final String typeOfValue_; public Foo(final String _typeOfValue) { typeOfValue_ = _typeOfValue; } @Override public String getTypeOf() { return typeOfValue_; } @Override public String getClassName() { return "Foo"; } } /** * ECMA 11.4.3 says that typeof on host object is Implementation-dependent */ public void testCustomizeTypeOf() throws Exception { testCustomizeTypeOf("object", new Foo("object")); testCustomizeTypeOf("blabla", new Foo("blabla")); } /** * ECMA 11.4.3 says that typeof on host object is Implementation-dependent */ public void test0() throws Exception { final Function f = new BaseFunction() { @Override public Object call(Context _cx, Scriptable _scope, Scriptable _thisObj, Object[] _args) { return _args[0].getClass().getName(); } }; final ContextAction action = new ContextAction() { public Object run(final Context context) { final Scriptable scope = context.initStandardObjects(); scope.put("myObj", scope, f); return context.evaluateString(scope, "typeof myObj", "test script", 1, null); } }; doTest("function", action); } private void testCustomizeTypeOf(final String expected, final Scriptable obj) { final ContextAction action = new ContextAction() { public Object run(final Context context) { final Scriptable scope = context.initStandardObjects(); scope.put("myObj", scope, obj); return context.evaluateString(scope, "typeof myObj", "test script", 1, null); } }; doTest(expected, action); } /** * See https://bugzilla.mozilla.org/show_bug.cgi?id=453360 */ public void testBug453360() throws Exception { doTest("object", "typeof new RegExp();"); doTest("object", "typeof /foo/;"); } private void doTest(String expected, final String script) { final ContextAction action = new ContextAction() { public Object run(final Context context) { final Scriptable scope = context.initStandardObjects(); return context.evaluateString(scope, script, "test script", 1, null); } }; doTest(expected, action); } private void doTest(final String expected, final ContextAction action) { doTest(-1, expected, action); doTest(0, expected, action); doTest(1, expected, action); } private void doTest(final int optimizationLevel, final String expected, final ContextAction action) { Object o = new ContextFactory().call(new ContextAction() { public Object run(final Context context) { context.setOptimizationLevel(optimizationLevel); return Context.toString(action.run(context)); } }); assertEquals(expected, o); } }jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/Bug482203.java0000755000175000017500000000327411314263504034221 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import java.io.InputStreamReader; import junit.framework.TestCase; import org.mozilla.javascript.Callable; import org.mozilla.javascript.Context; import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; public class Bug482203 extends TestCase { public void testJsApi() throws Exception { Context cx = Context.enter(); cx.setOptimizationLevel(-1); Script script = cx.compileReader(new InputStreamReader( Bug482203.class.getResourceAsStream("conttest.js")), "", 1, null); Scriptable scope = cx.initStandardObjects(); script.exec(cx, scope); for(;;) { Object cont = ScriptableObject.getProperty(scope, "c"); if(cont == null) { break; } ((Callable)cont).call(cx, scope, scope, new Object[] { null }); } } public void testJavaApi() throws Exception { Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); Script script = cx.compileReader(new InputStreamReader( Bug482203.class.getResourceAsStream("conttest.js")), "", 1, null); Scriptable scope = cx.initStandardObjects(); cx.executeScriptWithContinuations(script, scope); for(;;) { Object cont = ScriptableObject.getProperty(scope, "c"); if(cont == null) { break; } cx.resumeContinuation(cont, scope, null); } } finally { Context.exit(); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/Utils.java0000644000175000017500000000165311314263504034115 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ContextFactory; /** * Misc utilities to make test code easier. * @author Marc Guillemot */ public class Utils { /** * Runs the action successively with all available optimization levels */ public static void runWithAllOptimizationLevels(final ContextAction action) { runWithOptimizationLevel(action, -1); runWithOptimizationLevel(action, 0); runWithOptimizationLevel(action, 1); } /** * Runs the provided action at the given optimization level */ public static void runWithOptimizationLevel(final ContextAction action, final int optimizationLevel) { final Context cx = new ContextFactory().enterContext(); try { cx.setOptimizationLevel(optimizationLevel); action.run(cx); } finally { Context.exit(); } } } ././@LongLink0000000000000000000000000000017300000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/CustomSetterAcceptNullScriptableTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/CustomSetterAcceptN0000644000175000017500000000350011314263504035765 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import java.lang.reflect.Method; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; /** * Takes care that it's possible to set null value * when using custom setter for a {@link Scriptable} object. * See https://bugzilla.mozilla.org/show_bug.cgi?id=461138 * @author Marc Guillemot */ public class CustomSetterAcceptNullScriptableTest extends TestCase { public static class Foo extends ScriptableObject { private static final long serialVersionUID = -8771045033217033529L; @Override public String getClassName() { return "Foo"; } public void setMyProp(final Foo2 s) { } } public static class Foo2 extends ScriptableObject { private static final long serialVersionUID = -8880603824656138628L; @Override public String getClassName() { return "Foo2"; } } public void testSetNullForScriptableSetter() throws Exception { final String scriptCode = "foo.myProp = new Foo2();\n" + "foo.myProp = null;"; final ContextFactory factory = new ContextFactory(); final Context cx = factory.enterContext(); try { final ScriptableObject topScope = cx.initStandardObjects(); final Foo foo = new Foo(); // define custom setter method final Method setMyPropMethod = Foo.class.getMethod("setMyProp", Foo2.class); foo.defineProperty("myProp", null, null, setMyPropMethod, ScriptableObject.EMPTY); topScope.put("foo", topScope, foo); ScriptableObject.defineClass(topScope, Foo2.class); cx.evaluateString(topScope, scriptCode, "myScript", 1, null); } finally { Context.exit(); } } } ././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/StrictModeApiTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/StrictModeApiTest.j0000755000175000017500000000325111314263504035673 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.EvaluatorException; /** * Test of strict mode APIs. * * @author Norris Boyd */ public class StrictModeApiTest extends TestCase { private ScriptableObject global; private ContextFactory contextFactory; static class MyContextFactory extends ContextFactory { @Override protected boolean hasFeature(Context cx, int featureIndex) { switch (featureIndex) { case Context.FEATURE_STRICT_MODE: case Context.FEATURE_STRICT_VARS: case Context.FEATURE_STRICT_EVAL: case Context.FEATURE_WARNING_AS_ERROR: return true; } return super.hasFeature(cx, featureIndex); } } public void testStrictModeError() { contextFactory = new MyContextFactory(); Context cx = contextFactory.enterContext(); try { global = cx.initStandardObjects(); try { runScript("({}.nonexistent);"); fail(); } catch (EvaluatorException e) { assertTrue(e.getMessage().startsWith("Reference to undefined property")); } } finally { Context.exit(); } } private Object runScript(final String scriptSourceText) { return this.contextFactory.call(new ContextAction() { public Object run(Context context) { return context.evaluateString(global, scriptSourceText, "test source", 1, null); } }); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/Bug467396Test.java0000644000175000017500000000403711314263504035074 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.Wrapper; import junit.framework.TestCase; /** * Test for overloaded varargs/non-varargs methods. * See https://bugzilla.mozilla.org/show_bug.cgi?id=467396 * @author Hannes Wallnoefer */ public class Bug467396Test extends TestCase { public void testOverloadedVarargs() { Context cx = ContextFactory.getGlobal().enterContext(); try { Scriptable scope = cx.initStandardObjects(); Object result = unwrap(cx.evaluateString(scope, "java.lang.reflect.Array.newInstance(java.lang.Object, 1)", "source", 1, null)); assertTrue(result instanceof Object[]); assertEquals(1, ((Object[]) result).length); result = unwrap(cx.evaluateString(scope, "java.lang.reflect.Array.newInstance(java.lang.Object, [1])", "source", 1, null)); assertTrue(result instanceof Object[]); assertEquals(1, ((Object[]) result).length); result = unwrap(cx.evaluateString(scope, "java.lang.reflect.Array.newInstance(java.lang.Object, [1, 1])", "source", 1, null)); assertTrue(result instanceof Object[][]); assertEquals(1, ((Object[][]) result).length); assertEquals(1, ((Object[][]) result)[0].length); result = unwrap(cx.evaluateString(scope, "java.lang.reflect.Array.newInstance(java.lang.Object, 1, 1)", "source", 1, null)); assertTrue(result instanceof Object[][]); assertEquals(1, ((Object[][]) result).length); assertEquals(1, ((Object[][]) result)[0].length); } finally { Context.exit(); } } private Object unwrap(Object obj) { return obj instanceof Wrapper ? ((Wrapper) obj).unwrap() : obj; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/conttest.js0000644000175000017500000000071711314263504034353 0ustar jamespagejamespage00000000000000var __terminate_interpreter__ = new Continuation(); java.lang.System.out.println("top"); var c; function fib(x) { c = getContinuation(); java.lang.System.out.println("fib(" + x + "); c = "+c); if(c != null) { java.lang.System.out.println("here"); this.__terminate_interpreter__(null); } return x < 2 ? 1 : (fib(x-1) + fib(x-2)); } function getContinuation() { return new Continuation(); } java.lang.System.out.println(fib(3));jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/Bug419940Test.java0000755000175000017500000000170611314263504035067 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.*; /** * See https://bugzilla.mozilla.org/show_bug.cgi?id=419940 * @author Norris Boyd */ public class Bug419940Test extends TestCase { final static int value = 12; public static abstract class BaseFoo { public abstract int doSomething(); } public static class Foo extends BaseFoo { @Override public int doSomething() { return value; } } public void testAdapter() { String source = "(new JavaAdapter(" + Foo.class.getName() + ", {})).doSomething();"; Context cx = ContextFactory.getGlobal().enterContext(); try { Scriptable scope = cx.initStandardObjects(); Object result = cx.evaluateString(scope, source, "source", 1, null); assertEquals(new Integer(value), result); } finally { Context.exit(); } } } ././@LongLink0000000000000000000000000000016100000000000011213 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ApplyOnPrimitiveNumberTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ApplyOnPrimitiveNum0000644000175000017500000000201511314263504036021 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.ScriptableObject; /** * Primitive numbers are not wrapped before calling apply. * Test for bug
466661. * @author Marc Guillemot */ public class ApplyOnPrimitiveNumberTest extends TestCase { public void testIt() { final String script = "var fn = function() { return this; }\n" + "fn.apply(1)"; final ContextAction action = new ContextAction() { public Object run(final Context _cx) { final ScriptableObject scope = _cx.initStandardObjects(); final Object result = _cx.evaluateString(scope, script, "test script", 0, null); assertEquals("object", ScriptRuntime.typeof(result)); assertEquals("1", Context.toString(result)); return null; } }; Utils.runWithAllOptimizationLevels(action); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ParserTest.java0000644000175000017500000002053711314263504035113 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import org.mozilla.javascript.ast.*; import org.mozilla.javascript.CompilerEnvirons; import org.mozilla.javascript.Parser; import org.mozilla.javascript.Token; import org.mozilla.javascript.testing.TestErrorReporter; import junit.framework.TestCase; import java.io.IOException; import java.io.StringReader; public class ParserTest extends TestCase { public void testLinenoAssign() { AstRoot root = parse("\n\na = b"); ExpressionStatement st = (ExpressionStatement) root.getFirstChild(); AstNode n = st.getExpression(); assertTrue(n instanceof Assignment); assertEquals(Token.ASSIGN, n.getType()); assertEquals(2, n.getLineno()); } public void testLinenoCall() { AstRoot root = parse("\nfoo(123);"); ExpressionStatement st = (ExpressionStatement) root.getFirstChild(); AstNode n = st.getExpression(); assertTrue(n instanceof FunctionCall); assertEquals(Token.CALL, n.getType()); assertEquals(1, n.getLineno()); } public void testLinenoGetProp() { AstRoot root = parse("\nfoo.bar"); ExpressionStatement st = (ExpressionStatement) root.getFirstChild(); AstNode n = st.getExpression(); assertTrue(n instanceof PropertyGet); assertEquals(Token.GETPROP, n.getType()); assertEquals(1, n.getLineno()); PropertyGet getprop = (PropertyGet) n; AstNode m = getprop.getRight(); assertTrue(m instanceof Name); assertEquals(Token.NAME, m.getType()); // used to be Token.STRING! assertEquals(1, m.getLineno()); } public void testLinenoGetElem() { AstRoot root = parse("\nfoo[123]"); ExpressionStatement st = (ExpressionStatement) root.getFirstChild(); AstNode n = st.getExpression(); assertTrue(n instanceof ElementGet); assertEquals(Token.GETELEM, n.getType()); assertEquals(1, n.getLineno()); } public void testLinenoComment() { AstRoot root = parse("\n/** a */"); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); assertEquals(1, root.getComments().first().getLineno()); } public void testLinenoComment2() { AstRoot root = parse("\n/**\n\n a */"); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); assertEquals(1, root.getComments().first().getLineno()); } public void testLinenoComment3() { AstRoot root = parse("\n \n\n/**\n\n a */"); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); assertEquals(3, root.getComments().first().getLineno()); } public void testLinenoComment4() { AstRoot root = parse("\n \n\n /**\n\n a */"); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); assertEquals(3, root.getComments().first().getLineno()); } public void testLineComment5() { AstRoot root = parse(" /**\n* a.\n* b.\n* c.*/\n"); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); assertEquals(0, root.getComments().first().getLineno()); } public void testLineComment6() { AstRoot root = parse(" \n/**\n* a.\n* b.\n* c.*/\n"); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); assertEquals(1, root.getComments().first().getLineno()); } public void testInOperatorInForLoop1() { parse("var a={};function b_(p){ return p;};" + "for(var i=b_(\"length\" in a);i<0;) {}"); } public void testInOperatorInForLoop2() { parse("var a={}; for (;(\"length\" in a);) {}"); } public void testInOperatorInForLoop3() { parse("for (x in y) {}"); } public void testJSDocAttachment1() { AstRoot root = parse("/** @type number */var a;"); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); assertEquals("/** @type number */", root.getComments().first().getValue()); assertNotNull(root.getFirstChild().getJsDoc()); } public void testJSDocAttachment2() { AstRoot root = parse("/** @type number */a.b;"); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); assertEquals("/** @type number */", root.getComments().first().getValue()); ExpressionStatement st = (ExpressionStatement) root.getFirstChild(); assertNotNull(st.getExpression().getJsDoc()); } public void testJSDocAttachment3() { AstRoot root = parse("var a = /** @type number */(x);"); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); assertEquals("/** @type number */", root.getComments().first().getValue()); VariableDeclaration vd = (VariableDeclaration) root.getFirstChild(); VariableInitializer vi = vd.getVariables().get(0); assertNotNull(vi.getInitializer().getJsDoc()); } public void testJSDocAttachment4() { AstRoot root = parse("(function() {/** should not be attached */})()"); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); ExpressionStatement st = (ExpressionStatement) root.getFirstChild(); FunctionCall fc = (FunctionCall) st.getExpression(); ParenthesizedExpression pe = (ParenthesizedExpression) fc.getTarget(); assertNull(pe.getJsDoc()); } public void testParsingWithoutJSDoc() { AstRoot root = parse("var a = /** @type number */(x);", false); assertNotNull(root.getComments()); assertEquals(1, root.getComments().size()); assertEquals("/** @type number */", root.getComments().first().getValue()); VariableDeclaration vd = (VariableDeclaration) root.getFirstChild(); VariableInitializer vi = vd.getVariables().get(0); assertTrue(vi.getInitializer() instanceof ParenthesizedExpression); } public void testParseCommentsAsReader() throws IOException { AstRoot root = parseAsReader( "/** a */var a;\n /** b */var b; /** c */var c;"); assertNotNull(root.getComments()); assertEquals(3, root.getComments().size()); Comment[] comments = new Comment[3]; comments = root.getComments().toArray(comments); assertEquals("/** a */", comments[0].getValue()); assertEquals("/** b */", comments[1].getValue()); assertEquals("/** c */", comments[2].getValue()); } public void testParseCommentsAsReader2() throws IOException { String js = ""; for (int i = 0; i < 100; i++) { String stri = Integer.toString(i); js += "/** Some comment for a" + stri + " */" + "var a" + stri + " = " + stri + ";\n"; } AstRoot root = parseAsReader(js); } private AstRoot parse(String string) { return parse(string, true); } private AstRoot parse(String string, boolean jsdoc) { CompilerEnvirons environment = new CompilerEnvirons(); TestErrorReporter testErrorReporter = new TestErrorReporter(null, null); environment.setErrorReporter(testErrorReporter); environment.setRecordingComments(true); environment.setRecordingLocalJsDocComments(jsdoc); Parser p = new Parser(environment, testErrorReporter); AstRoot script = p.parse(string, null, 0); assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); return script; } private AstRoot parseAsReader(String string) throws IOException { CompilerEnvirons environment = new CompilerEnvirons(); TestErrorReporter testErrorReporter = new TestErrorReporter(null, null); environment.setErrorReporter(testErrorReporter); environment.setRecordingComments(true); environment.setRecordingLocalJsDocComments(true); Parser p = new Parser(environment, testErrorReporter); AstRoot script = p.parse(new StringReader(string), null, 0); assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); return script; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/Bug421071Test.java0000755000175000017500000000764011314263504035056 0ustar jamespagejamespage00000000000000/* * @(#)Bug421071Test.java * */ package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.ImporterTopLevel; import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; public class Bug421071Test extends TestCase { private ContextFactory factory; private TopLevelScope globalScope; private Script testScript; public void testProblemReplicator() throws Exception { // before debugging please put the breakpoint in the // NativeJavaPackage.getPkgProperty() // and observe names passed in there testScript = compileScript(); runTestScript(); // this one does not get to the // NativeJavaPackage.getPkgProperty() on my // variables runTestScript(); // however this one does } private Script compileScript() { String scriptSource = "importPackage(java.util);\n" + "var searchmon = 3;\n" + "var searchday = 10;\n" + "var searchyear = 2008;\n" + "var searchwkday = 0;\n" + "\n" + "var myDate = Calendar.getInstance();\n // this is a java.util.Calendar" + "myDate.set(Calendar.MONTH, searchmon);\n" + "myDate.set(Calendar.DATE, searchday);\n" + "myDate.set(Calendar.YEAR, searchyear);\n" + "searchwkday.value = myDate.get(Calendar.DAY_OF_WEEK);"; Script script; Context context = factory.enterContext(); try { script = context.compileString(scriptSource, "testScript", 1, null); return script; } finally { Context.exit(); } } private void runTestScript() throws InterruptedException { // will start new thread to get as close as possible to original // environment, however the same behavior is exposed using new // ScriptRunner(script).run(); Thread thread = new Thread(new ScriptRunner(testScript)); thread.start(); thread.join(); } static class DynamicScopeContextFactory extends ContextFactory { @Override public boolean hasFeature(Context cx, int featureIndex) { if (featureIndex == Context.FEATURE_DYNAMIC_SCOPE) return true; return super.hasFeature(cx, featureIndex); } } private TopLevelScope createGlobalScope() { factory = new DynamicScopeContextFactory(); Context context = factory.enterContext(); // noinspection deprecation TopLevelScope globalScope = new TopLevelScope(context); Context.exit(); return globalScope; } @Override protected void setUp() throws Exception { super.setUp(); globalScope = createGlobalScope(); } private class TopLevelScope extends ImporterTopLevel { private static final long serialVersionUID = 7831526694313927899L; public TopLevelScope(Context context) { super(context); } } private class ScriptRunner implements Runnable { private Script script; public ScriptRunner(Script script) { this.script = script; } public void run() { Context context = factory.enterContext(); try { // Run each script in its own scope, to keep global variables // defined in each script separate Scriptable threadScope = context.newObject(globalScope); threadScope.setPrototype(globalScope); threadScope.setParentScope(null); script.exec(context, threadScope); } catch (Exception ee) { ee.printStackTrace(); } finally { Context.exit(); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/JsTestsTest.java0000755000175000017500000000216011314263504035251 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import java.io.File; import java.io.FileFilter; import java.io.IOException; import org.mozilla.javascript.drivers.TestUtils; import org.mozilla.javascript.drivers.JsTestsBase; public class JsTestsTest extends JsTestsBase { static final String baseDirectory = "testsrc" + File.separator + "jstests"; static final String jstestsExtension = ".jstest"; public void runJsTests() throws IOException { File[] tests = TestUtils.recursiveListFiles(new File(baseDirectory), new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(jstestsExtension); } }); runJsTests(tests); } public void testJsTestsInterpreted() throws IOException { setOptimizationLevel(-1); runJsTests(); } public void testJsTestsCompiled() throws IOException { setOptimizationLevel(0); runJsTests(); } public void testJsTestsOptimized() throws IOException { setOptimizationLevel(9); runJsTests(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/Bug412433Test.java0000644000175000017500000000107211314263504035046 0ustar jamespagejamespage00000000000000/** * */ package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.*; /** * See https://bugzilla.mozilla.org/show_bug.cgi?id=412433 * @author Norris Boyd */ public class Bug412433Test extends TestCase { public void testMalformedJavascript2() { Context context = Context.enter(); try { ScriptableObject scope = context.initStandardObjects(); context.evaluateString(scope, "\"\".split(/[/?,/&]/)", "", 0, null); } finally { Context.exit(); } } } ././@LongLink0000000000000000000000000000015300000000000011214 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/JavaAcessibilityTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/JavaAcessibilityTes0000644000175000017500000001077311314263504036002 0ustar jamespagejamespage00000000000000/** * */ package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.NativeJavaObject; import org.mozilla.javascript.Script; import org.mozilla.javascript.drivers.TestUtils; import org.mozilla.javascript.tools.shell.Global; import org.mozilla.javascript.tools.shell.ShellContextFactory; /** * @author donnamalayeri */ public class JavaAcessibilityTest extends TestCase { protected final Global global = new Global(); String importClass = "importClass(Packages.org.mozilla.javascript.tests.PrivateAccessClass)\n"; public JavaAcessibilityTest() { global.init(contextFactory); } @Override protected void setUp() { TestUtils.setGlobalContextFactory(contextFactory); } @Override protected void tearDown() { TestUtils.setGlobalContextFactory(null); } private ContextFactory contextFactory = new ShellContextFactory() { @Override protected boolean hasFeature(Context cx, int featureIndex) { if (featureIndex == Context.FEATURE_ENHANCED_JAVA_ACCESS) return true; return super.hasFeature(cx, featureIndex); } }; public void testAccessingFields() { Object result = runScript(importClass + "PrivateAccessClass.staticPackagePrivateInt"); assertEquals(new Integer(0), result); result = runScript(importClass + "PrivateAccessClass.staticPrivateInt"); assertEquals(new Integer(1), result); result = runScript(importClass + "PrivateAccessClass.staticProtectedInt"); assertEquals(new Integer(2), result); result = runScript(importClass + "new PrivateAccessClass().packagePrivateString"); assertEquals("package private", ((NativeJavaObject) result).unwrap()); result = runScript(importClass + "new PrivateAccessClass().privateString"); assertEquals("private", ((NativeJavaObject) result).unwrap()); result = runScript(importClass + "new PrivateAccessClass().protectedString"); assertEquals("protected", ((NativeJavaObject) result).unwrap()); result = runScript(importClass + "new PrivateAccessClass.PrivateNestedClass().packagePrivateInt"); assertEquals(new Integer(0), result); result = runScript(importClass + "new PrivateAccessClass.PrivateNestedClass().privateInt"); assertEquals(new Integer(1), result); result = runScript(importClass + "new PrivateAccessClass.PrivateNestedClass().protectedInt"); assertEquals(new Integer(2), result); } public void testAccessingMethods() { Object result = runScript(importClass + "PrivateAccessClass.staticPackagePrivateMethod()"); assertEquals(new Integer(0), result); result = runScript(importClass + "PrivateAccessClass.staticPrivateMethod()"); assertEquals(new Integer(1), result); result = runScript(importClass + "PrivateAccessClass.staticProtectedMethod()"); assertEquals(new Integer(2), result); result = runScript(importClass + "new PrivateAccessClass().packagePrivateMethod()"); assertEquals(new Integer(3), result); result = runScript(importClass + "new PrivateAccessClass().privateMethod()"); assertEquals(new Integer(4), result); result = runScript(importClass + "new PrivateAccessClass().protectedMethod()"); assertEquals(new Integer(5), result); } public void testAccessingConstructors() { runScript(importClass + "new PrivateAccessClass(\"foo\")"); runScript(importClass + "new PrivateAccessClass(5)"); runScript(importClass + "new PrivateAccessClass(5, \"foo\")"); } public void testAccessingJavaBeanProperty() { Object result = runScript(importClass + "var x = new PrivateAccessClass(); x.javaBeanProperty + ' ' + x.getterCalled;"); assertEquals("6 true", result); result = runScript(importClass + "var x = new PrivateAccessClass(); x.javaBeanProperty = 4; x.javaBeanProperty + ' ' + x.setterCalled;"); assertEquals("4 true", result); } public void testOverloadFunctionRegression() { Object result = runScript( "(new java.util.GregorianCalendar()).set(3,4);'success';"); assertEquals("success", result); } private Object runScript(final String scriptSourceText) { return contextFactory.call(new ContextAction() { public Object run(Context context) { Script script = context.compileString(scriptSourceText, "", 1, null); return script.exec(context, global); } }); } } ././@LongLink0000000000000000000000000000015300000000000011214 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ContinuationsApiTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ContinuationsApiTes0000644000175000017500000002424611314263504036043 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tests; import java.io.*; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.Script; import org.mozilla.javascript.Function; import org.mozilla.javascript.ContinuationPending; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.WrappedException; import org.mozilla.javascript.serialize.ScriptableInputStream; import org.mozilla.javascript.serialize.ScriptableOutputStream; /** * Test of new API functions for running and resuming scripts containing * continuations, and for suspending a continuation from a Java method * called from JavaScript. * * @author Norris Boyd */ public class ContinuationsApiTest extends TestCase { Scriptable globalScope; public static class MyClass implements Serializable { private static final long serialVersionUID = 4189002778806232070L; public int f(int a) { Context cx = Context.enter(); try { ContinuationPending pending = cx.captureContinuation(); pending.setApplicationState(a); throw pending; } finally { Context.exit(); } } public int g(int a) { Context cx = Context.enter(); try { ContinuationPending pending = cx.captureContinuation(); pending.setApplicationState(2*a); throw pending; } finally { Context.exit(); } } } @Override public void setUp() { Context cx = Context.enter(); try { globalScope = cx.initStandardObjects(); cx.setOptimizationLevel(-1); // must use interpreter mode globalScope.put("myObject", globalScope, Context.javaToJS(new MyClass(), globalScope)); } finally { Context.exit(); } } public void testScriptWithContinuations() { Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); // must use interpreter mode Script script = cx.compileString("myObject.f(3) + 1;", "test source", 1, null); cx.executeScriptWithContinuations(script, globalScope); fail("Should throw ContinuationPending"); } catch (ContinuationPending pending) { Object applicationState = pending.getApplicationState(); assertEquals(new Integer(3), applicationState); int saved = (Integer) applicationState; Object result = cx.resumeContinuation(pending.getContinuation(), globalScope, saved + 1); assertEquals(5, ((Number)result).intValue()); } finally { Context.exit(); } } public void testScriptWithMultipleContinuations() { Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); // must use interpreter mode Script script = cx.compileString( "myObject.f(3) + myObject.g(3) + 2;", "test source", 1, null); cx.executeScriptWithContinuations(script, globalScope); fail("Should throw ContinuationPending"); } catch (ContinuationPending pending) { try { Object applicationState = pending.getApplicationState(); assertEquals(new Integer(3), applicationState); int saved = (Integer) applicationState; cx.resumeContinuation(pending.getContinuation(), globalScope, saved + 1); fail("Should throw another ContinuationPending"); } catch (ContinuationPending pending2) { Object applicationState2 = pending2.getApplicationState(); assertEquals(new Integer(6), applicationState2); int saved2 = (Integer) applicationState2; Object result2 = cx.resumeContinuation(pending2.getContinuation(), globalScope, saved2 + 1); assertEquals(13, ((Number)result2).intValue()); } } finally { Context.exit(); } } public void testScriptWithNestedContinuations() { Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); // must use interpreter mode Script script = cx.compileString("myObject.g( myObject.f(1) ) + 2;", "test source", 1, null); cx.executeScriptWithContinuations(script, globalScope); fail("Should throw ContinuationPending"); } catch (ContinuationPending pending) { try { Object applicationState = pending.getApplicationState(); assertEquals(new Integer(1), applicationState); int saved = (Integer) applicationState; cx.resumeContinuation(pending.getContinuation(), globalScope, saved + 1); fail("Should throw another ContinuationPending"); } catch (ContinuationPending pending2) { Object applicationState2 = pending2.getApplicationState(); assertEquals(new Integer(4), applicationState2); int saved2 = (Integer) applicationState2; Object result2 = cx.resumeContinuation(pending2.getContinuation(), globalScope, saved2 + 2); assertEquals(8, ((Number)result2).intValue()); } } finally { Context.exit(); } } public void testFunctionWithContinuations() { Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); // must use interpreter mode cx.evaluateString(globalScope, "function f(a) { return myObject.f(a); }", "function test source", 1, null); Function f = (Function) globalScope.get("f", globalScope); Object[] args = { 7 }; cx.callFunctionWithContinuations(f, globalScope, args); fail("Should throw ContinuationPending"); } catch (ContinuationPending pending) { Object applicationState = pending.getApplicationState(); assertEquals(7, ((Number)applicationState).intValue()); int saved = (Integer) applicationState; Object result = cx.resumeContinuation(pending.getContinuation(), globalScope, saved + 1); assertEquals(8, ((Number)result).intValue()); } finally { Context.exit(); } } /** * Since a continuation can only capture JavaScript frames and not Java * frames, ensure that Rhino throws an exception when the JavaScript frames * don't reach all the way to the code called by * executeScriptWithContinuations or callFunctionWithContinuations. */ public void testErrorOnEvalCall() { Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); // must use interpreter mode Script script = cx.compileString("eval('myObject.f(3);');", "test source", 1, null); cx.executeScriptWithContinuations(script, globalScope); fail("Should throw IllegalStateException"); } catch (WrappedException we) { Throwable t = we.getWrappedException(); assertTrue(t instanceof IllegalStateException); assertTrue(t.getMessage().startsWith("Cannot capture continuation")); } finally { Context.exit(); } } public void testSerializationWithContinuations() throws IOException, ClassNotFoundException { Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); // must use interpreter mode cx.evaluateString(globalScope, "function f(a) { var k = myObject.f(a); var t = []; return k; }", "function test source", 1, null); Function f = (Function) globalScope.get("f", globalScope); Object[] args = { 7 }; cx.callFunctionWithContinuations(f, globalScope, args); fail("Should throw ContinuationPending"); } catch (ContinuationPending pending) { // serialize ByteArrayOutputStream baos = new ByteArrayOutputStream(); ScriptableOutputStream sos = new ScriptableOutputStream(baos, globalScope); sos.writeObject(globalScope); sos.writeObject(pending.getContinuation()); sos.close(); baos.close(); byte[] serializedData = baos.toByteArray(); // deserialize ByteArrayInputStream bais = new ByteArrayInputStream(serializedData); ScriptableInputStream sis = new ScriptableInputStream(bais, globalScope); globalScope = (Scriptable) sis.readObject(); Object continuation = sis.readObject(); sis.close(); bais.close(); Object result = cx.resumeContinuation(continuation, globalScope, 8); assertEquals(8, ((Number)result).intValue()); } finally { Context.exit(); } } } ././@LongLink0000000000000000000000000000016700000000000011221 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/PrimitiveTypeScopeResolutionTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/PrimitiveTypeScopeR0000644000175000017500000001164411314263504036024 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import org.junit.Test; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; /** * Unit tests for Bug 374918 - * String primitive prototype wrongly resolved when used with many top scopes * @author Marc Guillemot */ public class PrimitiveTypeScopeResolutionTest { /** */ @Test public void functionCall() { String str2 = "function f() {\n" + "String.prototype.foo = function() { return 'from 2' }; \n" + "var s2 = 's2';\n" + "var s2Foo = s2.foo();\n" + "if (s2Foo != 'from 2') throw 's2 got: ' + s2Foo;\n" // fails + "}"; String str1 = "String.prototype.foo = function() { return 'from 1'};" + "scope2.f()"; testWithTwoScopes(str1, str2); } /** */ @Test public void propertyAccess() { String str2 = "function f() { String.prototype.foo = 'from 2'; \n" + "var s2 = 's2';\n" + "var s2Foo = s2.foo;\n" + "if (s2Foo != 'from 2') throw 's2 got: ' + s2Foo;\n" // fails + "}"; String str1 = "String.prototype.foo = 'from 1'; scope2.f()"; testWithTwoScopes(str1, str2); } /** */ @Test public void elementAccess() { String str2 = "function f() { String.prototype.foo = 'from 2'; \n" + "var s2 = 's2';\n" + "var s2Foo = s2['foo'];\n" + "if (s2Foo != 'from 2') throw 's2 got: ' + s2Foo;\n" // fails + "}"; String str1 = "String.prototype.foo = 'from 1'; scope2.f()"; testWithTwoScopes(str1, str2); } private void testWithTwoScopes(final String scriptScope1, final String scriptScope2) { final ContextAction action = new ContextAction() { public Object run(final Context cx) { final Scriptable scope1 = cx.initStandardObjects( new MySimpleScriptableObject("scope1")); final Scriptable scope2 = cx.initStandardObjects( new MySimpleScriptableObject("scope2")); cx.evaluateString(scope2, scriptScope2, "source2", 1, null); scope1.put("scope2", scope1, scope2); return cx.evaluateString(scope1, scriptScope1, "source1", 1, null); } }; Utils.runWithAllOptimizationLevels(action); } /** * Simple utility allowing to better see the concerned scope while debugging */ static class MySimpleScriptableObject extends ScriptableObject { private static final long serialVersionUID = 1L; private String label_; MySimpleScriptableObject(String label) { label_ = label; } @Override public String getClassName() { return "MySimpleScriptableObject"; } @Override public String toString() { return label_; } } public static class MyObject extends ScriptableObject { private static final long serialVersionUID = 1L; @Override public String getClassName() { return "MyObject"; } public Object readPropFoo(final Scriptable s) { return ScriptableObject.getProperty(s, "foo"); } } /** * Test that FunctionObject use the right top scope to convert a primitive * to an object */ @Test public void functionObjectPrimitiveToObject() throws Exception { final String scriptScope2 = "function f() {\n" + "String.prototype.foo = 'from 2'; \n" + "var s2 = 's2';\n" + "var s2Foo = s2.foo;\n" + "var s2FooReadByFunction = myObject.readPropFoo(s2);\n" + "if (s2Foo != s2FooReadByFunction)\n" + "throw 's2 got: ' + s2FooReadByFunction;\n" + "}"; // define object with custom method final MyObject myObject = new MyObject(); final String[] functionNames = { "readPropFoo" }; myObject.defineFunctionProperties(functionNames, MyObject.class, ScriptableObject.EMPTY); final String scriptScope1 = "String.prototype.foo = 'from 1'; scope2.f()"; final ContextAction action = new ContextAction() { public Object run(final Context cx) { final Scriptable scope1 = cx.initStandardObjects( new MySimpleScriptableObject("scope1")); final Scriptable scope2 = cx.initStandardObjects( new MySimpleScriptableObject("scope2")); scope2.put("myObject", scope2, myObject); cx.evaluateString(scope2, scriptScope2, "source2", 1, null); scope1.put("scope2", scope1, scope2); return cx.evaluateString(scope1, scriptScope1, "source1", 1, null); } }; Utils.runWithAllOptimizationLevels(action); } } ././@LongLink0000000000000000000000000000015500000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/GeneratedClassNameTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/GeneratedClassNameT0000644000175000017500000000255011314263504035703 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Script; import junit.framework.TestCase; /** * Takes care that the class name of the generated class "looks like" * the provided script name. * See https://bugzilla.mozilla.org/show_bug.cgi?id=460283 * @author Marc Guillemot */ public class GeneratedClassNameTest extends TestCase { public void testGeneratedClassName() throws Exception { doTest("myScript_js", "myScript.js"); doTest("foo", "foo"); doTest("c", ""); doTest("_1", "1"); doTest("_", "_"); doTest("unnamed_script", null); doTest("some_dir_some_foo_js", "some/dir/some/foo.js"); doTest("some_dir_some_foo_js", "some\\dir\\some\\foo.js"); doTest("_12_foo_34_js", "12 foo 34.js"); } private void doTest(final String expectedName, final String scriptName) throws Exception { final Script script = (Script) ContextFactory.getGlobal().call( new ContextAction() { public Object run(final Context context) { return context.compileString("var f = 1", scriptName, 1, null); } }); // remove serial number String name = script.getClass().getSimpleName(); assertEquals(expectedName, name.substring(0, name.lastIndexOf('_'))); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/Bug409702Test.java0000644000175000017500000000216611314263504035060 0ustar jamespagejamespage00000000000000/** * */ package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.*; /** * See https://bugzilla.mozilla.org/show_bug.cgi?id=409702 * @author Norris Boyd */ public class Bug409702Test extends TestCase { public static abstract class Foo { public Foo() { } public abstract void a(); public abstract int b(); public static abstract class Subclass extends Foo { @Override public final void a() { } } } public void testAdapter() { final int value = 12; String source = "var instance = " + " new JavaAdapter(" + Foo.Subclass.class.getName() + "," + "{ b: function () { return " + value + "; } });" + "instance.b();"; Context cx = ContextFactory.getGlobal().enterContext(); try { Scriptable scope = cx.initStandardObjects(); Object result = cx.evaluateString(scope, source, "source", 1, null); assertEquals(new Integer(value), result); } finally { Context.exit(); } } } ././@LongLink0000000000000000000000000000014700000000000011217 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/MozillaSuiteTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/MozillaSuiteTest.ja0000755000175000017500000002160611314263504035752 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import junit.framework.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.mozilla.javascript.drivers.ShellTest; import org.mozilla.javascript.drivers.StandardTests; import org.mozilla.javascript.drivers.TestUtils; import org.mozilla.javascript.tools.shell.ShellContextFactory; /** * This JUnit suite runs the Mozilla test suite (in mozilla.org CVS * at /mozilla/js/tests). * * Not all tests in the suite are run. Since the mozilla.org tests are * designed and maintained for the SpiderMonkey engine, tests in the * suite may not pass due to feature set differences and known bugs. * To make sure that this unit test is stable in the midst of changes * to the mozilla.org suite, we maintain a list of passing tests in * files opt-1.tests, opt0.tests, and opt9.tests. This class also * implements the ability to run skipped tests, see if any pass, and * print out a script to modify the *.tests files. * (This approach doesn't handle breaking changes to existing passing * tests, but in practice that has been very rare.) * @author Norris Boyd * @author Attila Szegedi */ @RunWith(Parameterized.class) public class MozillaSuiteTest { private final File jsFile; private final int optimizationLevel; static final int[] OPT_LEVELS = { -1, 0, 9 }; public MozillaSuiteTest(File jsFile, int optimizationLevel) { this.jsFile = jsFile; this.optimizationLevel = optimizationLevel; } public static File getTestDir() throws IOException { File testDir = null; if (System.getProperty("mozilla.js.tests") != null) { testDir = new File(System.getProperty("mozilla.js.tests")); } else { URL url = StandardTests.class.getResource("."); String path = url.getFile(); int jsIndex = path.lastIndexOf("/js"); if (jsIndex == -1) { throw new IllegalStateException("You aren't running the tests "+ "from within the standard mozilla/js directory structure"); } path = path.substring(0, jsIndex + 3).replace('/', File.separatorChar); path = path.replace("%20", " "); testDir = new File(path, "tests"); } if (!testDir.isDirectory()) { throw new FileNotFoundException(testDir + " is not a directory"); } return testDir; } public static String getTestFilename(int optimizationLevel) { return "opt" + optimizationLevel + ".tests"; } public static File[] getTestFiles(int optimizationLevel) throws IOException { File testDir = getTestDir(); String[] tests = TestUtils.loadTestsFromResource( "/" + getTestFilename(optimizationLevel), null); Arrays.sort(tests); File[] files = new File[tests.length]; for (int i=0; i < files.length; i++) { files[i] = new File(testDir, tests[i]); } return files; } public static String loadFile(File f) throws IOException { int length = (int) f.length(); // don't worry about very long files char[] buf = new char[length]; new FileReader(f).read(buf, 0, length); return new String(buf); } @Parameters public static Collection mozillaSuiteValues() throws IOException { List result = new ArrayList(); int[] optLevels = OPT_LEVELS; for (int i=0; i < optLevels.length; i++) { File[] tests = getTestFiles(optLevels[i]); for (File f : tests) { result.add(new Object[] { f, optLevels[i] }); } } return result; } // move "@Parameters" to this method to test a single Mozilla test public static Collection singleDoctest() throws IOException { final String SINGLE_TEST_FILE = "e4x/Expressions/11.1.1.js"; final int SINGLE_TEST_OPTIMIZATION_LEVEL = -1; List result = new ArrayList(); File f = new File(getTestDir(), SINGLE_TEST_FILE); result.add(new Object[] { f, SINGLE_TEST_OPTIMIZATION_LEVEL }); return result; } private static class ShellTestParameters extends ShellTest.Parameters { @Override public int getTimeoutMilliseconds() { if (System.getProperty("mozilla.js.tests.timeout") != null) { return Integer.parseInt(System.getProperty( "mozilla.js.tests.timeout")); } return 10000; } } private static class JunitStatus extends ShellTest.Status { @Override public final void running(File jsFile) { // do nothing } @Override public final void failed(String s) { System.out.println("Failed: " + s); Assert.fail(s); } @Override public final void exitCodesWere(int expected, int actual) { Assert.assertEquals("Unexpected exit code", expected, actual); } @Override public final void outputWas(String s) { // Do nothing; we don't want to see the output when running JUnit // tests. } @Override public final void threw(Throwable t) { Assert.fail(ShellTest.getStackTrace(t)); } @Override public final void timedOut() { failed("Timed out."); } } @Test public void runMozillaTest() throws Exception { //System.out.println("Test \"" + jsFile + "\" running under optimization level " + optimizationLevel); final ShellContextFactory shellContextFactory = new ShellContextFactory(); shellContextFactory.setOptimizationLevel(optimizationLevel); ShellTestParameters params = new ShellTestParameters(); JunitStatus status = new JunitStatus(); ShellTest.run(shellContextFactory, jsFile, params, status); } /** * The main class will run all the test files that are *not* covered in * the *.tests files, and print out a list of all the tests that pass. */ public static void main(String[] args) throws IOException { PrintStream out = new PrintStream("fix-tests-files.sh"); try { for (int i=0; i < OPT_LEVELS.length; i++) { int optLevel = OPT_LEVELS[i]; File testDir = getTestDir(); File[] allTests = TestUtils.recursiveListFiles(testDir, new FileFilter() { public boolean accept(File pathname) { return ShellTest.DIRECTORY_FILTER.accept(pathname) || ShellTest.TEST_FILTER.accept(pathname); } }); HashSet diff = new HashSet(Arrays.asList(allTests)); File testFiles[] = getTestFiles(optLevel); diff.removeAll(Arrays.asList(testFiles)); ArrayList skippedPassed = new ArrayList(); int absolutePathLength = testDir.getAbsolutePath().length() + 1; for (File testFile: diff) { try { (new MozillaSuiteTest(testFile, optLevel)).runMozillaTest(); // strip off testDir String canonicalized = testFile.getAbsolutePath().substring(absolutePathLength); canonicalized = canonicalized.replace('\\', '/'); skippedPassed.add(canonicalized); } catch (Throwable t) { // failed, so skip } } // "skippedPassed" now contains all the tests that are currently // skipped but now pass. Print out shell commands to update the // appropriate *.tests file. if (skippedPassed.size() > 0) { out.println("cat >> " + getTestFilename(optLevel) + " < 0 ? args[0] : Undefined.instance; Object privateValue = Undefined.instance; if (thisObj instanceof ScriptableObject) { privateValue = ((ScriptableObject) thisObj).getAssociatedValue(key); } return arg.toString() + privateValue; } /** * Associate a value with the global scope and call function 'g' * defined above. */ public void testPrivateData() { Context cx = Context.enter(); try { global.associateValue(key, "bar"); Object result = cx.evaluateString(global, "g('foo');", "test source", 1, null); assertEquals("foobar", result); } finally { Context.exit(); } } } ././@LongLink0000000000000000000000000000014700000000000011217 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/GlobalParseXTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/GlobalParseXTest.ja0000644000175000017500000000353411314263504035651 0ustar jamespagejamespage00000000000000/** * */ package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.Scriptable; /** * Tests for global functions parseFloat and parseInt. * @author Marc Guillemot */ public class GlobalParseXTest extends TestCase { /** * Test for bug #501972 * https://bugzilla.mozilla.org/show_bug.cgi?id=501972 * Leading whitespaces should be ignored with following white space chars * (see ECMA spec 15.1.2.3) * , , , , , , , , , */ public void testParseFloatAndIntWhiteSpaces() { testParseFloatWhiteSpaces("\\u00A0 "); // testParseFloatWhiteSpaces("\\t "); testParseFloatWhiteSpaces("\\u00A0 "); // testParseFloatWhiteSpaces("\\u000C "); // testParseFloatWhiteSpaces("\\u000B "); // testParseFloatWhiteSpaces("\\u000D "); // testParseFloatWhiteSpaces("\\u000A "); // testParseFloatWhiteSpaces("\\u2028 "); // testParseFloatWhiteSpaces("\\u2029 "); // } private void testParseFloatWhiteSpaces(final String prefix) { assertEvaluates("789", "String(parseInt('" + prefix + "789 '))"); assertEvaluates("7.89", "String(parseFloat('" + prefix + "7.89 '))"); } private void assertEvaluates(final Object expected, final String source) { final ContextAction action = new ContextAction() { public Object run(Context cx) { final Scriptable scope = cx.initStandardObjects(); final Object rep = cx.evaluateString(scope, source, "test.js", 0, null); assertEquals(expected, rep); return null; } }; Utils.runWithAllOptimizationLevels(action); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/DoctestsTest.java0000644000175000017500000000712011314263504035440 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import java.util.*; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.drivers.TestUtils; import org.mozilla.javascript.tools.shell.Global; import static org.junit.Assert.*; /** * Run doctests in folder testsrc/doctests. * * A doctest is a test in the form of an interactive shell session; Rhino * collects and runs the inputs to the shell prompt and compares them to the * expected outputs. * * @author Norris Boyd */ @RunWith(Parameterized.class) public class DoctestsTest { static final String baseDirectory = "testsrc" + File.separator + "doctests"; static final String doctestsExtension = ".doctest"; String name; String source; int optimizationLevel; public DoctestsTest(String name, String source, int optimizationLevel) { this.name = name; this.source = source; this.optimizationLevel = optimizationLevel; } public static File[] getDoctestFiles() { return TestUtils.recursiveListFiles(new File(baseDirectory), new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(doctestsExtension); } }); } public static String loadFile(File f) throws IOException { int length = (int) f.length(); // don't worry about very long files char[] buf = new char[length]; new FileReader(f).read(buf, 0, length); return new String(buf); } @Parameters public static Collection doctestValues() throws IOException { File[] doctests = getDoctestFiles(); List result = new ArrayList(); for (File f : doctests) { String contents = loadFile(f); result.add(new Object[] { f.getName(), contents, -1 }); result.add(new Object[] { f.getName(), contents, 0 }); result.add(new Object[] { f.getName(), contents, 9 }); } return result; } // move "@Parameters" to this method to test a single doctest public static Collection singleDoctest() throws IOException { List result = new ArrayList(); File f = new File(baseDirectory, "Counter.doctest"); String contents = loadFile(f); result.add(new Object[] { f.getName(), contents, -1 }); return result; } @Test public void runDoctest() throws Exception { ContextFactory factory = ContextFactory.getGlobal(); Context cx = factory.enterContext(); try { cx.setOptimizationLevel(optimizationLevel); Global global = new Global(cx); Scriptable scope = cx.newObject(global); scope.setPrototype(global); // global.runDoctest throws an exception on any failure int testsPassed = global.runDoctest(cx, scope, source, name, 1); System.out.println(name + "(" + optimizationLevel + "): " + testsPassed + " passed."); assertTrue(testsPassed > 0); } catch (Exception ex) { System.out.println(name + "(" + optimizationLevel + "): FAILED due to "+ex); throw ex; } finally { Context.exit(); } } } ././@LongLink0000000000000000000000000000014600000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ArrayConcatTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ArrayConcatTest.jav0000644000175000017500000000167511314263504035726 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ScriptableObject; /** * Test for overloaded array concat with non-dense arg. * See https://bugzilla.mozilla.org/show_bug.cgi?id=477604 * @author Marc Guillemot */ public class ArrayConcatTest extends TestCase { public void testArrayConcat() { final String script = "var a = ['a0', 'a1'];\n" + "a[3] = 'a3';\n" + "var b = ['b1', 'b2'];\n" + "b.concat(a)"; final ContextAction action = new ContextAction() { public Object run(final Context _cx) { final ScriptableObject scope = _cx.initStandardObjects(); final Object result = _cx.evaluateString(scope, script, "test script", 0, null); assertEquals("b1,b2,a0,a1,,a3", Context.toString(result)); return null; } }; Utils.runWithAllOptimizationLevels(action); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/Evaluator.java0000644000175000017500000000156111314263504034755 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import org.mozilla.javascript.*; import java.util.Collections; import java.util.Map; public class Evaluator { public static Object eval(String source) { return eval(source, Collections.EMPTY_MAP); } public static Object eval(String source, String id, Scriptable object) { return eval(source, Collections.singletonMap(id, object)); } public static Object eval(String source, Map bindings) { Context cx = ContextFactory.getGlobal().enterContext(); try { Scriptable scope = cx.initStandardObjects(); for (String id : bindings.keySet()) { Scriptable object = bindings.get(id); object.setParentScope(scope); scope.put(id, scope, object); } return cx.evaluateString(scope, source, "source", 1, null); } finally { Context.exit(); } } } ././@LongLink0000000000000000000000000000015100000000000011212 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/PrivateAccessClass.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/PrivateAccessClass.0000644000175000017500000000711611314263504035675 0ustar jamespagejamespage00000000000000/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Attila Szegedi * David P. Caldwell * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tests; /** * A class with private/protected/package private members, to test the Rhino * feature Context.FEATURE_ENHANCED_JAVA_ACCESS, that allows bypassing Java * member access restrictions. * @author Donna Malayeri */ public class PrivateAccessClass { private PrivateAccessClass() { } PrivateAccessClass(String s) { } private PrivateAccessClass(int x) { } protected PrivateAccessClass(int x, String s) { } private static class PrivateNestedClass { private PrivateNestedClass() { } int packagePrivateInt = 0; private int privateInt = 1; protected int protectedInt = 2; } static int staticPackagePrivateInt = 0; private static int staticPrivateInt = 1; protected static int staticProtectedInt = 2; String packagePrivateString = "package private"; private String privateString = "private"; protected String protectedString = "protected"; static int staticPackagePrivateMethod() { return 0; } static private int staticPrivateMethod() { return 1; } static protected int staticProtectedMethod() { return 2; } int packagePrivateMethod() { return 3; } private int privateMethod() { return 4; } protected int protectedMethod() { return 5; } private int javaBeanProperty = 6; public boolean getterCalled = false; public boolean setterCalled = false; public int getJavaBeanProperty() { getterCalled = true; return javaBeanProperty; } public void setJavaBeanProperty(int i) { setterCalled = true; javaBeanProperty = i; } /* * Suppress warnings about unused private members. */ public int referenceToPrivateMembers() { PrivateAccessClass pac = new PrivateAccessClass(); PrivateAccessClass pac2 = new PrivateAccessClass(2); PrivateNestedClass pnc = new PrivateNestedClass(); System.out.println(privateString); pac2.privateMethod(); // to silence warning return pnc.privateInt + staticPrivateInt + staticPrivateMethod() + pac.privateMethod() + javaBeanProperty; } } ././@LongLink0000000000000000000000000000015600000000000011217 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/GeneratedMethodNameTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/GeneratedMethodName0000644000175000017500000000474011314263504035735 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tests; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; import junit.framework.TestCase; /** * Takes care that the name of the method generated for a function "looks like" the original function name. * See https://bugzilla.mozilla.org/show_bug.cgi?id=460726 * @author Marc Guillemot */ public class GeneratedMethodNameTest extends TestCase { public void testStandardFunction() throws Exception { final String scriptCode = "function myFunc() {\n" + " var m = javaNameGetter.readCurrentFunctionJavaName();\n" + " if (m != 'myFunc') throw 'got ' + m;" + "}\n" + "myFunc();"; doTest(scriptCode); } public void testFunctionDollar() throws Exception { final String scriptCode = "function $() {\n" + " var m = javaNameGetter.readCurrentFunctionJavaName();\n" + " if (m != '$') throw 'got ' + m;" + "}\n" + "$();"; doTest(scriptCode); } public void testScriptName() throws Exception { final String scriptCode = "var m = javaNameGetter.readCurrentFunctionJavaName();\n" + "if (m != 'script') throw 'got ' + m;"; doTest(scriptCode); } public void testConstructor() throws Exception { final String scriptCode = "function myFunc() {\n" + " var m = javaNameGetter.readCurrentFunctionJavaName();\n" + " if (m != 'myFunc') throw 'got ' + m;" + "}\n" + "new myFunc();"; doTest(scriptCode); } public void testAnonymousFunction() throws Exception { final String scriptCode = "var myFunc = function() {\n" + " var m = javaNameGetter.readCurrentFunctionJavaName();\n" + " if (m != 'anonymous') throw 'got ' + m;" + "}\n" + "myFunc();"; doTest(scriptCode); } public class JavaNameGetter { public String readCurrentFunctionJavaName() { final Throwable t = new RuntimeException(); // remove prefix and suffix of method name return t.getStackTrace()[8].getMethodName(). replaceFirst("_[^_]*_(.*)_[^_]*", "$1"); } } public void doTest(final String scriptCode) throws Exception { final Context cx = ContextFactory.getGlobal().enterContext(); try { Scriptable topScope = cx.initStandardObjects(); topScope.put("javaNameGetter", topScope, new JavaNameGetter()); Script script = cx.compileString(scriptCode, "myScript", 1, null); script.exec(cx, topScope); } finally { Context.exit(); } } } ././@LongLink0000000000000000000000000000015100000000000011212 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ContextFactoryTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/ContextFactoryTest.0000644000175000017500000000272011314263504035763 0ustar jamespagejamespage00000000000000/** * */ package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.RhinoException; /** * @author Norris Boyd */ public class ContextFactoryTest extends TestCase { static class MyFactory extends ContextFactory { @Override public boolean hasFeature(Context cx, int featureIndex) { switch (featureIndex) { case Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME: return true; } return super.hasFeature(cx, featureIndex); } } public void testCustomContextFactory() { ContextFactory factory = new MyFactory(); Context cx = factory.enterContext(); try { Scriptable globalScope = cx.initStandardObjects(); // Test that FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME is enabled /* TODO(stevey): fix this functionality in parser Object result = cx.evaluateString(globalScope, "var obj = {};" + "function obj.foo() { return 'bar'; }" + "obj.foo();", "test source", 1, null); assertEquals("bar", result); */ } catch (RhinoException e) { fail(e.toString()); } finally { Context.exit(); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/es5/0000755000175000017500000000000011537630013032641 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000015100000000000011212 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/es5/ObjectKeysTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/es5/ObjectKeysTest.0000644000175000017500000000146511314263504035552 0ustar jamespagejamespage00000000000000/* * Tests for the Object.keys(obj) method */ package org.mozilla.javascript.tests.es5; import org.mozilla.javascript.*; import static org.mozilla.javascript.tests.Evaluator.eval; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ObjectKeysTest { @Test public void shouldReturnOnlyEnumerablePropertiesOfArg() { NativeObject object = new NativeObject(); object.defineProperty("a", "1", ScriptableObject.EMPTY); object.defineProperty("b", "2", ScriptableObject.EMPTY); object.defineProperty("c", "3", ScriptableObject.DONTENUM); Object result = eval("Object.keys(obj)", "obj", object); NativeArray keys = (NativeArray) result; assertEquals(2, keys.getLength()); assertEquals("a", keys.get(0, keys)); assertEquals("b", keys.get(1, keys)); } } ././@LongLink0000000000000000000000000000017500000000000011220 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/es5/ObjectGetOwnPropertyDescriptorTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/es5/ObjectGetOwnPro0000644000175000017500000000243311314263504035601 0ustar jamespagejamespage00000000000000/* * Tests for the Object.getOwnPropertyDescriptor(obj, prop) method */ package org.mozilla.javascript.tests.es5; import org.mozilla.javascript.*; import static org.mozilla.javascript.tests.Evaluator.eval; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ObjectGetOwnPropertyDescriptorTest { @Test public void testContentsOfPropertyDescriptorShouldReflectAttributesOfProperty() { NativeObject descriptor; NativeObject object = new NativeObject(); object.defineProperty("a", "1", ScriptableObject.EMPTY); object.defineProperty("b", "2", ScriptableObject.DONTENUM | ScriptableObject.READONLY | ScriptableObject.PERMANENT); descriptor = (NativeObject) eval("Object.getOwnPropertyDescriptor(obj, 'a')", "obj", object); assertEquals("1", descriptor.get("value")); assertEquals(true, descriptor.get("enumerable")); assertEquals(true, descriptor.get("writable")); assertEquals(true, descriptor.get("configurable")); descriptor = (NativeObject) eval("Object.getOwnPropertyDescriptor(obj, 'b')", "obj", object); assertEquals("2", descriptor.get("value")); assertEquals(false, descriptor.get("enumerable")); assertEquals(false, descriptor.get("writable")); assertEquals(false, descriptor.get("configurable")); } } ././@LongLink0000000000000000000000000000017000000000000011213 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/es5/ObjectGetOwnPropertyNamesTest.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/es5/ObjectGetOwnPro0000644000175000017500000000144411314263504035602 0ustar jamespagejamespage00000000000000/* * Tests for the Object.getOwnPropertyNames(obj) method */ package org.mozilla.javascript.tests.es5; import org.mozilla.javascript.*; import static org.mozilla.javascript.tests.Evaluator.eval; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ObjectGetOwnPropertyNamesTest { @Test public void testShouldReturnAllPropertiesOfArg() { NativeObject object = new NativeObject(); object.defineProperty("a", "1", ScriptableObject.EMPTY); object.defineProperty("b", "2", ScriptableObject.DONTENUM); Object result = eval("Object.getOwnPropertyNames(obj)", "obj", object); NativeArray names = (NativeArray) result; assertEquals(2, names.getLength()); assertEquals("a", names.get(0, names)); assertEquals("b", names.get(1, names)); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/tests/StackTraceTest.java0000644000175000017500000000301111314263504035667 0ustar jamespagejamespage00000000000000/** * */ package org.mozilla.javascript.tests; import junit.framework.TestCase; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.Scriptable; /** * @author Marc Guillemot */ public class StackTraceTest extends TestCase { /** * As of CVS head on May, 11. 2009, stacktrace information is lost when a call to some * native function has been made. */ public void testFailureStackTrace() { final String source1 = "function f2() { throw 'hello'; }; f2();"; final String source2 = "function f2() { 'H'.toLowerCase(); throw 'hello'; }; f2();"; runWithExpectedStackTrace(source1, " at test.js (f2)\n\tat test.js\n"); // works runWithExpectedStackTrace(source2, " at test.js (f2)\n\tat test.js\n"); // fails } private void runWithExpectedStackTrace(final String _source, final String _expectedStackTrace) { final ContextAction action = new ContextAction() { public Object run(Context cx) { final Scriptable scope = cx.initStandardObjects(); try { cx.evaluateString(scope, _source, "test.js", 0, null); } catch (final JavaScriptException e) { assertEquals(_expectedStackTrace, e.getScriptStackTrace()); return null; } throw new RuntimeException("Exception expected!"); } }; Utils.runWithOptimizationLevel(action, -1); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/drivers/0000755000175000017500000000000011537630013032461 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000014600000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/drivers/StandardTests.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/drivers/StandardTests.jav0000644000175000017500000001666211314263504035761 0ustar jamespagejamespage00000000000000/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Attila Szegedi * David P. Caldwell * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.drivers; import java.io.File; import java.io.FileNotFoundException; import java.net.URL; import java.util.Arrays; import junit.framework.Assert; import junit.framework.TestCase; import junit.framework.TestSuite; import org.mozilla.javascript.tools.shell.ShellContextFactory; /** * Executes the tests in the js/tests directory, much like jsDriver.pl does. * Excludes tests found in the js/tests/rhino-n.tests file. * @author Attila Szegedi * @version $Id: StandardTests.java 4668 2009-06-30 19:01:03Z mguillem $ */ public class StandardTests extends TestSuite { public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite("Standard JavaScript tests"); File testDir = null; if (System.getProperty("mozilla.js.tests") != null) { testDir = new File(System.getProperty("mozilla.js.tests")); } else { URL url = StandardTests.class.getResource("."); String path = url.getFile(); int jsIndex = path.lastIndexOf("/js"); if(jsIndex == -1) { throw new IllegalStateException("You aren't running the tests from within the standard mozilla/js directory structure"); } path = path.substring(0, jsIndex + 3).replace('/', File.separatorChar); path = path.replace("%20", " "); testDir = new File(path, "tests"); } if(!testDir.isDirectory()) { throw new FileNotFoundException(testDir + " is not a directory"); } String[] excludes = TestUtils.loadTestsFromResource("/base.skip", null); String[] opt1Excludes = TestUtils.loadTestsFromResource("/opt1.skip", excludes); for(int i = -1; i < 2; ++i) { TestSuite optimizationLevelSuite = new TestSuite("Optimization level " + i); addSuites(optimizationLevelSuite, testDir, i == -1 ? excludes : opt1Excludes, i); suite.addTest(optimizationLevelSuite); } return suite; } private static void addSuites(TestSuite topLevel, File testDir, String[] excludes, int optimizationLevel) { File[] subdirs = testDir.listFiles(ShellTest.DIRECTORY_FILTER); Arrays.sort(subdirs); for (int i = 0; i < subdirs.length; i++) { File subdir = subdirs[i]; String name = subdir.getName(); if (TestUtils.matches(excludes, name)) { continue; } TestSuite testSuite = new TestSuite(name); addCategories(testSuite, subdir, name + "/", excludes, optimizationLevel); topLevel.addTest(testSuite); } } private static void addCategories(TestSuite suite, File suiteDir, String prefix, String[] excludes, int optimizationLevel) { File[] subdirs = suiteDir.listFiles(ShellTest.DIRECTORY_FILTER); Arrays.sort(subdirs); for (int i = 0; i < subdirs.length; i++) { File subdir = subdirs[i]; String name = subdir.getName(); TestSuite testCategory = new TestSuite(name); addTests(testCategory, subdir, prefix + name + "/", excludes, optimizationLevel); suite.addTest(testCategory); } } private static void addTests(TestSuite suite, File suiteDir, String prefix, String[] excludes, int optimizationLevel) { File[] jsFiles = suiteDir.listFiles(ShellTest.TEST_FILTER); Arrays.sort(jsFiles); for (int i = 0; i < jsFiles.length; i++) { File jsFile = jsFiles[i]; String name = jsFile.getName(); if (!TestUtils.matches(excludes, prefix + name)) { suite.addTest(new JsTestCase(jsFile, optimizationLevel)); } } } public static class JunitStatus extends ShellTest.Status { @Override public final void running(File jsFile) { // do nothing } @Override public final void failed(String s) { Assert.fail(s); } @Override public final void exitCodesWere(int expected, int actual) { Assert.assertEquals("Unexpected exit code", expected, actual); } @Override public final void outputWas(String s) { // Do nothing; we don't want to see the output when running JUnit // tests. } @Override public final void threw(Throwable t) { Assert.fail(ShellTest.getStackTrace(t)); } @Override public final void timedOut() { failed("Timed out."); } } public static final class JsTestCase extends TestCase { private final File jsFile; private final int optimizationLevel; JsTestCase(File jsFile, int optimizationLevel) { super(jsFile.getName() + (optimizationLevel == 1 ? "-compiled" : "-interpreted")); this.jsFile = jsFile; this.optimizationLevel = optimizationLevel; } @Override public int countTestCases() { return 1; } public static class ShellTestParameters extends ShellTest.Parameters { @Override public int getTimeoutMilliseconds() { if (System.getProperty("mozilla.js.tests.timeout") != null) { return Integer.parseInt(System.getProperty("mozilla.js.tests.timeout")); } return 60000; } } @Override public void runBare() throws Exception { final ShellContextFactory shellContextFactory = new ShellContextFactory(); shellContextFactory.setOptimizationLevel(optimizationLevel); ShellTestParameters params = new ShellTestParameters(); ShellTest.run(shellContextFactory, jsFile, params, new JunitStatus()); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/drivers/TestUtils.java0000644000175000017500000000506011314263504035265 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.drivers; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Arrays; import org.mozilla.javascript.ContextFactory; public class TestUtils { private static ContextFactory.GlobalSetter globalSetter; public static void GrabContextFactoryGlobalSetter() { if (globalSetter == null) { globalSetter = ContextFactory.getGlobalSetter(); } } public static void setGlobalContextFactory(ContextFactory factory) { GrabContextFactoryGlobalSetter(); globalSetter.setContextFactoryGlobal(factory); } public static File[] recursiveListFiles(File dir, FileFilter filter) { if (!dir.isDirectory()) throw new IllegalArgumentException(dir + " is not a directory"); List fileList = new ArrayList(); recursiveListFilesHelper(dir, filter, fileList); return fileList.toArray(new File[fileList.size()]); } public static void recursiveListFilesHelper(File dir, FileFilter filter, List fileList) { for (File f: dir.listFiles()) { if (f.isDirectory()) { recursiveListFilesHelper(f, filter, fileList); } else { if (filter.accept(f)) fileList.add(f); } } } public static void addTestsFromFile(String filename, List list) throws IOException { addTestsFromStream(new FileInputStream(new File(filename)), list); } public static void addTestsFromStream(InputStream in, List list) throws IOException { Properties props = new Properties(); props.load(in); for (Object obj: props.keySet()) { list.add(obj.toString()); } } public static String[] loadTestsFromResource(String resource, String[] inherited) throws IOException { List list = inherited == null ? new ArrayList() : new ArrayList(Arrays.asList(inherited)); InputStream in = StandardTests.class.getResourceAsStream(resource); if (in != null) addTestsFromStream(in, list); return list.toArray(new String[0]); } public static boolean matches(String[] patterns, String path) { for (int i=0; i Rhino: Test Results

Results of JavaScript Test Library for Rhino

Summary

Test List
Skip List
Results
Platform, JRE
Classpath
Time Execution took , ending at

Failure Details Retest List

Failure Details

Testcase path failed Bug Number XXX

				
				
				
jenkins-htmlunit-core-js-2.6-hudson-1/rhino/testsrc/org/mozilla/javascript/drivers/JsDriver.java0000644000175000017500000007250611314263504035066 0ustar jamespagejamespage00000000000000/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Java port of jsDriver.pl. * * The Initial Developer of the Original Code is * David P. Caldwell. * Portions created by David P. Caldwell are Copyright (C) * 2007 David P. Caldwell. All Rights Reserved. * * * Contributor(s): * David P. Caldwell * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.drivers; import java.io.*; import java.util.*; import org.w3c.dom.*; import org.mozilla.javascript.tools.shell.*; /** * @version $Id: JsDriver.java 4668 2009-06-30 19:01:03Z mguillem $ */ public class JsDriver { private JsDriver() { } private static String join(String[] list) { String rv = ""; for (int i=0; i list = new ArrayList(); for (int i=0; i < tests.length; i++) { if (tests[i].startsWith("@")) TestUtils.addTestsFromFile(tests[i].substring(1), list); else list.add(tests[i]); } return list.toArray(new String[0]); } private boolean matches(String path) { if (list.length == 0) return true; return TestUtils.matches(list, path); } private boolean excluded(String path) { if (skip.length == 0) return false; return TestUtils.matches(skip, path); } private void addFiles(List\n'; out += '

'; } // additional tags can be added here (i.e., "if (tags["see"])...") return out; } /** * Create an html output file * @param outputdir directory to put the file * @param htmlfile name of the file */ function CreateOutputFile(outputdir,htmlfile) { if (outputdir==null) { var outname = htmlfile; } else { var separator = Packages.java.io.File.separator; var outname = outputdir + separator + htmlfile.substring(htmlfile.lastIndexOf(separator),htmlfile.length); } print("output file: " + outname); return new File(outname); } /** * Process a javascript file. Puts the generated HTML file in the outdir * @param filename name of the javascript file * @inputdir input directory of the file (default null) */ function processJSFile(filename,inputdir) { if (debug) print("filename = " + filename + " inputdir = " + inputdir); if (!filename.match(/\.js$/)) { print("Expected filename to end in '.js'; had instead " + filename + ". I don't treat the file."); } else { if (inputdir==null) { var inname = filename; } else { var separator = Packages.java.io.File.separator; var inname = inputdir + separator + filename; } print("Processing file " + inname); var f = new File(inname); // create the output file var htmlfile = filename.replace(/\.js$/, ".html"); var out = CreateOutputFile(outputdir,htmlfile); processFile(f, filename, inputdir, out); out.close(); } } /** * Generate index files containing links to the processed javascript files * and the generated functions */ function GenerateIndex(dirname) { // construct the files index file var out = CreateOutputFile(outputdir,indexFile); // write the beginning of the file out.writeLine('

File Index - directory: ' + dirname + ''); out.writeLine('

File Index - directory: ' + dirname + '

\n'); out.writeLine(''); out.writeLine(''); out.writeLine(''); out.writeLine(''); var separator = Packages.java.io.File.separator; // sort the index file array var SortedFileArray = []; for (var fname in indexFileArray) SortedFileArray.push(fname); SortedFileArray.sort(); for (var i=0; i < SortedFileArray.length; i++) { var fname = SortedFileArray[i]; var htmlfile = fname.replace(/\.js$/, ".html"); out.writeLine('\n'); } out.writeLine('
FileDescription
' + fname + ''); if (indexFileArray[fname]) out.writeLine(indexFileArray[fname]); else out.writeLine('No comments'); out.writeLine('
'); out.close(); // construct the functions index file var out = CreateOutputFile(outputdir,indexFunction); // write the beginning of the file out.writeLine('
Function Index - directory: ' + dirname + ''); out.writeLine('

Function Index - directory: ' + dirname + '

\n'); out.writeLine(''); out.writeLine(''); out.writeLine(''); out.writeLine(''); // sort the function array var SortedFunctionArray = []; for (var functionname in indexFunctionArray) SortedFunctionArray.push(functionname); SortedFunctionArray.sort(); for (var j=0; j < SortedFunctionArray.length; j++) { var funcname = SortedFunctionArray[j]; with (indexFunctionArray[funcname]) { var outstr = ''; out.writeLine(outstr); } } out.writeLine('
FunctionFiles
' + funcname + ''; var filelst = filename.split("|"); for (var i in filelst) { var htmlfile = filelst[i].replace(/\.js$/, ".html"); outstr += '' + filelst[i] + ' '; } outstr += '
'); out.close(); } /** * prints the options for JSDoc */ function PrintOptions() { print("You can use the following options:\n"); print("-d: specify an output directory for the generated html files\n"); print("-i: processes all files in an input directory (you can specify several directories)\n"); quit(); } // Main Script // first read the arguments if (! arguments) PrintOptions(); for (var i=0; i < arguments.length; i++) { if (debug) print("argument: + \'" + arguments[i] + "\'"); if (arguments[i].match(/^\-/)) { if (String(arguments[i])=="-d"){ // output directory for the generated html files outputdir = String(arguments[i+1]); if (debug) print("outputdir: + \'" + outputdir + "\'"); i++; } else if (String(arguments[i])=="-i"){ // process all files in an input directory DirList.push(String(arguments[i+1])); if (debug) print("inputdir: + \'" + arguments[i+1] + "\'"); i++; } else { print("Unknown option: " + arguments[i] + "\n"); PrintOptions(); } } else { // we have a single file if (debug) print("file: + \'" + arguments[i] + "\'"); FileList.push(String(arguments[i])); } } // first handle the single files for (var i in FileList) processJSFile(FileList[i],null); // then handle the input directories for (var j in DirList) { var inputdir = String(DirList[j]); print("Process input directory: " + inputdir); // clean up index arrays var indexFileArray = []; var indexFunctionArray = []; // for the directory name get rid of ../../ or ..\..\ inputDirName = inputdir.replace(/\.\.\/|\.\.\\/g,""); indexFile = indexFileName + "_" + inputDirName + ".html"; indexFunction = indexFunctionName + "_" + inputDirName + ".html"; print("indexFile = " + indexFile); print("indexFunction = " + indexFunction); // read the files in the directory var DirFile = new java.io.File(inputdir); var lst = DirFile.list(); var separator = Packages.java.io.File.separator; for (var i=0; i < lst.length; i++) { processJSFile(String(lst[i]),inputdir); } // generate the index files for the input directory GenerateIndex(inputDirName); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/Matrix.java0000644000175000017500000001774211314263504026650 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ import org.mozilla.javascript.*; import java.util.List; import java.util.ArrayList; /** * Matrix: An example host object class that implements the Scriptable interface. * * Built-in JavaScript arrays don't handle multiple dimensions gracefully: the * script writer must create every array in an array of arrays. The Matrix class * takes care of that by automatically allocating arrays for every index that * is accessed. What's more, the Matrix constructor takes a integer argument * that specifies the dimension of the Matrix. If m is a Matrix with dimension 3, * then m[0] will be a Matrix with dimension 1, and m[0][0] will be an Array. * * Here's a shell session showing the Matrix object in action: *
 * js> defineClass("Matrix")
 * js> var m = new Matrix(2); // A constructor call, see "Matrix(int dimension)"
 * js> m                      // Object.toString will call "Matrix.getClassName()"
 * [object Matrix]                     
 * js> m[0][0] = 3;
 * 3
 * js> uneval(m[0]);          // an array was created automatically!
 * [3]
 * js> uneval(m[1]);          // array is created even if we don't set a value
 * []
 * js> m.dim;                 // we can access the "dim" property
 * 2
 * js> m.dim = 3;
 * 3
 * js> m.dim;                 // but not modify the "dim" property
 * 2
 * 
* * @see org.mozilla.javascript.Context * @see org.mozilla.javascript.Scriptable * * @author Norris Boyd */ public class Matrix implements Scriptable { /** * The zero-parameter constructor. * * When ScriptableObject.defineClass is called with this class, it will * construct Matrix.prototype using this constructor. */ public Matrix() { } /** * The Java constructor, also used to define the JavaScript constructor. */ public Matrix(int dimension) { if (dimension <= 0) { throw Context.reportRuntimeError( "Dimension of Matrix must be greater than zero"); } dim = dimension; list = new ArrayList(); } /** * Returns the name of this JavaScript class, "Matrix". */ public String getClassName() { return "Matrix"; } /** * Defines the "dim" property by returning true if name is * equal to "dim". *

* Defines no other properties, i.e., returns false for * all other names. * * @param name the name of the property * @param start the object where lookup began */ public boolean has(String name, Scriptable start) { return name.equals("dim"); } /** * Defines all numeric properties by returning true. * * @param index the index of the property * @param start the object where lookup began */ public boolean has(int index, Scriptable start) { return true; } /** * Get the named property. *

* Handles the "dim" property and returns NOT_FOUND for all * other names. * @param name the property name * @param start the object where the lookup began */ public Object get(String name, Scriptable start) { if (name.equals("dim")) return new Integer(dim); return NOT_FOUND; } /** * Get the indexed property. *

* Look up the element in the associated list and return * it if it exists. If it doesn't exist, create it.

* @param index the index of the integral property * @param start the object where the lookup began */ public Object get(int index, Scriptable start) { while (index >= list.size()) { list.add(null); } Object result = list.get(index); if (result != null) return result; if (dim > 2) { Matrix m = new Matrix(dim-1); m.setParentScope(getParentScope()); m.setPrototype(getPrototype()); result = m; } else { Context cx = Context.getCurrentContext(); Scriptable scope = ScriptableObject.getTopLevelScope(start); result = cx.newArray(scope, 0); } list.set(index, result); return result; } /** * Set a named property. * * We do nothing here, so all properties are effectively read-only. */ public void put(String name, Scriptable start, Object value) { } /** * Set an indexed property. * * We do nothing here, so all properties are effectively read-only. */ public void put(int index, Scriptable start, Object value) { } /** * Remove a named property. * * This method shouldn't even be called since we define all properties * as PERMANENT. */ public void delete(String id) { } /** * Remove an indexed property. * * This method shouldn't even be called since we define all properties * as PERMANENT. */ public void delete(int index) { } /** * Get prototype. */ public Scriptable getPrototype() { return prototype; } /** * Set prototype. */ public void setPrototype(Scriptable prototype) { this.prototype = prototype; } /** * Get parent. */ public Scriptable getParentScope() { return parent; } /** * Set parent. */ public void setParentScope(Scriptable parent) { this.parent = parent; } /** * Get properties. * * We return an empty array since we define all properties to be DONTENUM. */ public Object[] getIds() { return new Object[0]; } /** * Default value. * * Use the convenience method from Context that takes care of calling * toString, etc. */ public Object getDefaultValue(Class typeHint) { return "[object Matrix]"; } /** * instanceof operator. * * We mimick the normal JavaScript instanceof semantics, returning * true if this appears in value's prototype * chain. */ public boolean hasInstance(Scriptable value) { Scriptable proto = value.getPrototype(); while (proto != null) { if (proto.equals(this)) return true; proto = proto.getPrototype(); } return false; } /** * Some private data for this class. */ private int dim; private List list; private Scriptable prototype, parent; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/RunScript.java0000644000175000017500000000553011314263504027325 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ import org.mozilla.javascript.*; /** * RunScript: simplest example of controlling execution of Rhino. * * Collects its arguments from the command line, executes the * script, and prints the result. * * @author Norris Boyd */ public class RunScript { public static void main(String args[]) { // Creates and enters a Context. The Context stores information // about the execution environment of a script. Context cx = Context.enter(); try { // Initialize the standard objects (Object, Function, etc.) // This must be done before scripts can be executed. Returns // a scope object that we use in later calls. Scriptable scope = cx.initStandardObjects(); // Collect the arguments into a single string. String s = ""; for (int i=0; i < args.length; i++) { s += args[i]; } // Now evaluate the string we've colected. Object result = cx.evaluateString(scope, s, "", 1, null); // Convert the result to a string and print it. System.err.println(Context.toString(result)); } finally { // Exit from the context. Context.exit(); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/enum.js0000644000175000017500000000470211314263504026033 0ustar jamespagejamespage00000000000000/* -*- tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Patrick Beard * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ /* Implementing the interface java.util.Enumeration passing the object with JavaScript implementation directly to the constructor. This is a shorthand for JavaAdapter constructor: elements = new JavaAdapter(java.util.Enumeration, { index: 0, elements: array, hasMoreElements: function ... nextElement: function ... }); */ // an array to enumerate. var array = [0, 1, 2]; // create an array enumeration. var elements = new java.util.Enumeration({ index: 0, elements: array, hasMoreElements: function() { return (this.index < this.elements.length); }, nextElement: function() { return this.elements[this.index++]; } }); // now print out the array by enumerating through the Enumeration while (elements.hasMoreElements()) print(elements.nextElement()); jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/RunScript4.java0000644000175000017500000000551511314263504027414 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ import org.mozilla.javascript.*; /** * RunScript4: Execute scripts in an environment that includes the * example Counter class. * * @author Norris Boyd */ public class RunScript4 { public static void main(String args[]) throws Exception { Context cx = Context.enter(); try { Scriptable scope = cx.initStandardObjects(); // Use the Counter class to define a Counter constructor // and prototype in JavaScript. ScriptableObject.defineClass(scope, Counter.class); // Create an instance of Counter and assign it to // the top-level variable "myCounter". This is // equivalent to the JavaScript code // myCounter = new Counter(7); Object[] arg = { new Integer(7) }; Scriptable myCounter = cx.newObject(scope, "Counter", arg); scope.put("myCounter", scope, myCounter); String s = ""; for (int i=0; i < args.length; i++) { s += args[i]; } Object result = cx.evaluateString(scope, s, "", 1, null); System.err.println(Context.toString(result)); } finally { Context.exit(); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/NervousText.html0000644000175000017500000000440311314263504027723 0ustar jamespagejamespage00000000000000 This is the NervousText applet in javascript:
The test assumes that applet code is generated with:
java -classpath js.jar org.mozilla.javascript.tools.jsc.Main \
  -extends java.applet.Applet \
  -implements java.lang.Runnable \
  NervousText.js
and the resulting 2 classes, NervousText.class extending java.applet.Applet and implementing java.lang.Runnable and NervousText1.class which represents compiled JavaScript code, are placed in the same directory as NervousText.html.

The test also assumes that js.jar from Rhino distribution is available in the same directory. jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/Shell.java0000644000175000017500000003011311314263504026436 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ import org.mozilla.javascript.*; import java.io.*; /** * The shell program. * * Can execute scripts interactively or in batch mode at the command line. * An example of controlling the JavaScript engine. * * @author Norris Boyd */ public class Shell extends ScriptableObject { private static final long serialVersionUID = -5638074146250193112L; @Override public String getClassName() { return "global"; } /** * Main entry point. * * Process arguments as would a normal Java program. Also * create a new Context and associate it with the current thread. * Then set up the execution environment and begin to * execute scripts. */ public static void main(String args[]) { // Associate a new Context with this thread Context cx = Context.enter(); try { // Initialize the standard objects (Object, Function, etc.) // This must be done before scripts can be executed. Shell shell = new Shell(); cx.initStandardObjects(shell); // Define some global functions particular to the shell. Note // that these functions are not part of ECMA. String[] names = { "print", "quit", "version", "load", "help" }; shell.defineFunctionProperties(names, Shell.class, ScriptableObject.DONTENUM); args = processOptions(cx, args); // Set up "arguments" in the global scope to contain the command // line arguments after the name of the script to execute Object[] array; if (args.length == 0) { array = new Object[0]; } else { int length = args.length - 1; array = new Object[length]; System.arraycopy(args, 1, array, 0, length); } Scriptable argsObj = cx.newArray(shell, array); shell.defineProperty("arguments", argsObj, ScriptableObject.DONTENUM); shell.processSource(cx, args.length == 0 ? null : args[0]); } finally { Context.exit(); } } /** * Parse arguments. */ public static String[] processOptions(Context cx, String args[]) { for (int i=0; i < args.length; i++) { String arg = args[i]; if (!arg.startsWith("-")) { String[] result = new String[args.length - i]; for (int j=i; j < args.length; j++) result[j-i] = args[j]; return result; } if (arg.equals("-version")) { if (++i == args.length) usage(arg); double d = Context.toNumber(args[i]); if (d != d) usage(arg); cx.setLanguageVersion((int) d); continue; } usage(arg); } return new String[0]; } /** * Print a usage message. */ private static void usage(String s) { p("Didn't understand \"" + s + "\"."); p("Valid arguments are:"); p("-version 100|110|120|130|140|150|160|170"); System.exit(1); } /** * Print a help message. * * This method is defined as a JavaScript function. */ public void help() { p(""); p("Command Description"); p("======= ==========="); p("help() Display usage and help messages. "); p("defineClass(className) Define an extension using the Java class"); p(" named with the string argument. "); p(" Uses ScriptableObject.defineClass(). "); p("load(['foo.js', ...]) Load JavaScript source files named by "); p(" string arguments. "); p("loadClass(className) Load a class named by a string argument."); p(" The class must be a script compiled to a"); p(" class file. "); p("print([expr ...]) Evaluate and print expressions. "); p("quit() Quit the shell. "); p("version([number]) Get or set the JavaScript version number."); p(""); } /** * Print the string values of its arguments. * * This method is defined as a JavaScript function. * Note that its arguments are of the "varargs" form, which * allows it to handle an arbitrary number of arguments * supplied to the JavaScript function. * */ public static void print(Context cx, Scriptable thisObj, Object[] args, Function funObj) { for (int i=0; i < args.length; i++) { if (i > 0) System.out.print(" "); // Convert the arbitrary JavaScript value into a string form. String s = Context.toString(args[i]); System.out.print(s); } System.out.println(); } /** * Quit the shell. * * This only affects the interactive mode. * * This method is defined as a JavaScript function. */ public void quit() { quitting = true; } /** * Get and set the language version. * * This method is defined as a JavaScript function. */ public static double version(Context cx, Scriptable thisObj, Object[] args, Function funObj) { double result = cx.getLanguageVersion(); if (args.length > 0) { double d = Context.toNumber(args[0]); cx.setLanguageVersion((int) d); } return result; } /** * Load and execute a set of JavaScript source files. * * This method is defined as a JavaScript function. * */ public static void load(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Shell shell = (Shell)getTopLevelScope(thisObj); for (int i = 0; i < args.length; i++) { shell.processSource(cx, Context.toString(args[i])); } } /** * Evaluate JavaScript source. * * @param cx the current context * @param filename the name of the file to compile, or null * for interactive mode. */ private void processSource(Context cx, String filename) { if (filename == null) { BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); String sourceName = ""; int lineno = 1; boolean hitEOF = false; do { int startline = lineno; System.err.print("js> "); System.err.flush(); try { String source = ""; // Collect lines of source to compile. while(true) { String newline; newline = in.readLine(); if (newline == null) { hitEOF = true; break; } source = source + newline + "\n"; lineno++; // Continue collecting as long as more lines // are needed to complete the current // statement. stringIsCompilableUnit is also // true if the source statement will result in // any error other than one that might be // resolved by appending more source. if (cx.stringIsCompilableUnit(source)) break; } Object result = cx.evaluateString(this, source, sourceName, startline, null); if (result != Context.getUndefinedValue()) { System.err.println(Context.toString(result)); } } catch (WrappedException we) { // Some form of exception was caught by JavaScript and // propagated up. System.err.println(we.getWrappedException().toString()); we.printStackTrace(); } catch (EvaluatorException ee) { // Some form of JavaScript error. System.err.println("js: " + ee.getMessage()); } catch (JavaScriptException jse) { // Some form of JavaScript error. System.err.println("js: " + jse.getMessage()); } catch (IOException ioe) { System.err.println(ioe.toString()); } if (quitting) { // The user executed the quit() function. break; } } while (!hitEOF); System.err.println(); } else { FileReader in = null; try { in = new FileReader(filename); } catch (FileNotFoundException ex) { Context.reportError("Couldn't open file \"" + filename + "\"."); return; } try { // Here we evalute the entire contents of the file as // a script. Text is printed only if the print() function // is called. cx.evaluateReader(this, in, filename, 1, null); } catch (WrappedException we) { System.err.println(we.getWrappedException().toString()); we.printStackTrace(); } catch (EvaluatorException ee) { System.err.println("js: " + ee.getMessage()); } catch (JavaScriptException jse) { System.err.println("js: " + jse.getMessage()); } catch (IOException ioe) { System.err.println(ioe.toString()); } finally { try { in.close(); } catch (IOException ioe) { System.err.println(ioe.toString()); } } } } private static void p(String s) { System.out.println(s); } private boolean quitting; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/unique.js0000644000175000017500000000416411314263504026377 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // unique.js: read the contents of a file and print out the unique lines defineClass("File") // "arguments[0]" refers to the first argument at the command line to the // script, if present. If not present, "arguments[0]" will be undefined, // which will cause f to read from System.in. var f = new File(arguments[0]); var o = {} var line; while ((line = f.readLine()) != null) { // Use JavaScript objects' inherent nature as an associative // array to provide uniqueness o[line] = true; } for (i in o) { print(i); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/CounterTest.java0000644000175000017500000000550111314263504027651 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ import org.mozilla.javascript.*; /** * An example illustrating how to create a JavaScript object and retrieve * properties and call methods. *

* Output should be: *

 * count = 0
 * count = 1
 * resetCount
 * count = 0
 * 
*/ public class CounterTest { public static void main(String[] args) throws Exception { Context cx = Context.enter(); try { Scriptable scope = cx.initStandardObjects(); ScriptableObject.defineClass(scope, Counter.class); Scriptable testCounter = cx.newObject(scope, "Counter"); Object count = ScriptableObject.getProperty(testCounter, "count"); System.out.println("count = " + count); count = ScriptableObject.getProperty(testCounter, "count"); System.out.println("count = " + count); ScriptableObject.callMethod(testCounter, "resetCount", new Object[0]); System.out.println("resetCount"); count = ScriptableObject.getProperty(testCounter, "count"); System.out.println("count = " + count); } finally { Context.exit(); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/RunScript3.java0000644000175000017500000000627511314263504027417 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ import org.mozilla.javascript.*; /** * RunScript3: Example of using JavaScript objects * * Collects its arguments from the command line, executes the * script, and then ... * * @author Norris Boyd */ public class RunScript3 { public static void main(String args[]) { Context cx = Context.enter(); try { Scriptable scope = cx.initStandardObjects(); // Collect the arguments into a single string. String s = ""; for (int i=0; i < args.length; i++) { s += args[i]; } // Now evaluate the string we've collected. We'll ignore the result. cx.evaluateString(scope, s, "", 1, null); // Print the value of variable "x" Object x = scope.get("x", scope); if (x == Scriptable.NOT_FOUND) { System.out.println("x is not defined."); } else { System.out.println("x = " + Context.toString(x)); } // Call function "f('my arg')" and print its result. Object fObj = scope.get("f", scope); if (!(fObj instanceof Function)) { System.out.println("f is undefined or not a function."); } else { Object functionArgs[] = { "my arg" }; Function f = (Function)fObj; Object result = f.call(cx, scope, scope, functionArgs); String report = "f('my args') = " + Context.toString(result); System.out.println(report); } } finally { Context.exit(); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/PrimitiveWrapFactory.java0000644000175000017500000000554511314263504031534 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ import org.mozilla.javascript.*; /** * An example WrapFactory that can be used to avoid wrapping of Java types * that can be converted to ECMA primitive values. * So java.lang.String is mapped to ECMA string, all java.lang.Numbers are * mapped to ECMA numbers, and java.lang.Booleans are mapped to ECMA booleans * instead of being wrapped as objects. Additionally java.lang.Character is * converted to ECMA string with length 1. * Other types have the default behavior. *

* Note that calling "new java.lang.String('foo')" in JavaScript with this * wrap factory enabled will still produce a wrapped Java object since the * WrapFactory.wrapNewObject method is not overridden. *

* The PrimitiveWrapFactory is enabled on a Context by calling setWrapFactory * on that context. */ public class PrimitiveWrapFactory extends WrapFactory { @Override public Object wrap(Context cx, Scriptable scope, Object obj, Class staticType) { if (obj instanceof String || obj instanceof Number || obj instanceof Boolean) { return obj; } else if (obj instanceof Character) { char[] a = { ((Character)obj).charValue() }; return new String(a); } return super.wrap(cx, scope, obj, staticType); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/Control.java0000644000175000017500000000733511314263504027021 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ import org.mozilla.javascript.*; /** * Example of controlling the JavaScript execution engine. * * We evaluate a script and then manipulate the result. * */ public class Control { /** * Main entry point. * * Process arguments as would a normal Java program. Also * create a new Context and associate it with the current thread. * Then set up the execution environment and begin to * execute scripts. */ public static void main(String[] args) { Context cx = Context.enter(); try { // Set version to JavaScript1.2 so that we get object-literal style // printing instead of "[object Object]" cx.setLanguageVersion(Context.VERSION_1_2); // Initialize the standard objects (Object, Function, etc.) // This must be done before scripts can be executed. Scriptable scope = cx.initStandardObjects(); // Now we can evaluate a script. Let's create a new object // using the object literal notation. Object result = cx.evaluateString(scope, "obj = {a:1, b:['x','y']}", "MySource", 1, null); Scriptable obj = (Scriptable) scope.get("obj", scope); // Should print "obj == result" (Since the result of an assignment // expression is the value that was assigned) System.out.println("obj " + (obj == result ? "==" : "!=") + " result"); // Should print "obj.a == 1" System.out.println("obj.a == " + obj.get("a", obj)); Scriptable b = (Scriptable) obj.get("b", obj); // Should print "obj.b[0] == x" System.out.println("obj.b[0] == " + b.get(0, b)); // Should print "obj.b[1] == y" System.out.println("obj.b[1] == " + b.get(1, b)); // Should print {a:1, b:["x", "y"]} Function fn = (Function) ScriptableObject.getProperty(obj, "toString"); System.out.println(fn.call(cx, scope, obj, new Object[0])); } finally { Context.exit(); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/checkParam.js0000644000175000017500000001010311314263504027115 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ /** * checkParam.js * * The files given as arguments on the command line are assumed to be * Java source code files. This program checks to see that the @param * tags in the documentation comments match with the parameters for * the associated Java methods. *

* Any errors found are reported. * */ defineClass("File") // Return true if "str" ends with "suffix". function stringEndsWith(str, suffix) { return str.substring(str.length - suffix.length) == suffix; } /** * Perform processing once the end of a documentation comment is seen. * * Look for a parameter list following the end of the comment and * collect the parameters and compare to the @param entries. * Report any discrepancies. * @param f the current file * @param a an array of parameters from @param comments * @param line the string containing the comment end (in case the * parameters are on the same line) */ function processCommentEnd(f, a, line) { while (line != null && !line.match(/\(/)) line = f.readLine(); while (line != null && !line.match(/\)/)) line += f.readLine(); if (line === null) return; var m = line.match(/\(([^\)]+)\)/); var args = m ? m[1].split(",") : []; if (a.length != args.length) { print('"' + f.name + '"; line ' + f.lineNumber + ' mismatch: had a different number' + ' of @param entries and parameters.'); } else { for (var i=0; i < a.length; i++) { if (!stringEndsWith(args[i], a[i])) { print('"' + f.name + '"; line ' + f.lineNumber + ' mismatch: had "' + a[i] + '" and "' + args[i] + '".'); break; } } } } /** * Process the given file, looking for mismatched @param lists and * parameter lists. * @param f the file to process */ function processFile(f) { var line; var m; var i = 0; var a = []; outer: while ((line = f.readLine()) != null) { if (line.match(/@param/)) { while (m = line.match(/@param[ ]+([^ ]+)/)) { a[i++] = m[1]; line = f.readLine(); if (line == null) break outer; } } if (i != 0 && line.match(/\*\//)) { processCommentEnd(f, a, line); i = 0; a = []; } } if (i != 0) { print('"' + f.name + '"; line ' + f.lineNumber + ' missing parameters at end of file.'); } } // main script: process each file in arguments list for (var i=0; i < arguments.length; i++) { var filename = String(arguments[i]); print("Checking " + filename + "..."); var f = new File(filename); processFile(f); } print("done."); jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/NervousText.js0000644000175000017500000000624411314263504027400 0ustar jamespagejamespage00000000000000/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // The Java "NervousText" example ported to JavaScript. // Compile using java org.mozilla.javascript.tools.jsc.Main -extends java.applet.Applet -implements java.lang.Runnable NervousText.js /* Adapted from Java code by Daniel Wyszynski Center for Applied Large-Scale Computing (CALC) 04-12-95 Test of text animation. kwalrath: Changed string; added thread suspension. 5-9-95 */ var Font = java.awt.Font; var Thread = java.lang.Thread; var separated; var s = null; var killme = null; var i; var x_coord = 0, y_coord = 0; var num; var speed=35; var counter =0; var threadSuspended = false; //added by kwalrath function init() { this.resize(150,50); this.setFont(new Font("TimesRoman",Font.BOLD,36)); s = this.getParameter("text"); if (s == null) { s = "Rhino"; } separated = s.split(''); } function start() { if(killme == null) { killme = new java.lang.Thread(java.lang.Runnable(this)); killme.start(); } } function stop() { killme = null; } function run() { while (killme != null) { try {Thread.sleep(100);} catch (e){} this.repaint(); } killme = null; } function paint(g) { for(i=0;i", 1, null); System.err.println(Context.toString(result)); } finally { Context.exit(); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/Foo.java0000644000175000017500000001376511314263504026130 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ import org.mozilla.javascript.*; /** * An example host object class. * * Here's a shell session showing the Foo object in action: *

 * js> defineClass("Foo")
 * js> foo = new Foo();         A constructor call, see Foo below.
 * [object Foo]                 The "Foo" here comes from getClassName.
 * js> foo.counter;             The counter property is defined by the defineProperty
 * 0                            call below and implemented by the getCounter
 * js> foo.counter;             method below.
 * 1
 * js> foo.counter;
 * 2
 * js> foo.resetCounter();      Results in a call to resetCounter.
 * js> foo.counter;             Now the counter has been reset.
 * 0
 * js> foo.counter;
 * 1
 * js> bar = new Foo(37);       Create a new instance.
 * [object Foo]
 * js> bar.counter;             This instance's counter is distinct from
 * 37                           the other instance's counter.
 * js> foo.varargs(3, "hi");    Calls varargs.
 * this = [object Foo]; args = [3, hi]
 * js> foo[7] = 34;             Since we extended ScriptableObject, we get
 * 34                           all the behavior of a JavaScript object
 * js> foo.a = 23;              for free.
 * 23
 * js> foo.a + foo[7];
 * 57
 * js>
 * 
* * @see org.mozilla.javascript.Context * @see org.mozilla.javascript.Scriptable * @see org.mozilla.javascript.ScriptableObject * * @author Norris Boyd */ public class Foo extends ScriptableObject { private static final long serialVersionUID = -3833489808933339159L; /** * The zero-parameter constructor. * * When Context.defineClass is called with this class, it will * construct Foo.prototype using this constructor. */ public Foo() { } /** * The Java method defining the JavaScript Foo constructor. * * Takes an initial value for the counter property. * Note that in the example Shell session above, we didn't * supply a argument to the Foo constructor. This means that * the Undefined value is used as the value of the argument, * and when the argument is converted to an integer, Undefined * becomes 0. */ public Foo(int counterStart) { counter = counterStart; } /** * Returns the name of this JavaScript class, "Foo". */ @Override public String getClassName() { return "Foo"; } /** * The Java method defining the JavaScript resetCounter function. * * Resets the counter to 0. */ public void jsFunction_resetCounter() { counter = 0; } /** * The Java method implementing the getter for the counter property. *

* If "setCounter" had been defined in this class, the runtime would * call the setter when the property is assigned to. */ public int jsGet_counter() { return counter++; } /** * An example of a variable-arguments method. * * All variable arguments methods must have the same number and * types of parameters, and must be static.

* @param cx the Context of the current thread * @param thisObj the JavaScript 'this' value. * @param args the array of arguments for this call * @param funObj the function object of the invoked JavaScript function * This value is useful to compute a scope using * Context.getTopLevelScope(). * @return computes the string values and types of 'this' and * of each of the supplied arguments and returns them in a string. * * @see org.mozilla.javascript.ScriptableObject#getTopLevelScope */ public static Object jsFunction_varargs(Context cx, Scriptable thisObj, Object[] args, Function funObj) { StringBuffer buf = new StringBuffer(); buf.append("this = "); buf.append(Context.toString(thisObj)); buf.append("; args = ["); for (int i=0; i < args.length; i++) { buf.append(Context.toString(args[i])); if (i+1 != args.length) buf.append(", "); } buf.append("]"); return buf.toString(); } /** * A piece of private data for this class. */ private int counter; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/examples/DynamicScopes.java0000644000175000017500000001654611314263504030146 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ import org.mozilla.javascript.*; /** * Example of controlling the JavaScript with multiple scopes and threads. */ public class DynamicScopes { static boolean useDynamicScope; static class MyFactory extends ContextFactory { @Override protected boolean hasFeature(Context cx, int featureIndex) { if (featureIndex == Context.FEATURE_DYNAMIC_SCOPE) { return useDynamicScope; } return super.hasFeature(cx, featureIndex); } } static { ContextFactory.initGlobal(new MyFactory()); } /** * Main entry point. * * Set up the shared scope and then spawn new threads that execute * relative to that shared scope. Try to run functions with and * without dynamic scope to see the effect. * * The expected output is *

     * sharedScope
     * nested:sharedScope
     * sharedScope
     * nested:sharedScope
     * sharedScope
     * nested:sharedScope
     * thread0
     * nested:thread0
     * thread1
     * nested:thread1
     * thread2
     * nested:thread2
     * 
* The final three lines may be permuted in any order depending on * thread scheduling. */ public static void main(String[] args) { Context cx = Context.enter(); try { // Precompile source only once String source = "" +"var x = 'sharedScope';\n" +"function f() { return x; }\n" // Dynamic scope works with nested function too +"function initClosure(prefix) {\n" +" return function test() { return prefix+x; }\n" +"}\n" +"var closure = initClosure('nested:');\n" +""; Script script = cx.compileString(source, "sharedScript", 1, null); useDynamicScope = false; runScripts(cx, script); useDynamicScope = true; runScripts(cx, script); } finally { Context.exit(); } } static void runScripts(Context cx, Script script) { // Initialize the standard objects (Object, Function, etc.) // This must be done before scripts can be executed. The call // returns a new scope that we will share. ScriptableObject sharedScope = cx.initStandardObjects(null, true); // Now we can execute the precompiled script against the scope // to define x variable and f function in the shared scope. script.exec(cx, sharedScope); // Now we spawn some threads that execute a script that calls the // function 'f'. The scope chain looks like this: //
        //            ------------------                ------------------
        //           | per-thread scope | -prototype-> |   shared scope   |
        //            ------------------                ------------------
        //                    ^
        //                    |
        //               parentScope
        //                    |
        //            ------------------
        //           | f's activation   |
        //            ------------------
        // 
// Both the shared scope and the per-thread scope have variables 'x' // defined in them. If 'f' is compiled with dynamic scope enabled, // the 'x' from the per-thread scope will be used. Otherwise, the 'x' // from the shared scope will be used. The 'x' defined in 'g' (which // calls 'f') should not be seen by 'f'. final int threadCount = 3; Thread[] t = new Thread[threadCount]; for (int i=0; i < threadCount; i++) { String source2 = "" +"function g() { var x = 'local'; return f(); }\n" +"java.lang.System.out.println(g());\n" +"function g2() { var x = 'local'; return closure(); }\n" +"java.lang.System.out.println(g2());\n" +""; t[i] = new Thread(new PerThread(sharedScope, source2, "thread" + i)); } for (int i=0; i < threadCount; i++) t[i].start(); // Don't return in this thread until all the spawned threads have // completed. for (int i=0; i < threadCount; i++) { try { t[i].join(); } catch (InterruptedException e) { } } } static class PerThread implements Runnable { PerThread(Scriptable sharedScope, String source, String x) { this.sharedScope = sharedScope; this.source = source; this.x = x; } public void run() { // We need a new Context for this thread. Context cx = Context.enter(); try { // We can share the scope. Scriptable threadScope = cx.newObject(sharedScope); threadScope.setPrototype(sharedScope); // We want "threadScope" to be a new top-level // scope, so set its parent scope to null. This // means that any variables created by assignments // will be properties of "threadScope". threadScope.setParentScope(null); // Create a JavaScript property of the thread scope named // 'x' and save a value for it. threadScope.put("x", threadScope, x); cx.evaluateString(threadScope, source, "threadScript", 1, null); } finally { Context.exit(); } } private Scriptable sharedScope; private String source; private String x; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/0000755000175000017500000000000011537630013025520 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/build.xml0000644000175000017500000000436411314263504027350 0ustar jamespagejamespage00000000000000 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/0000755000175000017500000000000011537630012026306 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/0000755000175000017500000000000011537630012027755 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/0000755000175000017500000000000011537630013032124 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/PropertyException.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/PropertyException.j0000644000175000017500000000365611314263504036014 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; /** * @deprecated This exception is no longer thrown by Rhino runtime. */ public class PropertyException extends RuntimeException { static final long serialVersionUID = -8221564865490676219L; public PropertyException(String detail) { super(detail); } } ././@LongLink0000000000000000000000000000015400000000000011215 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/NotAFunctionException.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/NotAFunctionExcepti0000644000175000017500000000367511314263504035753 0ustar jamespagejamespage00000000000000 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; /** * @deprecated The exception is no longer thrown by Rhino runtime as * {@link EvaluatorException} is used instead. */ public class NotAFunctionException extends RuntimeException { static final long serialVersionUID = 6461524852170711724L; public NotAFunctionException() { } } ././@LongLink0000000000000000000000000000015700000000000011220 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/ClassDefinitionException.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/ClassDefinitionExce0000644000175000017500000000373211314263504035737 0ustar jamespagejamespage00000000000000 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; /** * @deprecated The exception is no longer thrown by Rhino runtime as * {@link EvaluatorException} is used instead. */ public class ClassDefinitionException extends RuntimeException { static final long serialVersionUID = -5637830967241712746L; public ClassDefinitionException(String detail) { super(detail); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/0000755000175000017500000000000011537630012032723 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/0000755000175000017500000000000011537630012033664 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/0000755000175000017500000000000011537630013035476 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000016200000000000011214 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/Namespace.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/N0000644000175000017500000002201011314263504035611 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ethan Hugg * Terry Lucas * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml.impl.xmlbeans; import org.mozilla.javascript.*; /** * Class Namespace * */ class Namespace extends IdScriptableObject { static final long serialVersionUID = -5765755238131301744L; private static final Object NAMESPACE_TAG = "Namespace"; private XMLLibImpl lib; private String prefix; private String uri; public Namespace(XMLLibImpl lib, String uri) { super(lib.globalScope(), lib.namespacePrototype); if (uri == null) throw new IllegalArgumentException(); this.lib = lib; this.prefix = (uri.length() == 0) ? "" : null; this.uri = uri; } public Namespace(XMLLibImpl lib, String prefix, String uri) { super(lib.globalScope(), lib.namespacePrototype); if (uri == null) throw new IllegalArgumentException(); if (uri.length() == 0) { // prefix should be "" for empty uri if (prefix == null) throw new IllegalArgumentException(); if (prefix.length() != 0) throw new IllegalArgumentException(); } this.lib = lib; this.prefix = prefix; this.uri = uri; } public void exportAsJSClass(boolean sealed) { exportAsJSClass(MAX_PROTOTYPE_ID, lib.globalScope(), sealed); } /** * * @return */ public String uri() { return uri; } /** * * @return */ public String prefix() { return prefix; } /** * * @return */ public String toString () { return uri(); } /** * * @return */ public String toLocaleString () { return toString(); } public boolean equals(Object obj) { if (!(obj instanceof Namespace)) return false; return equals((Namespace)obj); } protected Object equivalentValues(Object value) { if (!(value instanceof Namespace)) return Scriptable.NOT_FOUND; boolean result = equals((Namespace)value); return result ? Boolean.TRUE : Boolean.FALSE; } private boolean equals(Namespace n) { return uri().equals(n.uri()); } /** * * @return */ public String getClassName () { return "Namespace"; } /** * * @param hint * @return */ public Object getDefaultValue (Class hint) { return uri(); } // #string_id_map# private static final int Id_prefix = 1, Id_uri = 2, MAX_INSTANCE_ID = 2; protected int getMaxInstanceId() { return super.getMaxInstanceId() + MAX_INSTANCE_ID; } protected int findInstanceIdInfo(String s) { int id; // #generated# Last update: 2004-07-20 19:50:50 CEST L0: { id = 0; String X = null; int s_length = s.length(); if (s_length==3) { X="uri";id=Id_uri; } else if (s_length==6) { X="prefix";id=Id_prefix; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# if (id == 0) return super.findInstanceIdInfo(s); int attr; switch (id) { case Id_prefix: case Id_uri: attr = PERMANENT | READONLY; break; default: throw new IllegalStateException(); } return instanceIdInfo(attr, super.getMaxInstanceId() + id); } // #/string_id_map# protected String getInstanceIdName(int id) { switch (id - super.getMaxInstanceId()) { case Id_prefix: return "prefix"; case Id_uri: return "uri"; } return super.getInstanceIdName(id); } protected Object getInstanceIdValue(int id) { switch (id - super.getMaxInstanceId()) { case Id_prefix: if (prefix == null) return Undefined.instance; return prefix; case Id_uri: return uri; } return super.getInstanceIdValue(id); } // #string_id_map# private static final int Id_constructor = 1, Id_toString = 2, Id_toSource = 3, MAX_PROTOTYPE_ID = 3; protected int findPrototypeId(String s) { int id; // #generated# Last update: 2004-08-21 12:07:01 CEST L0: { id = 0; String X = null; int c; int s_length = s.length(); if (s_length==8) { c=s.charAt(3); if (c=='o') { X="toSource";id=Id_toSource; } else if (c=='t') { X="toString";id=Id_toString; } } else if (s_length==11) { X="constructor";id=Id_constructor; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# return id; } // #/string_id_map# protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=2; s="constructor"; break; case Id_toString: arity=0; s="toString"; break; case Id_toSource: arity=0; s="toSource"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(NAMESPACE_TAG, id, s, arity); } public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(NAMESPACE_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); switch (id) { case Id_constructor: return jsConstructor(cx, (thisObj == null), args); case Id_toString: return realThis(thisObj, f).toString(); case Id_toSource: return realThis(thisObj, f).js_toSource(); } throw new IllegalArgumentException(String.valueOf(id)); } private Namespace realThis(Scriptable thisObj, IdFunctionObject f) { if(!(thisObj instanceof Namespace)) throw incompatibleCallError(f); return (Namespace)thisObj; } private Object jsConstructor(Context cx, boolean inNewExpr, Object[] args) { if (!inNewExpr && args.length == 1) { return lib.castToNamespace(cx, args[0]); } if (args.length == 0) { return lib.constructNamespace(cx); } else if (args.length == 1) { return lib.constructNamespace(cx, args[0]); } else { return lib.constructNamespace(cx, args[0], args[1]); } } private String js_toSource() { StringBuffer sb = new StringBuffer(); sb.append('('); toSourceImpl(prefix, uri, sb); sb.append(')'); return sb.toString(); } static void toSourceImpl(String prefix, String uri, StringBuffer sb) { sb.append("new Namespace("); if (uri.length() == 0) { if (!"".equals(prefix)) throw new IllegalArgumentException(prefix); } else { sb.append('\''); if (prefix != null) { sb.append(ScriptRuntime.escapeString(prefix, '\'')); sb.append("', '"); } sb.append(ScriptRuntime.escapeString(uri, '\'')); sb.append('\''); } sb.append(')'); } } ././@LongLink0000000000000000000000000000017000000000000011213 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/LogicalEquality.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/L0000644000175000017500000002313411314263504035617 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ethan Hugg * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml.impl.xmlbeans; import org.apache.xmlbeans.XmlCursor; import java.util.*; public class LogicalEquality { public static boolean nodesEqual(XmlCursor xmlOne, XmlCursor xmlTwo) { boolean result = false; if (xmlOne.isStartdoc()) { xmlOne.toFirstContentToken(); } if (xmlTwo.isStartdoc()) { xmlTwo.toFirstContentToken(); } if (xmlOne.currentTokenType() == xmlTwo.currentTokenType()) { if (xmlOne.isEnddoc()) { // Both empty result = true; } else if (xmlOne.isAttr()) { result = attributesEqual(xmlOne, xmlTwo); } else if (xmlOne.isText()) { result = textNodesEqual(xmlOne, xmlTwo); } else if (xmlOne.isComment()) { result = commentsEqual(xmlOne, xmlTwo); } else if (xmlOne.isProcinst()) { result = processingInstructionsEqual(xmlOne, xmlTwo); } else if (xmlOne.isStart()) { // Compare root elements result = elementsEqual(xmlOne, xmlTwo); } } return result; } private static boolean elementsEqual(XmlCursor xmlOne, XmlCursor xmlTwo) { boolean result = true; if (!qnamesEqual(xmlOne.getName(), xmlTwo.getName())) { result = false; } else { // These filter out empty text nodes. nextToken(xmlOne); nextToken(xmlTwo); do { if (xmlOne.currentTokenType() != xmlTwo.currentTokenType()) { // Not same token result = false; break; } else if (xmlOne.isEnd()) { // Done with this element, step over end break; } else if (xmlOne.isEnddoc()) { // Shouldn't get here break; } else if (xmlOne.isAttr()) { // This one will move us to the first non-attr token. result = attributeListsEqual(xmlOne, xmlTwo); } else { if (xmlOne.isText()) { result = textNodesEqual(xmlOne, xmlTwo); } else if (xmlOne.isComment()) { result = commentsEqual(xmlOne, xmlTwo); } else if (xmlOne.isProcinst()) { result = processingInstructionsEqual(xmlOne, xmlTwo); } else if (xmlOne.isStart()) { result = elementsEqual(xmlOne, xmlTwo); } else { //XML.log("Unknown token type" + xmlOne.currentTokenType()); } // These filter out empty text nodes. nextToken(xmlOne); nextToken(xmlTwo); } } while(result); } return result; } /** * * @param xmlOne * @param xmlTwo * @return */ private static boolean attributeListsEqual(XmlCursor xmlOne, XmlCursor xmlTwo) { boolean result = true; TreeMap mapOne = loadAttributeMap(xmlOne); TreeMap mapTwo = loadAttributeMap(xmlTwo); if (mapOne.size() != mapTwo.size()) { result = false; } else { Set keysOne = mapOne.keySet(); Set keysTwo = mapTwo.keySet(); Iterator itOne = keysOne.iterator(); Iterator itTwo = keysTwo.iterator(); while (result && itOne.hasNext()) { String valueOne = (String) itOne.next(); String valueTwo = (String) itTwo.next(); if (!valueOne.equals(valueTwo)) { result = false; } else { javax.xml.namespace.QName qnameOne = (javax.xml.namespace.QName) mapOne.get(valueOne); javax.xml.namespace.QName qnameTwo = (javax.xml.namespace.QName) mapTwo.get(valueTwo); if (!qnamesEqual(qnameOne, qnameTwo)) { result = false; } } } } return result; } /** * * @param xml * @return */ private static TreeMap loadAttributeMap(XmlCursor xml) { TreeMap result = new TreeMap(); while (xml.isAttr()) { result.put(xml.getTextValue(), xml.getName()); nextToken(xml); } return result; } /** * * @param xmlOne * @param xmlTwo * @return */ private static boolean attributesEqual(XmlCursor xmlOne, XmlCursor xmlTwo) { boolean result = false; if (xmlOne.isAttr() && xmlTwo.isAttr()) { if (qnamesEqual(xmlOne.getName(), xmlTwo.getName())) { if (xmlOne.getTextValue().equals(xmlTwo.getTextValue())) { result = true; } } } return result; } /** * * @param xmlOne * @param xmlTwo * @return */ private static boolean textNodesEqual(XmlCursor xmlOne, XmlCursor xmlTwo) { boolean result = false; if (xmlOne.isText() && xmlTwo.isText()) { if (xmlOne.getChars().equals(xmlTwo.getChars())) { result = true; } } return result; } /** * * @param xmlOne * @param xmlTwo * @return */ private static boolean commentsEqual(XmlCursor xmlOne, XmlCursor xmlTwo) { boolean result = false; if (xmlOne.isComment() && xmlTwo.isComment()) { if (xmlOne.getTextValue().equals(xmlTwo.getTextValue())) { result = true; } } return result; } /** * * @param xmlOne * @param xmlTwo * @return */ private static boolean processingInstructionsEqual(XmlCursor xmlOne, XmlCursor xmlTwo) { boolean result = false; if (xmlOne.isProcinst() && xmlTwo.isProcinst()) { if (qnamesEqual(xmlOne.getName(), xmlTwo.getName())) { if (xmlOne.getTextValue().equals(xmlTwo.getTextValue())) { result = true; } } } return result; } /** * * @param qnameOne * @param qnameTwo * @return */ private static boolean qnamesEqual(javax.xml.namespace.QName qnameOne, javax.xml.namespace.QName qnameTwo) { boolean result = false; if (qnameOne.getNamespaceURI().equals(qnameTwo.getNamespaceURI())) { if (qnameOne.getLocalPart().equals(qnameTwo.getLocalPart())) { return true; } } return result; } /** * filter out empty textNodes here * * @param xml */ private static void nextToken(XmlCursor xml) { do { xml.toNextToken(); if (!xml.isText()) { // Not a text node break; } else if (xml.getChars().trim().length() > 0) { // Text node is not empty break; } } while (true); } } ././@LongLink0000000000000000000000000000016300000000000011215 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/XMLLibImpl.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/X0000644000175000017500000005545411314263504035645 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml.impl.xmlbeans; import java.io.Serializable; import org.mozilla.javascript.*; import org.mozilla.javascript.xml.*; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlObject; public final class XMLLibImpl extends XMLLib implements Serializable { private static final long serialVersionUID = 1L; private Scriptable globalScope; XML xmlPrototype; XMLList xmlListPrototype; Namespace namespacePrototype; QName qnamePrototype; // Environment settings... boolean ignoreComments; boolean ignoreProcessingInstructions; boolean ignoreWhitespace; boolean prettyPrinting; int prettyIndent; Scriptable globalScope() { return globalScope; } private XMLLibImpl(Scriptable globalScope) { this.globalScope = globalScope; defaultSettings(); } public static void init(Context cx, Scriptable scope, boolean sealed) { // To force LinkageError if XmlObject is not available XmlObject.class.getName(); XMLLibImpl lib = new XMLLibImpl(scope); XMLLib bound = lib.bindToScope(scope); if (bound == lib) { lib.exportToScope(sealed); } } private void exportToScope(boolean sealed) { xmlPrototype = XML.createEmptyXML(this); xmlListPrototype = new XMLList(this); namespacePrototype = new Namespace(this, "", ""); qnamePrototype = new QName(this, "", "", ""); xmlPrototype.exportAsJSClass(sealed); xmlListPrototype.exportAsJSClass(sealed); namespacePrototype.exportAsJSClass(sealed); qnamePrototype.exportAsJSClass(sealed); } void defaultSettings() { ignoreComments = true; ignoreProcessingInstructions = true; ignoreWhitespace = true; prettyPrinting = true; prettyIndent = 2; } XMLName toAttributeName(Context cx, Object nameValue) { String uri; String localName; if (nameValue instanceof String) { uri = ""; localName = (String)nameValue; } else if (nameValue instanceof XMLName) { XMLName xmlName = (XMLName)nameValue; if (!xmlName.isAttributeName()) { xmlName.setAttributeName(); } return xmlName; } else if (nameValue instanceof QName) { QName qname = (QName)nameValue; uri = qname.uri(); localName = qname.localName(); } else if (nameValue instanceof Boolean || nameValue instanceof Number || nameValue == Undefined.instance || nameValue == null) { throw badXMLName(nameValue); } else { uri = ""; localName = ScriptRuntime.toString(nameValue); } XMLName xmlName = XMLName.formProperty(uri, localName); xmlName.setAttributeName(); return xmlName; } private static RuntimeException badXMLName(Object value) { String msg; if (value instanceof Number) { msg = "Can not construct XML name from number: "; } else if (value instanceof Boolean) { msg = "Can not construct XML name from boolean: "; } else if (value == Undefined.instance || value == null) { msg = "Can not construct XML name from "; } else { throw new IllegalArgumentException(value.toString()); } return ScriptRuntime.typeError(msg+ScriptRuntime.toString(value)); } XMLName toXMLName(Context cx, Object nameValue) { XMLName result; if (nameValue instanceof XMLName) { result = (XMLName)nameValue; } else if (nameValue instanceof QName) { QName qname = (QName)nameValue; result = XMLName.formProperty(qname.uri(), qname.localName()); } else if (nameValue instanceof String) { result = toXMLNameFromString(cx, (String)nameValue); } else if (nameValue instanceof Boolean || nameValue instanceof Number || nameValue == Undefined.instance || nameValue == null) { throw badXMLName(nameValue); } else { String name = ScriptRuntime.toString(nameValue); result = toXMLNameFromString(cx, name); } return result; } /** * If value represents Uint32 index, make it available through * ScriptRuntime.lastUint32Result(cx) and return null. * Otherwise return the same value as toXMLName(cx, value). */ XMLName toXMLNameOrIndex(Context cx, Object value) { XMLName result; if (value instanceof XMLName) { result = (XMLName)value; } else if (value instanceof String) { String str = (String)value; long test = ScriptRuntime.testUint32String(str); if (test >= 0) { ScriptRuntime.storeUint32Result(cx, test); result = null; } else { result = toXMLNameFromString(cx, str); } } else if (value instanceof Number) { double d = ((Number)value).doubleValue(); long l = (long)d; if (l == d && 0 <= l && l <= 0xFFFFFFFFL) { ScriptRuntime.storeUint32Result(cx, l); result = null; } else { throw badXMLName(value); } } else if (value instanceof QName) { QName qname = (QName)value; String uri = qname.uri(); boolean number = false; result = null; if (uri != null && uri.length() == 0) { // Only in this case qname.toString() can resemble uint32 long test = ScriptRuntime.testUint32String(uri); if (test >= 0) { ScriptRuntime.storeUint32Result(cx, test); number = true; } } if (!number) { result = XMLName.formProperty(uri, qname.localName()); } } else if (value instanceof Boolean || value == Undefined.instance || value == null) { throw badXMLName(value); } else { String str = ScriptRuntime.toString(value); long test = ScriptRuntime.testUint32String(str); if (test >= 0) { ScriptRuntime.storeUint32Result(cx, test); result = null; } else { result = toXMLNameFromString(cx, str); } } return result; } XMLName toXMLNameFromString(Context cx, String name) { if (name == null) throw new IllegalArgumentException(); int l = name.length(); if (l != 0) { char firstChar = name.charAt(0); if (firstChar == '*') { if (l == 1) { return XMLName.formStar(); } } else if (firstChar == '@') { XMLName xmlName = XMLName.formProperty("", name.substring(1)); xmlName.setAttributeName(); return xmlName; } } String uri = getDefaultNamespaceURI(cx); return XMLName.formProperty(uri, name); } Namespace constructNamespace(Context cx, Object uriValue) { String prefix; String uri; if (uriValue instanceof Namespace) { Namespace ns = (Namespace)uriValue; prefix = ns.prefix(); uri = ns.uri(); } else if (uriValue instanceof QName) { QName qname = (QName)uriValue; uri = qname.uri(); if (uri != null) { prefix = qname.prefix(); } else { uri = qname.toString(); prefix = null; } } else { uri = ScriptRuntime.toString(uriValue); prefix = (uri.length() == 0) ? "" : null; } return new Namespace(this, prefix, uri); } Namespace castToNamespace(Context cx, Object namescapeObj) { if (namescapeObj instanceof Namespace) { return (Namespace)namescapeObj; } return constructNamespace(cx, namescapeObj); } Namespace constructNamespace(Context cx) { return new Namespace(this, "", ""); } public Namespace constructNamespace(Context cx, Object prefixValue, Object uriValue) { String prefix; String uri; if (uriValue instanceof QName) { QName qname = (QName)uriValue; uri = qname.uri(); if (uri == null) { uri = qname.toString(); } } else { uri = ScriptRuntime.toString(uriValue); } if (uri.length() == 0) { if (prefixValue == Undefined.instance) { prefix = ""; } else { prefix = ScriptRuntime.toString(prefixValue); if (prefix.length() != 0) { throw ScriptRuntime.typeError( "Illegal prefix '"+prefix+"' for 'no namespace'."); } } } else if (prefixValue == Undefined.instance) { prefix = ""; } else if (!isXMLName(cx, prefixValue)) { prefix = ""; } else { prefix = ScriptRuntime.toString(prefixValue); } return new Namespace(this, prefix, uri); } String getDefaultNamespaceURI(Context cx) { String uri = ""; if (cx == null) { cx = Context.getCurrentContext(); } if (cx != null) { Object ns = ScriptRuntime.searchDefaultNamespace(cx); if (ns != null) { if (ns instanceof Namespace) { uri = ((Namespace)ns).uri(); } else { // Should not happen but for now it could // due to bad searchDefaultNamespace implementation. } } } return uri; } Namespace getDefaultNamespace(Context cx) { if (cx == null) { cx = Context.getCurrentContext(); if (cx == null) { return namespacePrototype; } } Namespace result; Object ns = ScriptRuntime.searchDefaultNamespace(cx); if (ns == null) { result = namespacePrototype; } else { if (ns instanceof Namespace) { result = (Namespace)ns; } else { // Should not happen but for now it could // due to bad searchDefaultNamespace implementation. result = namespacePrototype; } } return result; } QName castToQName(Context cx, Object qnameValue) { if (qnameValue instanceof QName) { return (QName)qnameValue; } return constructQName(cx, qnameValue); } QName constructQName(Context cx, Object nameValue) { QName result; if (nameValue instanceof QName) { QName qname = (QName)nameValue; result = new QName(this, qname.uri(), qname.localName(), qname.prefix()); } else { String localName = ScriptRuntime.toString(nameValue); result = constructQNameFromString(cx, localName); } return result; } /** * Optimized version of constructQName for String type */ QName constructQNameFromString(Context cx, String localName) { if (localName == null) throw new IllegalArgumentException(); String uri; String prefix; if ("*".equals(localName)) { uri = null; prefix = null; } else { Namespace ns = getDefaultNamespace(cx); uri = ns.uri(); prefix = ns.prefix(); } return new QName(this, uri, localName, prefix); } QName constructQName(Context cx, Object namespaceValue, Object nameValue) { String uri; String localName; String prefix; if (nameValue instanceof QName) { QName qname = (QName)nameValue; localName = qname.localName(); } else { localName = ScriptRuntime.toString(nameValue); } Namespace ns; if (namespaceValue == Undefined.instance) { if ("*".equals(localName)) { ns = null; } else { ns = getDefaultNamespace(cx); } } else if (namespaceValue == null) { ns = null; } else if (namespaceValue instanceof Namespace) { ns = (Namespace)namespaceValue; } else { ns = constructNamespace(cx, namespaceValue); } if (ns == null) { uri = null; prefix = null; } else { uri = ns.uri(); prefix = ns.prefix(); } return new QName(this, uri, localName, prefix); } Object addXMLObjects(Context cx, XMLObject obj1, XMLObject obj2) { XMLList listToAdd = new XMLList(this); if (obj1 instanceof XMLList) { XMLList list1 = (XMLList)obj1; if (list1.length() == 1) { listToAdd.addToList(list1.item(0)); } else { // Might be xmlFragment + xmlFragment + xmlFragment + ...; // then the result will be an XMLList which we want to be an // rValue and allow it to be assigned to an lvalue. listToAdd = new XMLList(this, obj1); } } else { listToAdd.addToList(obj1); } if (obj2 instanceof XMLList) { XMLList list2 = (XMLList)obj2; for (int i = 0; i < list2.length(); i++) { listToAdd.addToList(list2.item(i)); } } else if (obj2 instanceof XML) { listToAdd.addToList(obj2); } return listToAdd; } // // // Overriding XMLLib methods // // /** * See E4X 13.1.2.1. */ public boolean isXMLName(Context cx, Object nameObj) { String name; try { name = ScriptRuntime.toString(nameObj); } catch (EcmaError ee) { if ("TypeError".equals(ee.getName())) { return false; } throw ee; } // See http://w3.org/TR/xml-names11/#NT-NCName int length = name.length(); if (length != 0) { if (isNCNameStartChar(name.charAt(0))) { for (int i = 1; i != length; ++i) { if (!isNCNameChar(name.charAt(i))) { return false; } } return true; } } return false; } private static boolean isNCNameStartChar(int c) { if ((c & ~0x7F) == 0) { // Optimize for ASCII and use A..Z < _ < a..z if (c >= 'a') { return c <= 'z'; } else if (c >= 'A') { if (c <= 'Z') { return true; } return c == '_'; } } else if ((c & ~0x1FFF) == 0) { return (0xC0 <= c && c <= 0xD6) || (0xD8 <= c && c <= 0xF6) || (0xF8 <= c && c <= 0x2FF) || (0x370 <= c && c <= 0x37D) || 0x37F <= c; } return (0x200C <= c && c <= 0x200D) || (0x2070 <= c && c <= 0x218F) || (0x2C00 <= c && c <= 0x2FEF) || (0x3001 <= c && c <= 0xD7FF) || (0xF900 <= c && c <= 0xFDCF) || (0xFDF0 <= c && c <= 0xFFFD) || (0x10000 <= c && c <= 0xEFFFF); } private static boolean isNCNameChar(int c) { if ((c & ~0x7F) == 0) { // Optimize for ASCII and use - < . < 0..9 < A..Z < _ < a..z if (c >= 'a') { return c <= 'z'; } else if (c >= 'A') { if (c <= 'Z') { return true; } return c == '_'; } else if (c >= '0') { return c <= '9'; } else { return c == '-' || c == '.'; } } else if ((c & ~0x1FFF) == 0) { return isNCNameStartChar(c) || c == 0xB7 || (0x300 <= c && c <= 0x36F); } return isNCNameStartChar(c) || (0x203F <= c && c <= 0x2040); } XMLName toQualifiedName(Context cx, Object namespaceValue, Object nameValue) { // This is duplication of constructQName(cx, namespaceValue, nameValue) // but for XMLName String uri; String localName; if (nameValue instanceof QName) { QName qname = (QName)nameValue; localName = qname.localName(); } else { localName = ScriptRuntime.toString(nameValue); } Namespace ns; if (namespaceValue == Undefined.instance) { if ("*".equals(localName)) { ns = null; } else { ns = getDefaultNamespace(cx); } } else if (namespaceValue == null) { ns = null; } else if (namespaceValue instanceof Namespace) { ns = (Namespace)namespaceValue; } else { ns = constructNamespace(cx, namespaceValue); } if (ns == null) { uri = null; } else { uri = ns.uri(); } return XMLName.formProperty(uri, localName); } public Ref nameRef(Context cx, Object name, Scriptable scope, int memberTypeFlags) { if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) == 0) { // should only be called foir cases like @name or @[expr] throw Kit.codeBug(); } XMLName xmlName = toAttributeName(cx, name); return xmlPrimaryReference(cx, xmlName, scope); } public Ref nameRef(Context cx, Object namespace, Object name, Scriptable scope, int memberTypeFlags) { XMLName xmlName = toQualifiedName(cx, namespace, name); if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) != 0) { if (!xmlName.isAttributeName()) { xmlName.setAttributeName(); } } return xmlPrimaryReference(cx, xmlName, scope); } private Ref xmlPrimaryReference(Context cx, XMLName xmlName, Scriptable scope) { XMLObjectImpl xmlObj; XMLObjectImpl firstXmlObject = null; for (;;) { // XML object can only present on scope chain as a wrapper // of XMLWithScope if (scope instanceof XMLWithScope) { xmlObj = (XMLObjectImpl)scope.getPrototype(); if (xmlObj.hasXMLProperty(xmlName)) { break; } if (firstXmlObject == null) { firstXmlObject = xmlObj; } } scope = scope.getParentScope(); if (scope == null) { xmlObj = firstXmlObject; break; } } // xmlObj == null corresponds to undefined as the target of // the reference if (xmlObj != null) { xmlName.initXMLObject(xmlObj); } return xmlName; } /** * Escapes the reserved characters in a value of an attribute * * @param value Unescaped text * @return The escaped text */ public String escapeAttributeValue(Object value) { String text = ScriptRuntime.toString(value); if (text.length() == 0) return ""; XmlObject xo = XmlObject.Factory.newInstance(); XmlCursor cursor = xo.newCursor(); cursor.toNextToken(); cursor.beginElement("a"); cursor.insertAttributeWithValue("a", text); cursor.dispose(); String elementText = xo.toString(); int begin = elementText.indexOf('"'); int end = elementText.lastIndexOf('"'); return elementText.substring(begin + 1, end); } /** * Escapes the reserved characters in a value of a text node * * @param value Unescaped text * @return The escaped text */ public String escapeTextValue(Object value) { if (value instanceof XMLObjectImpl) { return ((XMLObjectImpl)value).toXMLString(0); } String text = ScriptRuntime.toString(value); if (text.length() == 0) return text; XmlObject xo = XmlObject.Factory.newInstance(); XmlCursor cursor = xo.newCursor(); cursor.toNextToken(); cursor.beginElement("a"); cursor.insertChars(text); cursor.dispose(); String elementText = xo.toString(); int begin = elementText.indexOf('>') + 1; int end = elementText.lastIndexOf('<'); return (begin < end) ? elementText.substring(begin, end) : ""; } public Object toDefaultXmlNamespace(Context cx, Object uriValue) { return constructNamespace(cx, uriValue); } } ././@LongLink0000000000000000000000000000015400000000000011215 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/XML.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/X0000644000175000017500000023256211314263504035642 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ethan Hugg * Terry Lucas * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml.impl.xmlbeans; import java.io.Serializable; import java.util.*; import org.mozilla.javascript.*; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor.XmlBookmark; import org.apache.xmlbeans.XmlCursor.TokenType; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; class XML extends XMLObjectImpl { static final long serialVersionUID = -630969919086449092L; final static class XScriptAnnotation extends XmlBookmark implements Serializable { private static final long serialVersionUID = 1L; javax.xml.namespace.QName _name; XML _xScriptXML; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Constructurs // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// XScriptAnnotation (XmlCursor curs) { _name = curs.getName(); } } /** * */ final static class NamespaceDeclarations { private int _prefixIdx; private StringBuffer _namespaceDecls; private String _defaultNSURI; NamespaceDeclarations (XmlCursor curs) { _prefixIdx = 0; _namespaceDecls = new StringBuffer(); skipNonElements(curs); _defaultNSURI = curs.namespaceForPrefix(""); if (isAnyDefaultNamespace()) { addDecl("", _defaultNSURI); } } private void addDecl (String prefix, String ns) { _namespaceDecls.append((prefix.length() > 0 ? "declare namespace " + prefix : "default element namespace") + " = \"" + ns + "\"" + "\n"); } String getNextPrefix (String ns) { String prefix = "NS" + _prefixIdx++; _namespaceDecls.append("declare namespace " + prefix + " = " + "\"" + ns + "\"" + "\n"); return prefix; } boolean isAnyDefaultNamespace () { return _defaultNSURI != null ?_defaultNSURI.length() > 0 : false; } String getDeclarations() { return _namespaceDecls.toString(); } } // Fields //static final XML prototype = new XML(); private XScriptAnnotation _anno; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Constructors // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * * @param anno */ private XML(XMLLibImpl lib, XScriptAnnotation anno) { super(lib, lib.xmlPrototype); _anno = anno; _anno._xScriptXML = this; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Public factories for creating a XScript XML object given an XBean cursor. // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static XML createEmptyXML(XMLLibImpl lib) { XScriptAnnotation anno; XmlObject xo = XmlObject.Factory.newInstance(); XmlCursor curs = xo.newCursor(); try { anno = new XScriptAnnotation(curs); curs.setBookmark(anno); } finally { curs.dispose(); } return new XML(lib, anno); } private static XML createXML (XMLLibImpl lib, XmlCursor curs) { if (curs.currentTokenType().isStartdoc()) { curs.toFirstContentToken(); } XScriptAnnotation anno = findAnnotation(curs); return new XML(lib, anno); } /** * Special constructor for making an attribute * */ private static XML createAttributeXML(XMLLibImpl lib, XmlCursor cursor) { if (!cursor.isAttr()) throw new IllegalArgumentException(); XScriptAnnotation anno = new XScriptAnnotation(cursor); cursor.setBookmark(anno); return new XML(lib, anno); } /** * * @param qname * @param value * @return */ static XML createTextElement(XMLLibImpl lib, javax.xml.namespace.QName qname, String value) { XScriptAnnotation anno; XmlObject xo = XmlObject.Factory.newInstance(); XmlCursor cursor = xo.newCursor(); try { cursor.toNextToken(); cursor.beginElement(qname.getLocalPart(), qname.getNamespaceURI()); //if(namespace.length() > 0) // cursor.insertNamespace("", namespace); cursor.insertChars(value); cursor.toStartDoc(); cursor.toNextToken(); anno = new XScriptAnnotation(cursor); cursor.setBookmark(anno); } finally { cursor.dispose(); } return new XML(lib, anno); } static XML createFromXmlObject(XMLLibImpl lib, XmlObject xo) { XScriptAnnotation anno; XmlCursor curs = xo.newCursor(); if (curs.currentTokenType().isStartdoc()) { curs.toFirstContentToken(); } try { anno = new XScriptAnnotation(curs); curs.setBookmark(anno); } finally { curs.dispose(); } return new XML(lib, anno); } static XML createFromJS(XMLLibImpl lib, Object inputObject) { XmlObject xo; boolean isText = false; String frag; if (inputObject == null || inputObject == Undefined.instance) { frag = ""; } else if (inputObject instanceof XMLObjectImpl) { // todo: faster way for XMLObjects? frag = ((XMLObjectImpl) inputObject).toXMLString(0); } else { if (inputObject instanceof Wrapper) { Object wrapped = ((Wrapper)inputObject).unwrap(); if (wrapped instanceof XmlObject) { return createFromXmlObject(lib, (XmlObject)wrapped); } } frag = ScriptRuntime.toString(inputObject); } if (frag.trim().startsWith("<>")) { throw ScriptRuntime.typeError("Invalid use of XML object anonymous tags <>."); } if (frag.indexOf("<") == -1) { // Must be solo text node, wrap in XML fragment isText = true; frag = "" + frag + ""; } XmlOptions options = new XmlOptions(); if (lib.ignoreComments) { options.put(XmlOptions.LOAD_STRIP_COMMENTS); } if (lib.ignoreProcessingInstructions) { options.put(XmlOptions.LOAD_STRIP_PROCINSTS); } if (lib.ignoreWhitespace) { options.put(XmlOptions.LOAD_STRIP_WHITESPACE); } try { xo = XmlObject.Factory.parse(frag, options); // Apply the default namespace Context cx = Context.getCurrentContext(); String defaultURI = lib.getDefaultNamespaceURI(cx); if(defaultURI.length() > 0) { XmlCursor cursor = xo.newCursor(); boolean isRoot = true; while(!cursor.toNextToken().isEnddoc()) { if(!cursor.isStart()) continue; // Check if this element explicitly sets the // default namespace boolean defaultNSDeclared = false; cursor.push(); while(cursor.toNextToken().isAnyAttr()) { if(cursor.isNamespace()) { if(cursor.getName().getLocalPart().length() == 0) { defaultNSDeclared = true; break; } } } cursor.pop(); if(defaultNSDeclared) { cursor.toEndToken(); continue; } // Check if this element's name is in no namespace javax.xml.namespace.QName qname = cursor.getName(); if(qname.getNamespaceURI().length() == 0) { // Change the namespace qname = new javax.xml.namespace.QName(defaultURI, qname.getLocalPart()); cursor.setName(qname); } if(isRoot) { // Declare the default namespace cursor.push(); cursor.toNextToken(); cursor.insertNamespace("", defaultURI); cursor.pop(); isRoot = false; } } cursor.dispose(); } } catch (XmlException xe) { /* todo need to handle namespace prefix not found in XML look for namespace type in the scope change. String errorMsg = "Use of undefined namespace prefix: "; String msg = xe.getError().getMessage(); if (msg.startsWith(errorMsg)) { String prefix = msg.substring(errorMsg.length()); } */ String errMsg = xe.getMessage(); if (errMsg.equals("error: Unexpected end of file after null")) { // Create an empty document. xo = XmlObject.Factory.newInstance(); } else { throw ScriptRuntime.typeError(xe.getMessage()); } } catch (Throwable e) { // todo: TLL Catch specific exceptions during parse. throw ScriptRuntime.typeError("Not Parsable as XML"); } XmlCursor curs = xo.newCursor(); if (curs.currentTokenType().isStartdoc()) { curs.toFirstContentToken(); } if (isText) { // Move it to point to the text node curs.toFirstContentToken(); } XScriptAnnotation anno; try { anno = new XScriptAnnotation(curs); curs.setBookmark(anno); } finally { curs.dispose(); } return new XML(lib, anno); } static XML getFromAnnotation(XMLLibImpl lib, XScriptAnnotation anno) { if (anno._xScriptXML == null) { anno._xScriptXML = new XML(lib, anno); } return anno._xScriptXML; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Private functions: // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * * @param curs * @return */ private static TokenType skipNonElements (XmlCursor curs) { TokenType tt = curs.currentTokenType(); while (tt.isComment() || tt.isProcinst()) { tt = curs.toNextToken(); } return tt; } /** * * @param curs * @return */ protected static XScriptAnnotation findAnnotation(XmlCursor curs) { XmlBookmark anno = curs.getBookmark(XScriptAnnotation.class); if (anno == null) { anno = new XScriptAnnotation(curs); curs.setBookmark(anno); } return (XScriptAnnotation)anno; } /** * * @return */ private XmlOptions getOptions() { XmlOptions options = new XmlOptions(); if (lib.ignoreComments) { options.put(XmlOptions.LOAD_STRIP_COMMENTS); } if (lib.ignoreProcessingInstructions) { options.put(XmlOptions.LOAD_STRIP_PROCINSTS); } if (lib.ignoreWhitespace) { options.put(XmlOptions.LOAD_STRIP_WHITESPACE); } if (lib.prettyPrinting) { options.put(XmlOptions.SAVE_PRETTY_PRINT, null); options.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, new Integer(lib.prettyIndent)); } return options; } /** * * @param cursor * @param opts * @return */ private static String dumpNode(XmlCursor cursor, XmlOptions opts) { if (cursor.isText()) return cursor.getChars(); if (cursor.isFinish()) return ""; cursor.push(); boolean wanRawText = cursor.isStartdoc() && !cursor.toFirstChild(); cursor.pop(); return wanRawText ? cursor.getTextValue() : cursor.xmlText( opts ); } /** * * @return */ private XmlCursor newCursor () { XmlCursor curs; if (_anno != null) { curs = _anno.createCursor(); if (curs == null) { // Orphaned case. XmlObject doc = XmlObject.Factory.newInstance(); curs = doc.newCursor(); if (_anno._name != null) { curs.toNextToken(); curs.insertElement(_anno._name); curs.toPrevSibling(); } curs.setBookmark(_anno); } } else { XmlObject doc = XmlObject.Factory.newInstance(); curs = doc.newCursor(); } return curs; } /* * fUseStartDoc used by child(int index) the index is at startDoc is the element at the top-level * otherwise we always want to drill in. */ private boolean moveToChild(XmlCursor curs, long index, boolean fFirstChild, boolean fUseStartDoc) { if (index < 0) throw new IllegalArgumentException(); long idxChild = 0; if (!fUseStartDoc && curs.currentTokenType().isStartdoc()) { // We always move to the children of the top node. // todo: This assumes that we want have multiple top-level nodes. Which we should be able tohave. curs.toFirstContentToken(); } TokenType tt = curs.toFirstContentToken(); if (!tt.isNone() && !tt.isEnd()) { while (true) { if (index == idxChild) { return true; } tt = curs.currentTokenType(); if (tt.isText()) { curs.toNextToken(); } else if (tt.isStart()) { // Need to do this we want to be pointing at the text if that after the end token. curs.toEndToken(); curs.toNextToken(); } else if (tt.isComment() || tt.isProcinst()) { continue; } else { break; } idxChild++; } } else if (fFirstChild && index == 0) { // Drill into where first child would be. // curs.toFirstContentToken(); return true; } return false; } /** * * @return */ XmlCursor.TokenType tokenType() { XmlCursor.TokenType result; XmlCursor curs = newCursor(); if (curs.isStartdoc()) { curs.toFirstContentToken(); } result = curs.currentTokenType(); curs.dispose(); return result; } /** * * @param srcCurs * @param destCurs * @param fDontMoveIfSame * @return */ private boolean moveSrcToDest (XmlCursor srcCurs, XmlCursor destCurs, boolean fDontMoveIfSame) { boolean fMovedSomething = true; TokenType tt; do { if (fDontMoveIfSame && srcCurs.isInSameDocument(destCurs) && (srcCurs.comparePosition(destCurs) == 0)) { // If the source and destination are pointing at the same place then there's nothing to move. fMovedSomething = false; break; } // todo ***TLL*** Use replaceContents (when added) and eliminate children removes (see above todo). if (destCurs.currentTokenType().isStartdoc()) { destCurs.toNextToken(); } // todo ***TLL*** Can Eric support notion of copy instead of me copying then moving??? XmlCursor copyCurs = copy(srcCurs); copyCurs.moveXml(destCurs); copyCurs.dispose(); tt = srcCurs.currentTokenType(); } while (!tt.isStart() && !tt.isEnd() && !tt.isEnddoc()); return fMovedSomething; } /** * * @param cursToCopy * @return */ private XmlCursor copy (XmlCursor cursToCopy) { XmlObject xo = XmlObject.Factory.newInstance(); XmlCursor copyCurs = null; if (cursToCopy.currentTokenType().isText()) { try { // Try just as a textnode, to do that we need to wrap the text in a special fragment tag // that is not visible from the XmlCursor. copyCurs = XmlObject.Factory.parse("" + cursToCopy.getChars() + "").newCursor(); if (!cursToCopy.toNextSibling()) { if (cursToCopy.currentTokenType().isText()) { cursToCopy.toNextToken(); // It's not an element it's text so skip it. } } } catch (Exception ex) { throw ScriptRuntime.typeError(ex.getMessage()); } } else { copyCurs = xo.newCursor(); copyCurs.toFirstContentToken(); if (cursToCopy.currentTokenType() == XmlCursor.TokenType.STARTDOC) { cursToCopy.toNextToken(); } cursToCopy.copyXml(copyCurs); if (!cursToCopy.toNextSibling()) // If element skip element. { if (cursToCopy.currentTokenType().isText()) { cursToCopy.toNextToken(); // It's not an element it's text so skip it. } } } copyCurs.toStartDoc(); copyCurs.toFirstContentToken(); return copyCurs; } private static final int APPEND_CHILD = 1; private static final int PREPEND_CHILD = 2; /** * * @param curs * @param xmlToInsert */ private void insertChild(XmlCursor curs, Object xmlToInsert) { if (xmlToInsert == null || xmlToInsert instanceof Undefined) { // Do nothing } else if (xmlToInsert instanceof XmlCursor) { moveSrcToDest((XmlCursor)xmlToInsert, curs, true); } else if (xmlToInsert instanceof XML) { XML xmlValue = (XML) xmlToInsert; // If it's an attribute, then change to text node if (xmlValue.tokenType() == XmlCursor.TokenType.ATTR) { insertChild(curs, xmlValue.toString()); } else { XmlCursor cursToInsert = ((XML) xmlToInsert).newCursor(); moveSrcToDest(cursToInsert, curs, true); cursToInsert.dispose(); } } else if (xmlToInsert instanceof XMLList) { XMLList list = (XMLList) xmlToInsert; for (int i = 0; i < list.length(); i++) { insertChild(curs, list.item(i)); } } else { // Convert to string and make XML out of it String xmlStr = ScriptRuntime.toString(xmlToInsert); XmlObject xo = XmlObject.Factory.newInstance(); // Create an empty document. XmlCursor sourceCurs = xo.newCursor(); sourceCurs.toNextToken(); // To hold the text. sourceCurs.insertChars(xmlStr); sourceCurs.toPrevToken(); // Call us again with the cursor. moveSrcToDest(sourceCurs, curs, true); } } /** * * @param childToMatch * @param xmlToInsert * @param addToType */ private void insertChild(XML childToMatch, Object xmlToInsert, int addToType) { XmlCursor curs = newCursor(); TokenType tt = curs.currentTokenType(); XmlCursor xmlChildCursor = childToMatch.newCursor(); if (tt.isStartdoc()) { tt = curs.toFirstContentToken(); } if (tt.isContainer()) { tt = curs.toNextToken(); while (!tt.isEnd()) { if (tt.isStart()) { // See if this child is the same as the one thep passed in if (curs.comparePosition(xmlChildCursor) == 0) { // Found it if (addToType == APPEND_CHILD) { // Move the cursor to just past the end of this element curs.toEndToken(); curs.toNextToken(); } insertChild(curs, xmlToInsert); break; } } // Skip over child elements if (tt.isStart()) { tt = curs.toEndToken(); } tt = curs.toNextToken(); } } xmlChildCursor.dispose(); curs.dispose(); } /** * * @param curs */ protected void removeToken (XmlCursor curs) { XmlObject xo = XmlObject.Factory.newInstance(); // Don't delete anything move to another document so it gets orphaned nicely. XmlCursor tmpCurs = xo.newCursor(); tmpCurs.toFirstContentToken(); curs.moveXml(tmpCurs); tmpCurs.dispose(); } /** * * @param index */ protected void removeChild(long index) { XmlCursor curs = newCursor(); if (moveToChild(curs, index, false, false)) { removeToken(curs); } curs.dispose(); } /** * * @param name * @return */ protected static javax.xml.namespace.QName computeQName (Object name) { if (name instanceof String) { String ns = null; String localName = null; String fullName = (String)name; localName = fullName; if (fullName.startsWith("\"")) { int idx = fullName.indexOf(":"); if (idx != -1) { ns = fullName.substring(1, idx - 1); // Don't include the "" around the namespace localName = fullName.substring(idx + 1); } } if (ns == null) { return new javax.xml.namespace.QName(localName); } else { return new javax.xml.namespace.QName(ns, localName); } } return null; } /** * * @param destCurs * @param newValue */ private void replace(XmlCursor destCurs, XML newValue) { if (destCurs.isStartdoc()) { // Can't overwrite a whole document (user really wants to overwrite the contents of). destCurs.toFirstContentToken(); } // Orphan the token -- don't delete it outright on the XmlCursor. removeToken(destCurs); XmlCursor srcCurs = newValue.newCursor(); if (srcCurs.currentTokenType().isStartdoc()) { // Cann't append a whole document (user really wants to append the contents of). srcCurs.toFirstContentToken(); } moveSrcToDest(srcCurs, destCurs, false); // Re-link a new annotation to this cursor -- we just deleted the previous annotation on entrance to replace. if (!destCurs.toPrevSibling()) { destCurs.toPrevToken(); } destCurs.setBookmark(new XScriptAnnotation(destCurs)); // todo would be nice if destCurs.toNextSibling went to where the next token if the cursor was pointing at the last token in the stream. destCurs.toEndToken(); destCurs.toNextToken(); srcCurs.dispose(); } /** * * @param currXMLNode * @param xmlValue * @return */ private boolean doPut(XMLName name, XML currXMLNode, XMLObjectImpl xmlValue) { boolean result = false; XmlCursor curs = currXMLNode.newCursor(); try { // Replace the node with this new xml value. XML xml; int toAssignLen = xmlValue.length(); for (int i = 0; i < toAssignLen; i++) { if (xmlValue instanceof XMLList) { xml = ((XMLList) xmlValue).item(i); } else { xml = (XML) xmlValue; } // If it's an attribute or text node, make text node. XmlCursor.TokenType tt = xml.tokenType(); if (tt == XmlCursor.TokenType.ATTR || tt == XmlCursor.TokenType.TEXT) { xml = makeXmlFromString(lib, name, xml.toString()); } if (i == 0) { // 1st assignment is replaceChild all others are appendChild replace(curs, xml); } else { insertChild(curs, xml); } } // We're done we've blown away the node because the rvalue was XML... result = true; } catch (Exception ex) { ex.printStackTrace(); throw ScriptRuntime.typeError(ex.getMessage()); } finally { curs.dispose(); } return result; } /** * Make a text node element with this element name and text value. * * @param name * @param value * @return */ private XML makeXmlFromString(XMLLibImpl lib, XMLName name, String value) { XML result; javax.xml.namespace.QName qname; try { qname = new javax.xml.namespace.QName(name.uri(), name.localName()); } catch(Exception e) { throw ScriptRuntime.typeError(e.getMessage()); } result = createTextElement(lib, qname, value); return result; } /** * * @param name * @return */ private XMLList matchAttributes(XMLName xmlName) { XMLList result = new XMLList(lib); XmlCursor curs = newCursor(); if (curs.currentTokenType().isStartdoc()) { curs.toFirstContentToken(); } if (curs.isStart()) { if (curs.toFirstAttribute()) { do { if (qnameMatches(xmlName, curs.getName())) { result.addToList(createAttributeObject(curs)); } } while (curs.toNextAttribute()); } } curs.dispose(); return result; } /** * * @param attrCurs * @return */ private XML createAttributeObject (XmlCursor attrCurs) { XML result = null; if (attrCurs.currentTokenType().isAttr()) { result = createAttributeXML(lib, attrCurs); } return result; } // // // methods overriding ScriptableObject // // public String getClassName () { return "XML"; } // // // methods overriding IdScriptableObject // // /** * XML[0] should return this, all other indexes are Undefined * * @param index * @param start * @return */ public Object get(int index, Scriptable start) { //Log("get index: " + index); if (index == 0) { return this; } else { return Scriptable.NOT_FOUND; } } /** * Does the named property exist * * @param name * @param start * @return */ boolean hasXMLProperty(XMLName xmlName) { boolean result = false; if (prototypeFlag) { String name = xmlName.localName(); if (getMethod(name) != NOT_FOUND) { result = true; } } else { // Has now should return true if the property would have results > 0 or // if it's a method name String name = xmlName.localName(); if ((getPropertyList(xmlName).length() > 0) || (getMethod(name) != NOT_FOUND)) { result = true; } } return result; } /** * * @param index * @param start * @return */ public boolean has(int index, Scriptable start) { return (index == 0); } /** * * @return */ public Object[] getIds() { Object[] enumObjs; if (prototypeFlag) { enumObjs = new Object[0]; } else { enumObjs = new Object[1]; enumObjs[0] = new Integer(0); } return enumObjs; } /** * * @return */ public Object [] getIdsForDebug() { return getIds(); } /** * * @param name * @param start * @return */ Object getXMLProperty(XMLName xmlName) { Object result = NOT_FOUND; if (prototypeFlag) { String name = xmlName.localName(); result = getMethod(name); } else { result = getPropertyList(xmlName); } return result; } /** * * @param name * @param start * @param value */ void putXMLProperty(XMLName xmlName, Object value) { //Log("put property: " + name + " value: " + value.getClass()); if (prototypeFlag) { } else { // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } // Get the named property if (xmlName.isAttributeName()) { setAttribute(xmlName, value); } else if (xmlName.uri() == null && xmlName.localName().equals("*")) { setChildren(value); } else { // Convert text into XML if needed. XMLObjectImpl xmlValue = null; if (value instanceof XMLObjectImpl) { xmlValue = (XMLObjectImpl) value; // Check for attribute type and convert to textNode if (xmlValue instanceof XML) { if (((XML) xmlValue).tokenType() == XmlCursor.TokenType.ATTR) { xmlValue = makeXmlFromString(lib, xmlName, xmlValue.toString()); } } if (xmlValue instanceof XMLList) { for (int i = 0; i < xmlValue.length(); i++) { XML xml = ((XMLList) xmlValue).item(i); if (xml.tokenType() == XmlCursor.TokenType.ATTR) { ((XMLList) xmlValue).replace(i, makeXmlFromString(lib, xmlName, xml.toString())); } } } } else { xmlValue = makeXmlFromString(lib, xmlName, ScriptRuntime.toString(value)); } XMLList matches = getPropertyList(xmlName); if (matches.length() == 0) { appendChild(xmlValue); } else { // Remove all other matches for (int i = 1; i < matches.length(); i++) { removeChild(matches.item(i).childIndex()); } // Replace first match with new value. doPut(xmlName, matches.item(0), xmlValue); } } } } /** * * @param index * @param start * @param value */ public void put(int index, Scriptable start, Object value) { // Spec says assignment to indexed XML object should return type error throw ScriptRuntime.typeError("Assignment to indexed XML is not allowed"); } /** * * @param name */ void deleteXMLProperty(XMLName name) { if (!name.isDescendants() && name.isAttributeName()) { XmlCursor curs = newCursor(); // TODO: Cover the case *::name if (name.localName().equals("*")) { // Delete all attributes. if (curs.toFirstAttribute()) { while (curs.currentTokenType().isAttr()) { curs.removeXml(); } } } else { // Delete an attribute. javax.xml.namespace.QName qname = new javax.xml.namespace.QName( name.uri(), name.localName()); curs.removeAttribute(qname); } curs.dispose(); } else { XMLList matches = getPropertyList(name); matches.remove(); } } /** * * @param index */ public void delete(int index) { if (index == 0) { remove(); } } // // // package utility functions: // // protected XScriptAnnotation getAnnotation () { return _anno; } protected void changeNS (String oldURI, String newURI) { XmlCursor curs = newCursor(); while (curs.toParent()) { /* Goto the top of the document */ } TokenType tt = curs.currentTokenType(); if (tt.isStartdoc()) { tt = curs.toFirstContentToken(); } if (tt.isStart()) { do { if (tt.isStart() || tt.isAttr() || tt.isNamespace()) { javax.xml.namespace.QName currQName = curs.getName(); if (oldURI.equals(currQName.getNamespaceURI())) { curs.setName(new javax.xml.namespace.QName(newURI, currQName.getLocalPart())); } } tt = curs.toNextToken(); } while (!tt.isEnddoc() && !tt.isNone()); } curs.dispose(); } /** * */ void remove () { XmlCursor childCurs = newCursor(); if (childCurs.currentTokenType().isStartdoc()) { // Remove on the document removes all children. TokenType tt = childCurs.toFirstContentToken(); while (!tt.isEnd() && !tt.isEnddoc()) { removeToken(childCurs); tt = childCurs.currentTokenType(); // Now see where we're pointing after the delete -- next token. } } else { removeToken(childCurs); } childCurs.dispose(); } /** * * @param value */ void replaceAll(XML value) { XmlCursor curs = newCursor(); replace(curs, value); _anno = value._anno; curs.dispose(); } /** * * @param attrName * @param value */ void setAttribute(XMLName xmlName, Object value) { if (xmlName.uri() == null && xmlName.localName().equals("*")) { throw ScriptRuntime.typeError("@* assignment not supported."); } XmlCursor curs = newCursor(); String strValue = ScriptRuntime.toString(value); if (curs.currentTokenType().isStartdoc()) { curs.toFirstContentToken(); } javax.xml.namespace.QName qName; try { qName = new javax.xml.namespace.QName(xmlName.uri(), xmlName.localName()); } catch(Exception e) { throw ScriptRuntime.typeError(e.getMessage()); } if (!curs.setAttributeText(qName, strValue)) { if (curs.currentTokenType().isStart()) { // Can only add attributes inside of a start. curs.toNextToken(); } curs.insertAttributeWithValue(qName, strValue); } curs.dispose(); } /** * * @param namespace * @return */ private XMLList allChildNodes(String namespace) { XMLList result = new XMLList(lib); XmlCursor curs = newCursor(); TokenType tt = curs.currentTokenType(); javax.xml.namespace.QName targetProperty = new javax.xml.namespace.QName(namespace, "*"); if (tt.isStartdoc()) { tt = curs.toFirstContentToken(); } if (tt.isContainer()) { tt = curs.toFirstContentToken(); while (!tt.isEnd()) { if (!tt.isStart()) { // Not an element result.addToList(findAnnotation(curs)); // Reset target property to null in this case targetProperty = null; } else { // Match namespace as well if specified if (namespace == null || namespace.length() == 0 || namespace.equals("*") || curs.getName().getNamespaceURI().equals(namespace)) { // Add it to the list result.addToList(findAnnotation(curs)); // Set target property if target name is "*", // Otherwise if target property does not match current, then // set to null if (targetProperty != null) { if (targetProperty.getLocalPart().equals("*")) { targetProperty = curs.getName(); } else if (!targetProperty.getLocalPart().equals(curs.getName().getLocalPart())) { // Not a match, unset target property targetProperty = null; } } } } // Skip over child elements if (tt.isStart()) { tt = curs.toEndToken(); } tt = curs.toNextToken(); } } curs.dispose(); // Set the targets for this XMLList. result.setTargets(this, targetProperty); return result; } /** * * @return */ private XMLList matchDescendantAttributes(XMLName xmlName) { XMLList result = new XMLList(lib); XmlCursor curs = newCursor(); TokenType tt = curs.currentTokenType(); // Set the targets for this XMLList. result.setTargets(this, null); if (tt.isStartdoc()) { tt = curs.toFirstContentToken(); } if (tt.isContainer()) { int nestLevel = 1; while (nestLevel > 0) { tt = curs.toNextToken(); // Only try to match names for attributes if (tt.isAttr()) { if (qnameMatches(xmlName, curs.getName())) { result.addToList(findAnnotation(curs)); } } if (tt.isStart()) { nestLevel++; } else if (tt.isEnd()) { nestLevel--; } else if (tt.isEnddoc()) { // Shouldn't get here, but just in case. break; } } } curs.dispose(); return result; } /** * * @return */ private XMLList matchDescendantChildren(XMLName xmlName) { XMLList result = new XMLList(lib); XmlCursor curs = newCursor(); TokenType tt = curs.currentTokenType(); // Set the targets for this XMLList. result.setTargets(this, null); if (tt.isStartdoc()) { tt = curs.toFirstContentToken(); } if (tt.isContainer()) { int nestLevel = 1; while (nestLevel > 0) { tt = curs.toNextToken(); if (!tt.isAttr() && !tt.isEnd() && !tt.isEnddoc()) { // Only try to match names for elements or processing instructions. if (!tt.isStart() && !tt.isProcinst()) { // Not an element or procinst, only add if qname is all if (xmlName.localName().equals("*")) { result.addToList(findAnnotation(curs)); } } else { if (qnameMatches(xmlName, curs.getName())) { result.addToList(findAnnotation(curs)); } } } if (tt.isStart()) { nestLevel++; } else if (tt.isEnd()) { nestLevel--; } else if (tt.isEnddoc()) { // Shouldn't get here, but just in case. break; } } } curs.dispose(); return result; } /** * * @param tokenType * @return */ private XMLList matchChildren(XmlCursor.TokenType tokenType) { return matchChildren(tokenType, XMLName.formStar()); } /** * * @return */ private XMLList matchChildren(XmlCursor.TokenType tokenType, XMLName name) { XMLList result = new XMLList(lib); XmlCursor curs = newCursor(); TokenType tt = curs.currentTokenType(); javax.xml.namespace.QName qname = new javax.xml.namespace.QName(name.uri(), name.localName()); javax.xml.namespace.QName targetProperty = qname; if (tt.isStartdoc()) { tt = curs.toFirstContentToken(); } if (tt.isContainer()) { tt = curs.toFirstContentToken(); while (!tt.isEnd()) { if (tt == tokenType) { // Only try to match names for elements or processing instructions. if (!tt.isStart() && !tt.isProcinst()) { // Not an element or no name specified. result.addToList(findAnnotation(curs)); // Reset target property to null in this case targetProperty = null; } else { // Match names as well if (qnameMatches(name, curs.getName())) { // Add it to the list result.addToList(findAnnotation(curs)); // Set target property if target name is "*", // Otherwise if target property does not match current, then // set to null if (targetProperty != null) { if (targetProperty.getLocalPart().equals("*")) { targetProperty = curs.getName(); } else if (!targetProperty.getLocalPart().equals(curs.getName().getLocalPart())) { // Not a match, unset target property targetProperty = null; } } } } } // Skip over child elements if (tt.isStart()) { tt = curs.toEndToken(); } tt = curs.toNextToken(); } } curs.dispose(); if (tokenType == XmlCursor.TokenType.START) { // Set the targets for this XMLList. result.setTargets(this, targetProperty); } return result; } /** * * @param template * @param match * @return */ private boolean qnameMatches(XMLName template, javax.xml.namespace.QName match) { boolean matches = false; if (template.uri() == null || template.uri().equals(match.getNamespaceURI())) { // URI OK, test name if (template.localName().equals("*") || template.localName().equals(match.getLocalPart())) { matches = true; } } return matches; } // // // Methods from section 12.4.4 in the spec // // /** * The addNamespace method adds a namespace declaration to the in scope * namespaces for this XML object and returns this XML object. * * @param toAdd */ XML addNamespace(Namespace ns) { // When a namespace is used it will be added automatically // to the inScopeNamespaces set. There is no need to add // Namespaces with undefined prefixes. String nsPrefix = ns.prefix(); if (nsPrefix == null) return this; XmlCursor cursor = newCursor(); try { if(!cursor.isContainer()) return this; javax.xml.namespace.QName qname = cursor.getName(); // Don't add a default namespace declarations to containers // with QNames in no namespace. if(qname.getNamespaceURI().equals("") && nsPrefix.equals("")) return this; // Get all declared namespaces that are in scope Map prefixToURI = NamespaceHelper.getAllNamespaces(lib, cursor); String uri = (String)prefixToURI.get(nsPrefix); if(uri != null) { // Check if the Namespace is not already in scope if(uri.equals(ns.uri())) return this; cursor.push(); // Let's see if we have to delete a namespace declaration while(cursor.toNextToken().isAnyAttr()) { if(cursor.isNamespace()) { qname = cursor.getName(); String prefix = qname.getLocalPart(); if(prefix.equals(nsPrefix)) { // Delete the current Namespace declaration cursor.removeXml(); break; } } } cursor.pop(); } cursor.toNextToken(); cursor.insertNamespace(nsPrefix, ns.uri()); } finally { cursor.dispose(); } return this; } /** * * @param xml * @return */ XML appendChild(Object xml) { XmlCursor curs = newCursor(); if (curs.isStartdoc()) { curs.toFirstContentToken(); } // Move the cursor to the end of this element if (curs.isStart()) { curs.toEndToken(); } insertChild(curs, xml); curs.dispose(); return this; } /** * * @param name * @return */ XMLList attribute(XMLName xmlName) { return matchAttributes(xmlName); } /** * * @return */ XMLList attributes() { XMLName xmlName = XMLName.formStar(); return matchAttributes(xmlName); } XMLList child(long index) { XMLList result = new XMLList(lib); result.setTargets(this, null); result.addToList(getXmlChild(index)); return result; } XMLList child(XMLName xmlName) { if (xmlName == null) return new XMLList(lib); XMLList result; if (xmlName.localName().equals("*")) { result = allChildNodes(xmlName.uri()); } else { result = matchChildren(XmlCursor.TokenType.START, xmlName); } return result; } /** * * @param index * @return */ XML getXmlChild(long index) { XML result = null; XmlCursor curs = newCursor(); if (moveToChild(curs, index, false, true)) { result = createXML(lib, curs); } curs.dispose(); return result; } /** * * @return */ int childIndex() { int index = 0; XmlCursor curs = newCursor(); TokenType tt = curs.currentTokenType(); while (true) { if (tt.isText()) { index++; if (!curs.toPrevSibling()) { break; } } else if (tt.isStart()) { tt = curs.toPrevToken(); if (tt.isEnd()) { curs.toNextToken(); if (!curs.toPrevSibling()) { break; } index++; } else { // Hit the parent start tag so get out we're down counting children. break; } } else if (tt.isComment() || tt.isProcinst()) { curs.toPrevToken(); } else { break; } tt = curs.currentTokenType(); } index = curs.currentTokenType().isStartdoc() ? -1 : index; curs.dispose(); return index; } /** * * @return */ XMLList children() { return allChildNodes(null); } /** * * @return */ XMLList comments() { return matchChildren(XmlCursor.TokenType.COMMENT); } /** * * @param xml * @return */ boolean contains(Object xml) { boolean result = false; if (xml instanceof XML) { result = equivalentXml(xml); } return result; } /** * * @return */ Object copy() { XmlCursor srcCurs = newCursor(); if (srcCurs.isStartdoc()) { srcCurs.toFirstContentToken(); } XML xml = createEmptyXML(lib); XmlCursor destCurs = xml.newCursor(); destCurs.toFirstContentToken(); srcCurs.copyXml(destCurs); destCurs.dispose(); srcCurs.dispose(); return xml; } /** * * @param name * @return */ XMLList descendants(XMLName xmlName) { XMLList result; if (xmlName.isAttributeName()) { result = matchDescendantAttributes(xmlName); } else { result = matchDescendantChildren(xmlName); } return result; } /** * The inScopeNamespaces method returns an Array of Namespace objects * representing the namespaces in scope for this XML object in the * context of its parent. * * @return Array of all Namespaces in scope for this XML Object. */ Object[] inScopeNamespaces() { XmlCursor cursor = newCursor(); Object[] namespaces = NamespaceHelper.inScopeNamespaces(lib, cursor); cursor.dispose(); return namespaces; } /** * * @param child * @param xml */ XML insertChildAfter(Object child, Object xml) { if (child == null) { // Spec says inserting after nothing is the same as prepending prependChild(xml); } else if (child instanceof XML) { insertChild((XML) child, xml, APPEND_CHILD); } return this; } /** * * @param child * @param xml */ XML insertChildBefore(Object child, Object xml) { if (child == null) { // Spec says inserting before nothing is the same as appending appendChild(xml); } else if (child instanceof XML) { insertChild((XML) child, xml, PREPEND_CHILD); } return this; } /** * * @return */ boolean hasOwnProperty(XMLName xmlName) { boolean hasProperty = false; if (prototypeFlag) { String property = xmlName.localName(); hasProperty = (0 != findPrototypeId(property)); } else { hasProperty = (getPropertyList(xmlName).length() > 0); } return hasProperty; } /** * * @return */ boolean hasComplexContent() { return !hasSimpleContent(); } /** * * @return */ boolean hasSimpleContent() { boolean simpleContent = false; XmlCursor curs = newCursor(); if (curs.isAttr() || curs.isText()) { return true; } if (curs.isStartdoc()) { curs.toFirstContentToken(); } simpleContent = !(curs.toFirstChild()); curs.dispose(); return simpleContent; } /** * Length of an XML object is always 1, it's a list of XML objects of size 1. * * @return */ int length() { return 1; } /** * * @return */ String localName() { XmlCursor cursor = newCursor(); if (cursor.isStartdoc()) cursor.toFirstContentToken(); String name = null; if(cursor.isStart() || cursor.isAttr() || cursor.isProcinst()) { javax.xml.namespace.QName qname = cursor.getName(); name = qname.getLocalPart(); } cursor.dispose(); return name; } /** * The name method returns the qualified name associated with this XML object. * * @return The qualified name associated with this XML object. */ QName name() { XmlCursor cursor = newCursor(); if (cursor.isStartdoc()) cursor.toFirstContentToken(); QName name = null; if(cursor.isStart() || cursor.isAttr() || cursor.isProcinst()) { javax.xml.namespace.QName qname = cursor.getName(); if(cursor.isProcinst()) { name = new QName(lib, "", qname.getLocalPart(), ""); } else { String uri = qname.getNamespaceURI(); String prefix = qname.getPrefix(); name = new QName(lib, uri, qname.getLocalPart(), prefix); } } cursor.dispose(); return name; } /** * * @param prefix * @return */ Object namespace(String prefix) { XmlCursor cursor = newCursor(); if (cursor.isStartdoc()) { cursor.toFirstContentToken(); } Object result = null; if (prefix == null) { if(cursor.isStart() || cursor.isAttr()) { Object[] inScopeNS = NamespaceHelper.inScopeNamespaces(lib, cursor); // XXX Is it reaaly necessary to create the second cursor? XmlCursor cursor2 = newCursor(); if (cursor2.isStartdoc()) cursor2.toFirstContentToken(); result = NamespaceHelper.getNamespace(lib, cursor2, inScopeNS); cursor2.dispose(); } } else { Map prefixToURI = NamespaceHelper.getAllNamespaces(lib, cursor); String uri = (String)prefixToURI.get(prefix); result = (uri == null) ? Undefined.instance : new Namespace(lib, prefix, uri); } cursor.dispose(); return result; } /** * * @return */ Object[] namespaceDeclarations() { XmlCursor cursor = newCursor(); Object[] namespaces = NamespaceHelper.namespaceDeclarations(lib, cursor); cursor.dispose(); return namespaces; } /** * * @return */ Object nodeKind() { String result; XmlCursor.TokenType tt = tokenType(); if (tt == XmlCursor.TokenType.ATTR) { result = "attribute"; } else if (tt == XmlCursor.TokenType.TEXT) { result = "text"; } else if (tt == XmlCursor.TokenType.COMMENT) { result = "comment"; } else if (tt == XmlCursor.TokenType.PROCINST) { result = "processing-instruction"; } else if (tt == XmlCursor.TokenType.START) { result = "element"; } else { // A non-existant node has the nodeKind() of text result = "text"; } return result; } /** * */ void normalize() { XmlCursor curs = newCursor(); TokenType tt = curs.currentTokenType(); // Walk through the tokens removing empty text nodes and merging adjacent text nodes. if (tt.isStartdoc()) { tt = curs.toFirstContentToken(); } if (tt.isContainer()) { int nestLevel = 1; String previousText = null; while (nestLevel > 0) { tt = curs.toNextToken(); if (tt == XmlCursor.TokenType.TEXT) { String currentText = curs.getChars().trim(); if (currentText.trim().length() == 0) { // Empty text node, remove. removeToken(curs); curs.toPrevToken(); } else if (previousText == null) { // No previous text node, reset to trimmed version previousText = currentText; } else { // It appears that this case never happens with XBeans. // Previous text node exists, concatenate String newText = previousText + currentText; curs.toPrevToken(); removeToken(curs); removeToken(curs); curs.insertChars(newText); } } else { previousText = null; } if (tt.isStart()) { nestLevel++; } else if (tt.isEnd()) { nestLevel--; } else if (tt.isEnddoc()) { // Shouldn't get here, but just in case. break; } } } curs.dispose(); } /** * * @return */ Object parent() { Object parent; XmlCursor curs = newCursor(); if (curs.isStartdoc()) { // At doc level - no parent parent = Undefined.instance; } else { if (curs.toParent()) { if (curs.isStartdoc()) { // Was top-level - no parent parent = Undefined.instance; } else { parent = getFromAnnotation(lib, findAnnotation(curs)); } } else { // No parent parent = Undefined.instance; } } curs.dispose(); return parent; } /** * * @param xml * @return */ XML prependChild (Object xml) { XmlCursor curs = newCursor(); if (curs.isStartdoc()) { curs.toFirstContentToken(); } // Move the cursor to the first content token curs.toFirstContentToken(); insertChild(curs, xml); curs.dispose(); return this; } /** * * @return */ Object processingInstructions(XMLName xmlName) { return matchChildren(XmlCursor.TokenType.PROCINST, xmlName); } /** * * @param name * @return */ boolean propertyIsEnumerable(Object name) { boolean result; if (name instanceof Integer) { result = (((Integer)name).intValue() == 0); } else if (name instanceof Number) { double x = ((Number)name).doubleValue(); // Check that number is posotive 0 result = (x == 0.0 && 1.0 / x > 0); } else { result = ScriptRuntime.toString(name).equals("0"); } return result; } /** * * @param namespace */ XML removeNamespace(Namespace ns) { XmlCursor cursor = newCursor(); try { if(cursor.isStartdoc()) cursor.toFirstContentToken(); if(!cursor.isStart()) return this; String nsPrefix = ns.prefix(); String nsURI = ns.uri(); Map prefixToURI = new HashMap(); int depth = 1; while(!(cursor.isEnd() && depth == 0)) { if(cursor.isStart()) { // Get the namespaces declared in this element. // The ones with undefined prefixes are not candidates // for removal because they are used. prefixToURI.clear(); NamespaceHelper.getNamespaces(cursor, prefixToURI); ObjArray inScopeNSBag = new ObjArray(); Iterator i = prefixToURI.entrySet().iterator(); while(i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); ns = new Namespace(lib, (String)entry.getKey(), (String)entry.getValue()); inScopeNSBag.add(ns); } // Add the URI we are looking for to avoid matching // non-existing Namespaces. ns = new Namespace(lib, nsURI); inScopeNSBag.add(ns); Object[] inScopeNS = inScopeNSBag.toArray(); // Check the element name Namespace n = NamespaceHelper.getNamespace(lib, cursor, inScopeNS); if(nsURI.equals(n.uri()) && (nsPrefix == null || nsPrefix.equals(n.prefix()))) { // This namespace is used return this; } // Check the attributes cursor.push(); boolean hasNext = cursor.toFirstAttribute(); while(hasNext) { n = NamespaceHelper.getNamespace(lib, cursor, inScopeNS); if(nsURI.equals(n.uri()) && (nsPrefix == null || nsPrefix.equals(n.prefix()))) { // This namespace is used return this; } hasNext = cursor.toNextAttribute(); } cursor.pop(); if(nsPrefix == null) { // Remove all namespaces declarations that match nsURI i = prefixToURI.entrySet().iterator(); while(i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); if(entry.getValue().equals(nsURI)) NamespaceHelper.removeNamespace(cursor, (String)entry.getKey()); } } else if(nsURI.equals(prefixToURI.get(nsPrefix))) { // Remove the namespace declaration that matches nsPrefix NamespaceHelper.removeNamespace(cursor, String.valueOf(nsPrefix)); } } switch(cursor.toNextToken().intValue()) { case XmlCursor.TokenType.INT_START: depth++; break; case XmlCursor.TokenType.INT_END: depth--; break; } } } finally { cursor.dispose(); } return this; } XML replace(long index, Object xml) { XMLList xlChildToReplace = child(index); if (xlChildToReplace.length() > 0) { // One exists an that index XML childToReplace = xlChildToReplace.item(0); insertChildAfter(childToReplace, xml); removeChild(index); } return this; } /** * * @param propertyName * @param xml * @return */ XML replace(XMLName xmlName, Object xml) { putXMLProperty(xmlName, xml); return this; } /** * * @param xml */ XML setChildren(Object xml) { // remove all children XMLName xmlName = XMLName.formStar(); XMLList matches = getPropertyList(xmlName); matches.remove(); // append new children appendChild(xml); return this; } /** * * @param name */ void setLocalName(String localName) { XmlCursor cursor = newCursor(); try { if(cursor.isStartdoc()) cursor.toFirstContentToken(); if(cursor.isText() || cursor.isComment()) return; javax.xml.namespace.QName qname = cursor.getName(); cursor.setName(new javax.xml.namespace.QName( qname.getNamespaceURI(), localName, qname.getPrefix())); } finally { cursor.dispose(); } } /** * * @param name */ void setName(QName qname) { XmlCursor cursor = newCursor(); try { if(cursor.isStartdoc()) cursor.toFirstContentToken(); if(cursor.isText() || cursor.isComment()) return; if(cursor.isProcinst()) { String localName = qname.localName(); cursor.setName(new javax.xml.namespace.QName(localName)); } else { String prefix = qname.prefix(); if (prefix == null) { prefix = ""; } cursor.setName(new javax.xml.namespace.QName( qname.uri(), qname.localName(), prefix)); } } finally { cursor.dispose(); } } /** * * @param ns */ void setNamespace(Namespace ns) { XmlCursor cursor = newCursor(); try { if(cursor.isStartdoc()) cursor.toFirstContentToken(); if(cursor.isText() || cursor.isComment() || cursor.isProcinst()) return; String prefix = ns.prefix(); if (prefix == null) { prefix = ""; } cursor.setName(new javax.xml.namespace.QName( ns.uri(), localName(), prefix)); } finally { cursor.dispose(); } } /** * * @return */ XMLList text() { return matchChildren(XmlCursor.TokenType.TEXT); } /** * * @return */ public String toString() { String result; XmlCursor curs = newCursor(); if (curs.isStartdoc()) { curs.toFirstContentToken(); } if (curs.isText()) { result = curs.getChars(); } else if (curs.isStart() && hasSimpleContent()) { result = curs.getTextValue(); } else { result = toXMLString(0); } return result; } String toSource(int indent) { // XXX Does toXMLString always return valid XML literal? return toXMLString(indent); } /** * * @return */ String toXMLString(int indent) { // XXX indent is ignored String result; XmlCursor curs = newCursor(); if (curs.isStartdoc()) { curs.toFirstContentToken(); } try { if (curs.isText()) { result = curs.getChars(); } else if (curs.isAttr()) { result = curs.getTextValue(); } else if (curs.isComment() || curs.isProcinst()) { result = XML.dumpNode(curs, getOptions()); // todo: XBeans-dependent hack here // If it's a comment or PI, take off the xml-frament stuff String start = ""; String end = ""; if (result.startsWith(start)) { result = result.substring(start.length()); } if (result.endsWith(end)) { result = result.substring(0, result.length() - end.length()); } } else { result = XML.dumpNode(curs, getOptions()); } } finally { curs.dispose(); } return result; } /** * * @return */ Object valueOf() { return this; } // // Other public Functions from XMLObject // /** * * @param target * @return */ boolean equivalentXml(Object target) { boolean result = false; if (target instanceof XML) { XML otherXml = (XML) target; // Compare with toString() if either side is text node or attribute // otherwise compare as XML XmlCursor.TokenType thisTT = tokenType(); XmlCursor.TokenType otherTT = otherXml.tokenType(); if (thisTT == XmlCursor.TokenType.ATTR || otherTT == XmlCursor.TokenType.ATTR || thisTT == XmlCursor.TokenType.TEXT || otherTT == XmlCursor.TokenType.TEXT) { result = toString().equals(otherXml.toString()); } else { XmlCursor cursOne = newCursor(); XmlCursor cursTwo = otherXml.newCursor(); result = LogicalEquality.nodesEqual(cursOne, cursTwo); cursOne.dispose(); cursTwo.dispose(); // Old way of comparing by string. // boolean orgPrettyPrinting = prototype.prettyPrinting; // prototype.prettyPrinting = true; // result = toXMLString(0).equals(otherXml.toXMLString(0)); // prototype.prettyPrinting = orgPrettyPrinting; } } else if (target instanceof XMLList) { XMLList otherList = (XMLList) target; if (otherList.length() == 1) { result = equivalentXml(otherList.getXmlFromAnnotation(0)); } } else if (hasSimpleContent()) { String otherStr = ScriptRuntime.toString(target); result = toString().equals(otherStr); } return result; } /** * * @param name * @param start * @return */ XMLList getPropertyList(XMLName name) { XMLList result; // Get the named property if (name.isDescendants()) { result = descendants(name); } else if (name.isAttributeName()) { result = attribute(name); } else { result = child(name); } return result; } protected Object jsConstructor(Context cx, boolean inNewExpr, Object[] args) { if (args.length == 0) { return createFromJS(lib, ""); } else { Object arg0 = args[0]; if (!inNewExpr && arg0 instanceof XML) { // XML(XML) returns the same object. return arg0; } return createFromJS(lib, arg0); } } /** * See ECMA 357, 11_2_2_1, Semantics, 3_f. */ public Scriptable getExtraMethodSource(Context cx) { if (hasSimpleContent()) { String src = toString(); return ScriptRuntime.toObjectOrNull(cx, src); } return null; } XmlObject getXmlObject() { XmlObject xo; XmlCursor cursor = newCursor(); try { xo = cursor.getObject(); } finally { cursor.dispose(); } return xo; } } ././@LongLink0000000000000000000000000000016000000000000011212 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/XMLCtor.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/X0000644000175000017500000002243211314263504035633 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml.impl.xmlbeans; import org.mozilla.javascript.*; class XMLCtor extends IdFunctionObject { static final long serialVersionUID = -8708195078359817341L; private static final Object XMLCTOR_TAG = "XMLCtor"; private XMLLibImpl lib; XMLCtor(XML xml, Object tag, int id, int arity) { super(xml, tag, id, arity); this.lib = xml.lib; activatePrototypeMap(MAX_FUNCTION_ID); } private void writeSetting(Scriptable target) { for (int i = 1; i <= MAX_INSTANCE_ID; ++i) { int id = super.getMaxInstanceId() + i; String name = getInstanceIdName(id); Object value = getInstanceIdValue(id); ScriptableObject.putProperty(target, name, value); } } private void readSettings(Scriptable source) { for (int i = 1; i <= MAX_INSTANCE_ID; ++i) { int id = super.getMaxInstanceId() + i; String name = getInstanceIdName(id); Object value = ScriptableObject.getProperty(source, name); if (value == Scriptable.NOT_FOUND) { continue; } switch (i) { case Id_ignoreComments: case Id_ignoreProcessingInstructions: case Id_ignoreWhitespace: case Id_prettyPrinting: if (!(value instanceof Boolean)) { continue; } break; case Id_prettyIndent: if (!(value instanceof Number)) { continue; } break; default: throw new IllegalStateException(); } setInstanceIdValue(id, value); } } // #string_id_map# private static final int Id_ignoreComments = 1, Id_ignoreProcessingInstructions = 2, Id_ignoreWhitespace = 3, Id_prettyIndent = 4, Id_prettyPrinting = 5, MAX_INSTANCE_ID = 5; protected int getMaxInstanceId() { return super.getMaxInstanceId() + MAX_INSTANCE_ID; } protected int findInstanceIdInfo(String s) { int id; // #generated# Last update: 2004-07-19 13:03:52 CEST L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 12: X="prettyIndent";id=Id_prettyIndent; break L; case 14: c=s.charAt(0); if (c=='i') { X="ignoreComments";id=Id_ignoreComments; } else if (c=='p') { X="prettyPrinting";id=Id_prettyPrinting; } break L; case 16: X="ignoreWhitespace";id=Id_ignoreWhitespace; break L; case 28: X="ignoreProcessingInstructions";id=Id_ignoreProcessingInstructions; break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# if (id == 0) return super.findInstanceIdInfo(s); int attr; switch (id) { case Id_ignoreComments: case Id_ignoreProcessingInstructions: case Id_ignoreWhitespace: case Id_prettyIndent: case Id_prettyPrinting: attr = PERMANENT | DONTENUM; break; default: throw new IllegalStateException(); } return instanceIdInfo(attr, super.getMaxInstanceId() + id); } // #/string_id_map# protected String getInstanceIdName(int id) { switch (id - super.getMaxInstanceId()) { case Id_ignoreComments: return "ignoreComments"; case Id_ignoreProcessingInstructions: return "ignoreProcessingInstructions"; case Id_ignoreWhitespace: return "ignoreWhitespace"; case Id_prettyIndent: return "prettyIndent"; case Id_prettyPrinting: return "prettyPrinting"; } return super.getInstanceIdName(id); } protected Object getInstanceIdValue(int id) { switch (id - super.getMaxInstanceId()) { case Id_ignoreComments: return ScriptRuntime.wrapBoolean(lib.ignoreComments); case Id_ignoreProcessingInstructions: return ScriptRuntime.wrapBoolean(lib.ignoreProcessingInstructions); case Id_ignoreWhitespace: return ScriptRuntime.wrapBoolean(lib.ignoreWhitespace); case Id_prettyIndent: return ScriptRuntime.wrapInt(lib.prettyIndent); case Id_prettyPrinting: return ScriptRuntime.wrapBoolean(lib.prettyPrinting); } return super.getInstanceIdValue(id); } protected void setInstanceIdValue(int id, Object value) { switch (id - super.getMaxInstanceId()) { case Id_ignoreComments: lib.ignoreComments = ScriptRuntime.toBoolean(value); return; case Id_ignoreProcessingInstructions: lib.ignoreProcessingInstructions = ScriptRuntime.toBoolean(value); return; case Id_ignoreWhitespace: lib.ignoreWhitespace = ScriptRuntime.toBoolean(value); return; case Id_prettyIndent: lib.prettyIndent = ScriptRuntime.toInt32(value); return; case Id_prettyPrinting: lib.prettyPrinting = ScriptRuntime.toBoolean(value); return; } super.setInstanceIdValue(id, value); } // #string_id_map# private static final int Id_defaultSettings = 1, Id_settings = 2, Id_setSettings = 3, MAX_FUNCTION_ID = 3; protected int findPrototypeId(String s) { int id; // #generated# Last update: 2004-07-19 13:03:52 CEST L0: { id = 0; String X = null; int s_length = s.length(); if (s_length==8) { X="settings";id=Id_settings; } else if (s_length==11) { X="setSettings";id=Id_setSettings; } else if (s_length==15) { X="defaultSettings";id=Id_defaultSettings; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# return id; } // #/string_id_map# protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_defaultSettings: arity=0; s="defaultSettings"; break; case Id_settings: arity=0; s="settings"; break; case Id_setSettings: arity=1; s="setSettings"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(XMLCTOR_TAG, id, s, arity); } public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(XMLCTOR_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); switch (id) { case Id_defaultSettings: { lib.defaultSettings(); Scriptable obj = cx.newObject(scope); writeSetting(obj); return obj; } case Id_settings: { Scriptable obj = cx.newObject(scope); writeSetting(obj); return obj; } case Id_setSettings: { if (args.length == 0 || args[0] == null || args[0] == Undefined.instance) { lib.defaultSettings(); } else if (args[0] instanceof Scriptable) { readSettings((Scriptable)args[0]); } return Undefined.instance; } } throw new IllegalArgumentException(String.valueOf(id)); } } ././@LongLink0000000000000000000000000000016500000000000011217 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/XMLWithScope.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/X0000644000175000017500000001046111314263504035632 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Ethan Hugg * Terry Lucas * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml.impl.xmlbeans; import org.mozilla.javascript.*; import org.mozilla.javascript.xml.*; final class XMLWithScope extends NativeWith { private static final long serialVersionUID = -696429282095170887L; private XMLLibImpl lib; private int _currIndex; private XMLList _xmlList; private XMLObject _dqPrototype; XMLWithScope(XMLLibImpl lib, Scriptable parent, XMLObject prototype) { super(parent, prototype); this.lib = lib; } void initAsDotQuery() { XMLObject prototype = (XMLObject)getPrototype(); // XMLWithScope also handles the .(xxx) DotQuery for XML // basically DotQuery is a for/in/with statement and in // the following 3 statements we setup to signal it's // DotQuery, // the index and the object being looped over. The // xws.setPrototype is the scope of the object which is // is a element of the lhs (XMLList). _currIndex = 0; _dqPrototype = prototype; if (prototype instanceof XMLList) { XMLList xl = (XMLList)prototype; if (xl.length() > 0) { setPrototype((Scriptable)(xl.get(0, null))); } } // Always return the outer-most type of XML lValue of // XML to left of dotQuery. _xmlList = new XMLList(lib); } protected Object updateDotQuery(boolean value) { // Return null to continue looping XMLObject seed = _dqPrototype; XMLList xmlL = _xmlList; if (seed instanceof XMLList) { // We're a list so keep testing each element of the list if the // result on the top of stack is true then that element is added // to our result list. If false, we try the next element. XMLList orgXmlL = (XMLList)seed; int idx = _currIndex; if (value) { xmlL.addToList(orgXmlL.get(idx, null)); } // More elements to test? if (++idx < orgXmlL.length()) { // Yes, set our new index, get the next element and // reset the expression to run with this object as // the WITH selector. _currIndex = idx; setPrototype((Scriptable)(orgXmlL.get(idx, null))); // continue looping return null; } } else { // If we're not a XMLList then there's no looping // just return DQPrototype if the result is true. if (value) { xmlL.addToList(seed); } } return xmlL; } } ././@LongLink0000000000000000000000000000017000000000000011213 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/NamespaceHelper.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/N0000644000175000017500000002333111314263504035620 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml.impl.xmlbeans; import java.util.*; import org.apache.xmlbeans.XmlCursor; import org.mozilla.javascript.*; class NamespaceHelper { private XMLLibImpl lib; private final Map prefixToURI = new HashMap(); private final Map uriToPrefix = new HashMap(); // A set of URIs that are used without explicit namespace declaration in scope. private final Set undeclared = new HashSet(); private NamespaceHelper(XMLLibImpl lib) { this.lib = lib; // Insert the default namespace prefixToURI.put("", ""); Set prefixes = new HashSet(); prefixes.add(""); uriToPrefix.put("", prefixes); } /** * Declared a new namespace * * @param prefix * @param uri * @param declarations */ private void declareNamespace(String prefix, String uri, ObjArray declarations) { Set prefixes = (Set)uriToPrefix.get(uri); if(prefixes == null) { prefixes = new HashSet(); uriToPrefix.put(uri, prefixes); } if(!prefixes.contains(prefix)) { String oldURI = (String)prefixToURI.get(prefix); // Add the new mapping prefixes.add(prefix); prefixToURI.put(prefix, uri); if(declarations != null) declarations.add(new Namespace(lib, prefix, uri)); if(oldURI != null) { // Update the existing mapping prefixes = (Set)uriToPrefix.get(oldURI); prefixes.remove(prefix); } } } /** * Updates the internal state of this NamespaceHelper to reflect the * existance of the XML token pointed to by the cursor. */ private void processName(XmlCursor cursor, ObjArray declarations) { javax.xml.namespace.QName qname = cursor.getName(); String uri = qname.getNamespaceURI(); Set prefixes = (Set)uriToPrefix.get(uri); if(prefixes == null || prefixes.size() == 0) { undeclared.add(uri); if(declarations != null) declarations.add(new Namespace(lib, uri)); } } /** * Updates the internal state of this NamespaceHelper with the * namespace information of the element pointed to by the cursor. */ private void update(XmlCursor cursor, ObjArray declarations) { // Process the Namespace declarations cursor.push(); while(cursor.toNextToken().isAnyAttr()) { if(cursor.isNamespace()) { javax.xml.namespace.QName name = cursor.getName(); String prefix = name.getLocalPart(); String uri = name.getNamespaceURI(); declareNamespace(prefix, uri, declarations); } } cursor.pop(); // Process the element processName(cursor, declarations); // Process the attributes cursor.push(); boolean hasNext = cursor.toFirstAttribute(); while(hasNext) { processName(cursor, declarations); hasNext = cursor.toNextAttribute(); } cursor.pop(); } /** * @return Object[] array of Namespace objects in scope at the cursor. */ public static Object[] inScopeNamespaces(XMLLibImpl lib, XmlCursor cursor) { ObjArray namespaces = new ObjArray(); NamespaceHelper helper = new NamespaceHelper(lib); cursor.push(); int depth = 0; while(cursor.hasPrevToken()) { if(cursor.isContainer()) { cursor.push(); depth++; } cursor.toParent(); } for(int i = 0; i < depth; i++) { cursor.pop(); helper.update(cursor, null); } Iterator i = helper.prefixToURI.entrySet().iterator(); while(i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); Namespace ns = new Namespace(lib, (String)entry.getKey(), (String)entry.getValue()); namespaces.add(ns); } i = helper.undeclared.iterator(); while(i.hasNext()) { Namespace ns = new Namespace(lib, (String)i.next()); namespaces.add(ns); } cursor.pop(); return namespaces.toArray(); } static Namespace getNamespace(XMLLibImpl lib, XmlCursor cursor, Object[] inScopeNamespaces) { String uri; String prefix; if (cursor.isProcinst()) { uri = ""; prefix = ""; } else { javax.xml.namespace.QName qname = cursor.getName(); uri = qname.getNamespaceURI(); prefix = qname.getPrefix(); } if (inScopeNamespaces == null) return new Namespace(lib, prefix, uri); Namespace result = null; for (int i = 0; i != inScopeNamespaces.length; ++i) { Namespace ns = (Namespace)inScopeNamespaces[i]; if(ns == null) continue; String nsURI = ns.uri(); if(nsURI.equals(uri)) { if(prefix.equals(ns.prefix())) { result = ns; break; } if(result == null || (result.prefix() == null && ns.prefix() != null)) result = ns; } } if(result == null) result = new Namespace(lib, prefix, uri); return result; } /** * @return List of Namespace objects that are declared in the container pointed to by the cursor. */ public static Object[] namespaceDeclarations(XMLLibImpl lib, XmlCursor cursor) { ObjArray declarations = new ObjArray(); NamespaceHelper helper = new NamespaceHelper(lib); cursor.push(); int depth = 0; while(cursor.hasPrevToken()) { if(cursor.isContainer()) { cursor.push(); depth++; } cursor.toParent(); } for(int i = 0; i < depth - 1; i++) { cursor.pop(); helper.update(cursor, null); } if(depth > 0) { cursor.pop(); helper.update(cursor, declarations); } cursor.pop(); return declarations.toArray(); } /** * @return Prefix to URI map of all namespaces in scope at the cursor. */ public static Map getAllNamespaces(XMLLibImpl lib, XmlCursor cursor) { NamespaceHelper helper = new NamespaceHelper(lib); cursor.push(); int depth = 0; while(cursor.hasPrevToken()) { if(cursor.isContainer()) { cursor.push(); depth++; } cursor.toParent(); } for(int i = 0; i < depth; i++) { cursor.pop(); helper.update(cursor, null); } cursor.pop(); return helper.prefixToURI; } public static void getNamespaces(XmlCursor cursor, Map prefixToURI) { cursor.push(); while(cursor.toNextToken().isAnyAttr()) { if(cursor.isNamespace()) { javax.xml.namespace.QName name = cursor.getName(); String prefix = name.getLocalPart(); String uri = name.getNamespaceURI(); prefixToURI.put(prefix, uri); } } cursor.pop(); } public static void removeNamespace(XmlCursor cursor, String prefix) { cursor.push(); while(cursor.toNextToken().isAnyAttr()) { if(cursor.isNamespace()) { javax.xml.namespace.QName name = cursor.getName(); if(name.getLocalPart().equals(prefix)) { cursor.removeXml(); break; } } } cursor.pop(); } }././@LongLink0000000000000000000000000000016000000000000011212 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/XMLName.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/X0000644000175000017500000001152111314263504035630 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml.impl.xmlbeans; import org.mozilla.javascript.Context; import org.mozilla.javascript.Kit; import org.mozilla.javascript.Ref; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.Undefined; class XMLName extends Ref { static final long serialVersionUID = 3832176310755686977L; private String uri; private String localName; private boolean isAttributeName; private boolean isDescendants; private XMLObjectImpl xmlObject; private XMLName(String uri, String localName) { this.uri = uri; this.localName = localName; } static XMLName formStar() { return new XMLName(null, "*"); } static XMLName formProperty(String uri, String localName) { return new XMLName(uri, localName); } void initXMLObject(XMLObjectImpl xmlObject) { if (xmlObject == null) throw new IllegalArgumentException(); if (this.xmlObject != null) throw new IllegalStateException(); this.xmlObject = xmlObject; } String uri() { return uri; } String localName() { return localName; } boolean isAttributeName() { return isAttributeName; } void setAttributeName() { if (isAttributeName) throw new IllegalStateException(); isAttributeName = true; } boolean isDescendants() { return isDescendants; } void setIsDescendants() { if (isDescendants) throw new IllegalStateException(); isDescendants = true; } public boolean has(Context cx) { if (xmlObject == null) { return false; } return xmlObject.hasXMLProperty(this); } public Object get(Context cx) { if (xmlObject == null) { throw ScriptRuntime.undefReadError(Undefined.instance, toString()); } return xmlObject.getXMLProperty(this); } public Object set(Context cx, Object value) { if (xmlObject == null) { throw ScriptRuntime.undefWriteError(Undefined.instance, toString(), value); } // Assignment to descendants causes parse error on bad reference // and this should not be called if (isDescendants) throw Kit.codeBug(); xmlObject.putXMLProperty(this, value); return value; } public boolean delete(Context cx) { if (xmlObject == null) { return true; } xmlObject.deleteXMLProperty(this); return !xmlObject.hasXMLProperty(this); } public String toString() { //return qname.localName(); StringBuffer buff = new StringBuffer(); if (isDescendants) buff.append(".."); if (isAttributeName) buff.append('@'); if (uri == null) { buff.append('*'); if(localName().equals("*")) { return buff.toString(); } } else { buff.append('"').append(uri()).append('"'); } buff.append(':').append(localName()); return buff.toString(); } } ././@LongLink0000000000000000000000000000016600000000000011220 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/XMLObjectImpl.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/X0000644000175000017500000006531011314263504035635 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Ethan Hugg * Terry Lucas * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml.impl.xmlbeans; import org.mozilla.javascript.*; import org.mozilla.javascript.xml.*; /** * This abstract class describes what all XML objects (XML, XMLList) should have in common. * * @see XML */ abstract class XMLObjectImpl extends XMLObject { private static final Object XMLOBJECT_TAG = "XMLObject"; protected final XMLLibImpl lib; protected boolean prototypeFlag; protected XMLObjectImpl(XMLLibImpl lib, XMLObject prototype) { super(lib.globalScope(), prototype); this.lib = lib; } /** * ecmaHas(cx, id) calls this after resolving when id to XMLName * and checking it is not Uint32 index. */ abstract boolean hasXMLProperty(XMLName name); /** * ecmaGet(cx, id) calls this after resolving when id to XMLName * and checking it is not Uint32 index. */ abstract Object getXMLProperty(XMLName name); /** * ecmaPut(cx, id, value) calls this after resolving when id to XMLName * and checking it is not Uint32 index. */ abstract void putXMLProperty(XMLName name, Object value); /** * ecmaDelete(cx, id) calls this after resolving when id to XMLName * and checking it is not Uint32 index. */ abstract void deleteXMLProperty(XMLName name); /** * Test XML equality with target the target. */ abstract boolean equivalentXml(Object target); // Methods from section 12.4.4 in the spec abstract XML addNamespace(Namespace ns); abstract XML appendChild(Object xml); abstract XMLList attribute(XMLName xmlName); abstract XMLList attributes(); abstract XMLList child(long index); abstract XMLList child(XMLName xmlName); abstract int childIndex(); abstract XMLList children(); abstract XMLList comments(); abstract boolean contains(Object xml); abstract Object copy(); abstract XMLList descendants(XMLName xmlName); abstract Object[] inScopeNamespaces(); abstract XML insertChildAfter(Object child, Object xml); abstract XML insertChildBefore(Object child, Object xml); abstract boolean hasOwnProperty(XMLName xmlName); abstract boolean hasComplexContent(); abstract boolean hasSimpleContent(); abstract int length(); abstract String localName(); abstract QName name(); abstract Object namespace(String prefix); abstract Object[] namespaceDeclarations(); abstract Object nodeKind(); abstract void normalize(); abstract Object parent(); abstract XML prependChild(Object xml); abstract Object processingInstructions(XMLName xmlName); abstract boolean propertyIsEnumerable(Object member); abstract XML removeNamespace(Namespace ns); abstract XML replace(long index, Object xml); abstract XML replace(XMLName name, Object xml); abstract XML setChildren(Object xml); abstract void setLocalName(String name); abstract void setName(QName xmlName); abstract void setNamespace(Namespace ns); abstract XMLList text(); public abstract String toString(); abstract String toSource(int indent); abstract String toXMLString(int indent); abstract Object valueOf(); /** * Extension to access native implementation from scripts */ abstract org.apache.xmlbeans.XmlObject getXmlObject(); protected abstract Object jsConstructor(Context cx, boolean inNewExpr, Object[] args); final Object getMethod(String id) { return super.get(id, this); } // // // Methods overriding ScriptableObject // // public final Object getDefaultValue(Class hint) { return toString(); } public void delete(String name) { throw new IllegalArgumentException("String: [" + name + "]"); } /** * XMLObject always compare with any value and equivalentValues * never returns {@link Scriptable#NOT_FOUND} for them but rather * calls equivalentXml(value) and wrap the result as Boolean. */ protected final Object equivalentValues(Object value) { boolean result = equivalentXml(value); return result ? Boolean.TRUE : Boolean.FALSE; } // // // Methods overriding XMLObject // // public final XMLLib lib() { return lib; } /** * Implementation of ECMAScript [[Has]] */ public final boolean ecmaHas(Context cx, Object id) { if (cx == null) cx = Context.getCurrentContext(); XMLName xmlName = lib.toXMLNameOrIndex(cx, id); if (xmlName == null) { long index = ScriptRuntime.lastUint32Result(cx); // XXX Fix this cast return has((int)index, this); } return hasXMLProperty(xmlName); } /** * Implementation of ECMAScript [[Get]] */ public final Object ecmaGet(Context cx, Object id) { if (cx == null) cx = Context.getCurrentContext(); XMLName xmlName = lib.toXMLNameOrIndex(cx, id); if (xmlName == null) { long index = ScriptRuntime.lastUint32Result(cx); // XXX Fix this cast Object result = get((int)index, this); if (result == Scriptable.NOT_FOUND) { result = Undefined.instance; } return result; } return getXMLProperty(xmlName); } /** * Implementation of ECMAScript [[Put]] */ public final void ecmaPut(Context cx, Object id, Object value) { if (cx == null) cx = Context.getCurrentContext(); XMLName xmlName = lib.toXMLNameOrIndex(cx, id); if (xmlName == null) { long index = ScriptRuntime.lastUint32Result(cx); // XXX Fix this cast put((int)index, this, value); return; } putXMLProperty(xmlName, value); } /** * Implementation of ECMAScript [[Delete]]. */ public final boolean ecmaDelete(Context cx, Object id) { if (cx == null) cx = Context.getCurrentContext(); XMLName xmlName = lib.toXMLNameOrIndex(cx, id); if (xmlName == null) { long index = ScriptRuntime.lastUint32Result(cx); // XXX Fix this delete((int)index); return true; } deleteXMLProperty(xmlName); return true; } public Ref memberRef(Context cx, Object elem, int memberTypeFlags) { XMLName xmlName; if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) != 0) { xmlName = lib.toAttributeName(cx, elem); } else { if ((memberTypeFlags & Node.DESCENDANTS_FLAG) == 0) { // Code generation would use ecma(Get|Has|Delete|Set) for // normal name idenrifiers so one ATTRIBUTE_FLAG // or DESCENDANTS_FLAG has to be set throw Kit.codeBug(); } xmlName = lib.toXMLName(cx, elem); } if ((memberTypeFlags & Node.DESCENDANTS_FLAG) != 0) { xmlName.setIsDescendants(); } xmlName.initXMLObject(this); return xmlName; } /** * Generic reference to implement x::ns, x.@ns::y, x..@ns::y etc. */ public Ref memberRef(Context cx, Object namespace, Object elem, int memberTypeFlags) { XMLName xmlName = lib.toQualifiedName(cx, namespace, elem); if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) != 0) { if (!xmlName.isAttributeName()) { xmlName.setAttributeName(); } } if ((memberTypeFlags & Node.DESCENDANTS_FLAG) != 0) { xmlName.setIsDescendants(); } xmlName.initXMLObject(this); return xmlName; } public NativeWith enterWith(Scriptable scope) { return new XMLWithScope(lib, scope, this); } public NativeWith enterDotQuery(Scriptable scope) { XMLWithScope xws = new XMLWithScope(lib, scope, this); xws.initAsDotQuery(); return xws; } public final Object addValues(Context cx, boolean thisIsLeft, Object value) { if (value instanceof XMLObject) { XMLObject v1, v2; if (thisIsLeft) { v1 = this; v2 = (XMLObject)value; } else { v1 = (XMLObject)value; v2 = this; } return lib.addXMLObjects(cx, v1, v2); } if (value == Undefined.instance) { // both "xml + undefined" and "undefined + xml" gives String(xml) return ScriptRuntime.toString(this); } return super.addValues(cx, thisIsLeft, value); } // // // IdScriptableObject machinery // // final void exportAsJSClass(boolean sealed) { prototypeFlag = true; exportAsJSClass(MAX_PROTOTYPE_ID, lib.globalScope(), sealed); } // #string_id_map# private final static int Id_constructor = 1, Id_addNamespace = 2, Id_appendChild = 3, Id_attribute = 4, Id_attributes = 5, Id_child = 6, Id_childIndex = 7, Id_children = 8, Id_comments = 9, Id_contains = 10, Id_copy = 11, Id_descendants = 12, Id_inScopeNamespaces = 13, Id_insertChildAfter = 14, Id_insertChildBefore = 15, Id_hasOwnProperty = 16, Id_hasComplexContent = 17, Id_hasSimpleContent = 18, Id_length = 19, Id_localName = 20, Id_name = 21, Id_namespace = 22, Id_namespaceDeclarations = 23, Id_nodeKind = 24, Id_normalize = 25, Id_parent = 26, Id_prependChild = 27, Id_processingInstructions = 28, Id_propertyIsEnumerable = 29, Id_removeNamespace = 30, Id_replace = 31, Id_setChildren = 32, Id_setLocalName = 33, Id_setName = 34, Id_setNamespace = 35, Id_text = 36, Id_toString = 37, Id_toSource = 38, Id_toXMLString = 39, Id_valueOf = 40, Id_getXmlObject = 41, MAX_PROTOTYPE_ID = 41; protected int findPrototypeId(String s) { int id; // #generated# Last update: 2004-11-10 15:38:11 CET L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 4: c=s.charAt(0); if (c=='c') { X="copy";id=Id_copy; } else if (c=='n') { X="name";id=Id_name; } else if (c=='t') { X="text";id=Id_text; } break L; case 5: X="child";id=Id_child; break L; case 6: c=s.charAt(0); if (c=='l') { X="length";id=Id_length; } else if (c=='p') { X="parent";id=Id_parent; } break L; case 7: c=s.charAt(0); if (c=='r') { X="replace";id=Id_replace; } else if (c=='s') { X="setName";id=Id_setName; } else if (c=='v') { X="valueOf";id=Id_valueOf; } break L; case 8: switch (s.charAt(4)) { case 'K': X="nodeKind";id=Id_nodeKind; break L; case 'a': X="contains";id=Id_contains; break L; case 'd': X="children";id=Id_children; break L; case 'e': X="comments";id=Id_comments; break L; case 'r': X="toString";id=Id_toString; break L; case 'u': X="toSource";id=Id_toSource; break L; } break L; case 9: switch (s.charAt(2)) { case 'c': X="localName";id=Id_localName; break L; case 'm': X="namespace";id=Id_namespace; break L; case 'r': X="normalize";id=Id_normalize; break L; case 't': X="attribute";id=Id_attribute; break L; } break L; case 10: c=s.charAt(0); if (c=='a') { X="attributes";id=Id_attributes; } else if (c=='c') { X="childIndex";id=Id_childIndex; } break L; case 11: switch (s.charAt(0)) { case 'a': X="appendChild";id=Id_appendChild; break L; case 'c': X="constructor";id=Id_constructor; break L; case 'd': X="descendants";id=Id_descendants; break L; case 's': X="setChildren";id=Id_setChildren; break L; case 't': X="toXMLString";id=Id_toXMLString; break L; } break L; case 12: switch (s.charAt(0)) { case 'a': X="addNamespace";id=Id_addNamespace; break L; case 'g': X="getXmlObject";id=Id_getXmlObject; break L; case 'p': X="prependChild";id=Id_prependChild; break L; case 's': c=s.charAt(3); if (c=='L') { X="setLocalName";id=Id_setLocalName; } else if (c=='N') { X="setNamespace";id=Id_setNamespace; } break L; } break L; case 14: X="hasOwnProperty";id=Id_hasOwnProperty; break L; case 15: X="removeNamespace";id=Id_removeNamespace; break L; case 16: c=s.charAt(0); if (c=='h') { X="hasSimpleContent";id=Id_hasSimpleContent; } else if (c=='i') { X="insertChildAfter";id=Id_insertChildAfter; } break L; case 17: c=s.charAt(3); if (c=='C') { X="hasComplexContent";id=Id_hasComplexContent; } else if (c=='c') { X="inScopeNamespaces";id=Id_inScopeNamespaces; } else if (c=='e') { X="insertChildBefore";id=Id_insertChildBefore; } break L; case 20: X="propertyIsEnumerable";id=Id_propertyIsEnumerable; break L; case 21: X="namespaceDeclarations";id=Id_namespaceDeclarations; break L; case 22: X="processingInstructions";id=Id_processingInstructions; break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# return id; } // #/string_id_map# protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: { IdFunctionObject ctor; if (this instanceof XML) { ctor = new XMLCtor((XML)this, XMLOBJECT_TAG, id, 1); } else { ctor = new IdFunctionObject(this, XMLOBJECT_TAG, id, 1); } initPrototypeConstructor(ctor); return; } case Id_addNamespace: arity=1; s="addNamespace"; break; case Id_appendChild: arity=1; s="appendChild"; break; case Id_attribute: arity=1; s="attribute"; break; case Id_attributes: arity=0; s="attributes"; break; case Id_child: arity=1; s="child"; break; case Id_childIndex: arity=0; s="childIndex"; break; case Id_children: arity=0; s="children"; break; case Id_comments: arity=0; s="comments"; break; case Id_contains: arity=1; s="contains"; break; case Id_copy: arity=0; s="copy"; break; case Id_descendants: arity=1; s="descendants"; break; case Id_hasComplexContent: arity=0; s="hasComplexContent"; break; case Id_hasOwnProperty: arity=1; s="hasOwnProperty"; break; case Id_hasSimpleContent: arity=0; s="hasSimpleContent"; break; case Id_inScopeNamespaces: arity=0; s="inScopeNamespaces"; break; case Id_insertChildAfter: arity=2; s="insertChildAfter"; break; case Id_insertChildBefore: arity=2; s="insertChildBefore"; break; case Id_length: arity=0; s="length"; break; case Id_localName: arity=0; s="localName"; break; case Id_name: arity=0; s="name"; break; case Id_namespace: arity=1; s="namespace"; break; case Id_namespaceDeclarations: arity=0; s="namespaceDeclarations"; break; case Id_nodeKind: arity=0; s="nodeKind"; break; case Id_normalize: arity=0; s="normalize"; break; case Id_parent: arity=0; s="parent"; break; case Id_prependChild: arity=1; s="prependChild"; break; case Id_processingInstructions: arity=1; s="processingInstructions"; break; case Id_propertyIsEnumerable: arity=1; s="propertyIsEnumerable"; break; case Id_removeNamespace: arity=1; s="removeNamespace"; break; case Id_replace: arity=2; s="replace"; break; case Id_setChildren: arity=1; s="setChildren"; break; case Id_setLocalName: arity=1; s="setLocalName"; break; case Id_setName: arity=1; s="setName"; break; case Id_setNamespace: arity=1; s="setNamespace"; break; case Id_text: arity=0; s="text"; break; case Id_toString: arity=0; s="toString"; break; case Id_toSource: arity=1; s="toSource"; break; case Id_toXMLString: arity=1; s="toXMLString"; break; case Id_valueOf: arity=0; s="valueOf"; break; case Id_getXmlObject: arity=0; s="getXmlObject"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(XMLOBJECT_TAG, id, s, arity); } /** * * @param f * @param cx * @param scope * @param thisObj * @param args * @return */ public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(XMLOBJECT_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); if (id == Id_constructor) { return jsConstructor(cx, thisObj == null, args); } // All (XML|XMLList).prototype methods require thisObj to be XML if (!(thisObj instanceof XMLObjectImpl)) throw incompatibleCallError(f); XMLObjectImpl realThis = (XMLObjectImpl)thisObj; switch (id) { case Id_addNamespace: { Namespace ns = lib.castToNamespace(cx, arg(args, 0)); return realThis.addNamespace(ns); } case Id_appendChild: return realThis.appendChild(arg(args, 0)); case Id_attribute: { XMLName xmlName = lib.toAttributeName(cx, arg(args, 0)); return realThis.attribute(xmlName); } case Id_attributes: return realThis.attributes(); case Id_child: { XMLName xmlName = lib.toXMLNameOrIndex(cx, arg(args, 0)); if (xmlName == null) { long index = ScriptRuntime.lastUint32Result(cx); return realThis.child(index); } else { return realThis.child(xmlName); } } case Id_childIndex: return ScriptRuntime.wrapInt(realThis.childIndex()); case Id_children: return realThis.children(); case Id_comments: return realThis.comments(); case Id_contains: return ScriptRuntime.wrapBoolean( realThis.contains(arg(args, 0))); case Id_copy: return realThis.copy(); case Id_descendants: { XMLName xmlName = (args.length == 0) ? XMLName.formStar() : lib.toXMLName(cx, args[0]); return realThis.descendants(xmlName); } case Id_inScopeNamespaces: { Object[] array = realThis.inScopeNamespaces(); return cx.newArray(scope, array); } case Id_insertChildAfter: return realThis.insertChildAfter(arg(args, 0), arg(args, 1)); case Id_insertChildBefore: return realThis.insertChildBefore(arg(args, 0), arg(args, 1)); case Id_hasOwnProperty: { XMLName xmlName = lib.toXMLName(cx, arg(args, 0)); return ScriptRuntime.wrapBoolean( realThis.hasOwnProperty(xmlName)); } case Id_hasComplexContent: return ScriptRuntime.wrapBoolean(realThis.hasComplexContent()); case Id_hasSimpleContent: return ScriptRuntime.wrapBoolean(realThis.hasSimpleContent()); case Id_length: return ScriptRuntime.wrapInt(realThis.length()); case Id_localName: return realThis.localName(); case Id_name: return realThis.name(); case Id_namespace: { String prefix = (args.length > 0) ? ScriptRuntime.toString(args[0]) : null; return realThis.namespace(prefix); } case Id_namespaceDeclarations: { Object[] array = realThis.namespaceDeclarations(); return cx.newArray(scope, array); } case Id_nodeKind: return realThis.nodeKind(); case Id_normalize: realThis.normalize(); return Undefined.instance; case Id_parent: return realThis.parent(); case Id_prependChild: return realThis.prependChild(arg(args, 0)); case Id_processingInstructions: { XMLName xmlName = (args.length > 0) ? lib.toXMLName(cx, args[0]) : XMLName.formStar(); return realThis.processingInstructions(xmlName); } case Id_propertyIsEnumerable: { return ScriptRuntime.wrapBoolean( realThis.propertyIsEnumerable(arg(args, 0))); } case Id_removeNamespace: { Namespace ns = lib.castToNamespace(cx, arg(args, 0)); return realThis.removeNamespace(ns); } case Id_replace: { XMLName xmlName = lib.toXMLNameOrIndex(cx, arg(args, 0)); Object arg1 = arg(args, 1); if (xmlName == null) { long index = ScriptRuntime.lastUint32Result(cx); return realThis.replace(index, arg1); } else { return realThis.replace(xmlName, arg1); } } case Id_setChildren: return realThis.setChildren(arg(args, 0)); case Id_setLocalName: { String localName; Object arg = arg(args, 0); if (arg instanceof QName) { localName = ((QName)arg).localName(); } else { localName = ScriptRuntime.toString(arg); } realThis.setLocalName(localName); return Undefined.instance; } case Id_setName: { Object arg = (args.length != 0) ? args[0] : Undefined.instance; QName qname; if (arg instanceof QName) { qname = (QName)arg; if (qname.uri() == null) { qname = lib.constructQNameFromString(cx, qname.localName()); } else { // E4X 13.4.4.35 requires to always construct QName qname = lib.constructQName(cx, qname); } } else { qname = lib.constructQName(cx, arg); } realThis.setName(qname); return Undefined.instance; } case Id_setNamespace: { Namespace ns = lib.castToNamespace(cx, arg(args, 0)); realThis.setNamespace(ns); return Undefined.instance; } case Id_text: return realThis.text(); case Id_toString: return realThis.toString(); case Id_toSource: { int indent = ScriptRuntime.toInt32(args, 0); return realThis.toSource(indent); } case Id_toXMLString: { int indent = ScriptRuntime.toInt32(args, 0); return realThis.toXMLString(indent); } case Id_valueOf: return realThis.valueOf(); case Id_getXmlObject: { org.apache.xmlbeans.XmlObject xmlObject = realThis.getXmlObject(); return Context.javaToJS(xmlObject, scope); } } throw new IllegalArgumentException(String.valueOf(id)); } private static Object arg(Object[] args, int i) { return (i < args.length) ? args[i] : Undefined.instance; } }././@LongLink0000000000000000000000000000016000000000000011212 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/XMLList.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/X0000644000175000017500000011110411314263504035626 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ethan Hugg * Terry Lucas * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml.impl.xmlbeans; import java.util.Vector; import org.mozilla.javascript.*; import org.mozilla.javascript.xml.*; import org.apache.xmlbeans.XmlCursor; class XMLList extends XMLObjectImpl implements Function { static final long serialVersionUID = -4543618751670781135L; static class AnnotationList { private Vector v; AnnotationList () { v = new Vector(); } void add (XML.XScriptAnnotation n) { v.add(n); } XML.XScriptAnnotation item(int index) { return (XML.XScriptAnnotation)(v.get(index)); } void remove (int index) { v.remove(index); } int length() { return v.size(); } }; // Fields private AnnotationList _annos; private XMLObjectImpl targetObject = null; private javax.xml.namespace.QName targetProperty = null; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Constructors // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * */ XMLList(XMLLibImpl lib) { super(lib, lib.xmlListPrototype); _annos = new AnnotationList(); } /** * * @param inputObject */ XMLList(XMLLibImpl lib, Object inputObject) { super(lib, lib.xmlListPrototype); String frag; if (inputObject == null || inputObject instanceof Undefined) { frag = ""; } else if (inputObject instanceof XML) { XML xml = (XML) inputObject; _annos = new AnnotationList(); _annos.add(xml.getAnnotation()); } else if (inputObject instanceof XMLList) { XMLList xmll = (XMLList) inputObject; _annos = new AnnotationList(); for (int i = 0; i < xmll._annos.length(); i++) { _annos.add(xmll._annos.item(i)); } } else { frag = ScriptRuntime.toString(inputObject).trim(); if (!frag.startsWith("<>")) { frag = "<>" + frag + ""; } frag = "" + frag.substring(2); if (!frag.endsWith("")) { throw ScriptRuntime.typeError("XML with anonymous tag missing end anonymous tag"); } frag = frag.substring(0, frag.length() - 3) + ""; XML orgXML = XML.createFromJS(lib, frag); // Now orphan the children and add them to our XMLList. XMLList children = orgXML.children(); _annos = new AnnotationList(); for (int i = 0; i < children._annos.length(); i++) { // Copy here is so that they'll be orphaned (parent() will be undefined) _annos.add(((XML) children.item(i).copy()).getAnnotation()); } } } // // // TargetObject/Property accessors // // /** * * @param object * @param property */ void setTargets(XMLObjectImpl object, javax.xml.namespace.QName property) { targetObject = object; targetProperty = property; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Private functions // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * * @param index * @return */ XML getXmlFromAnnotation(int index) { XML retVal; if (index >= 0 && index < length()) { XML.XScriptAnnotation anno = _annos.item(index); retVal = XML.getFromAnnotation(lib, anno); } else { retVal = null; } return retVal; } /** * * @param index */ private void internalRemoveFromList (int index) { _annos.remove(index); } /** * * @param index * @param xml */ void replace(int index, XML xml) { if (index < length()) { AnnotationList newAnnoList = new AnnotationList(); // Copy upto item to replace. for (int i = 0; i < index; i++) { newAnnoList.add(_annos.item(i)); } newAnnoList.add(xml.getAnnotation()); // Skip over old item we're going to replace we've already add new item on above line. for (int i = index + 1; i < length(); i++) { newAnnoList.add(_annos.item(i)); } _annos = newAnnoList; } } /** * * @param index * @param xml */ private void insert(int index, XML xml) { if (index < length()) { AnnotationList newAnnoList = new AnnotationList(); // Copy upto item to insert. for (int i = 0; i < index; i++) { newAnnoList.add(_annos.item(i)); } newAnnoList.add(xml.getAnnotation()); for (int i = index; i < length(); i++) { newAnnoList.add(_annos.item(i)); } _annos = newAnnoList; } } // // // methods overriding ScriptableObject // // public String getClassName () { return "XMLList"; } // // // methods overriding IdScriptableObject // // /** * * @param index * @param start * @return */ public Object get(int index, Scriptable start) { //Log("get index: " + index); if (index >= 0 && index < length()) { return getXmlFromAnnotation(index); } else { return Scriptable.NOT_FOUND; } } /** * * @param name * @param start * @return */ boolean hasXMLProperty(XMLName xmlName) { boolean result = false; // Has now should return true if the property would have results > 0 or // if it's a method name String name = xmlName.localName(); if ((getPropertyList(xmlName).length() > 0) || (getMethod(name) != NOT_FOUND)) { result = true; } return result; } /** * * @param index * @param start * @return */ public boolean has(int index, Scriptable start) { return 0 <= index && index < length(); } /** * * @param name * @param value */ void putXMLProperty(XMLName xmlName, Object value) { //Log("put property: " + name); // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (length() > 1) { throw ScriptRuntime.typeError("Assignment to lists with more that one item is not supported"); } else if (length() == 0) { // Secret sauce for super-expandos. // We set an element here, and then add ourselves to our target. if (targetObject != null && targetProperty != null && !targetProperty.getLocalPart().equals("*")) { // Add an empty element with our targetProperty name and then set it. XML xmlValue = XML.createTextElement(lib, targetProperty, ""); addToList(xmlValue); if(xmlName.isAttributeName()) { setAttribute(xmlName, value); } else { XML xml = item(0); xml.putXMLProperty(xmlName, value); // Update the list with the new item at location 0. replace(0, item(0)); } // Now add us to our parent XMLName name2 = XMLName.formProperty(targetProperty.getNamespaceURI(), targetProperty.getLocalPart()); targetObject.putXMLProperty(name2, this); } else { throw ScriptRuntime.typeError("Assignment to empty XMLList without targets not supported"); } } else if(xmlName.isAttributeName()) { setAttribute(xmlName, value); } else { XML xml = item(0); xml.putXMLProperty(xmlName, value); // Update the list with the new item at location 0. replace(0, item(0)); } } /** * * @param name * @return */ Object getXMLProperty(XMLName name) { return getPropertyList(name); } /** * * @param index * @param value */ public void put(int index, Scriptable start, Object value) { Object parent = Undefined.instance; // Convert text into XML if needed. XMLObject xmlValue; // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (value instanceof XMLObject) { xmlValue = (XMLObject) value; } else { if (targetProperty == null) { xmlValue = XML.createFromJS(lib, value.toString()); } else { xmlValue = XML.createTextElement(lib, targetProperty, value.toString()); } } // Find the parent if (index < length()) { parent = item(index).parent(); } else { // Appending parent = parent(); } if (parent instanceof XML) { // found parent, alter doc XML xmlParent = (XML) parent; if (index < length()) { // We're replacing the the node. XML xmlNode = getXmlFromAnnotation(index); if (xmlValue instanceof XML) { xmlNode.replaceAll((XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { int lastIndexAdded = xmlNode.childIndex(); xmlNode.replaceAll(list.item(0)); replace(index, list.item(0)); for (int i = 1; i < list.length(); i++) { xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i)); lastIndexAdded++; insert(index + i, list.item(i)); } } } } else { // Appending xmlParent.appendChild(xmlValue); addToList(xmlParent.getXmlChild(index)); } } else { // Don't all have same parent, no underlying doc to alter if (index < length()) { XML xmlNode = XML.getFromAnnotation(lib, _annos.item(index)); if (xmlValue instanceof XML) { xmlNode.replaceAll((XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { xmlNode.replaceAll(list.item(0)); replace(index, list.item(0)); for (int i = 1; i < list.length(); i++) { insert(index + i, list.item(i)); } } } } else { addToList(xmlValue); } } } /** * * @param name */ void deleteXMLProperty(XMLName name) { for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); if (xml.tokenType() == XmlCursor.TokenType.START) { xml.deleteXMLProperty(name); } } } /** * * @param index */ public void delete(int index) { if (index >= 0 && index < length()) { XML xml = getXmlFromAnnotation(index); xml.remove(); internalRemoveFromList(index); } } /** * * @return */ public Object[] getIds() { Object enumObjs[]; if (prototypeFlag) { enumObjs = new Object[0]; } else { enumObjs = new Object[length()]; for (int i = 0; i < enumObjs.length; i++) { enumObjs[i] = new Integer(i); } } return enumObjs; } /** * * @return */ public Object[] getIdsForDebug() { return getIds(); } // XMLList will remove will delete all items in the list (a set delete) this differs from the XMLList delete operator. void remove () { int nLen = length(); for (int i = nLen - 1; i >= 0; i--) { XML xml = getXmlFromAnnotation(i); if (xml != null) { xml.remove(); internalRemoveFromList(i); } } } /** * * @param index * @return */ XML item (int index) { return _annos != null ? getXmlFromAnnotation(index) : XML.createEmptyXML(lib); } /** * * @param name * @param value */ private void setAttribute (XMLName xmlName, Object value) { for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); xml.setAttribute(xmlName, value); } } /** * * @param toAdd */ void addToList(Object toAdd) { if (toAdd instanceof Undefined) { // Missing argument do nothing... return; } if (toAdd instanceof XMLList) { XMLList xmlSrc = (XMLList)toAdd; for (int i = 0; i < xmlSrc.length(); i++) { _annos.add((xmlSrc.item(i)).getAnnotation()); } } else if (toAdd instanceof XML) { _annos.add(((XML)(toAdd)).getAnnotation()); } else if (toAdd instanceof XML.XScriptAnnotation) { _annos.add((XML.XScriptAnnotation)toAdd); } } // // // Methods from section 12.4.4 in the spec // // /** * * @param toAdd */ XML addNamespace(Namespace ns) { if(length() == 1) { return getXmlFromAnnotation(0).addNamespace(ns); } else { throw ScriptRuntime.typeError("The addNamespace method works only on lists containing one item"); } } /** * * @param xml * @return */ XML appendChild(Object xml) { if (length() == 1) { return getXmlFromAnnotation(0).appendChild(xml); } else { throw ScriptRuntime.typeError("The appendChild method works only on lists containing one item"); } } /** * * @param attr * @return */ XMLList attribute(XMLName xmlName) { XMLList result = new XMLList(lib); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.attribute(xmlName)); } return result; } /** * * @return */ XMLList attributes() { XMLList result = new XMLList(lib); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.attributes()); } return result; } XMLList child(long index) { XMLList result = new XMLList(lib); for (int i = 0; i < length(); i++) { result.addToList(getXmlFromAnnotation(i).child(index)); } return result; } XMLList child(XMLName xmlName) { XMLList result = new XMLList(lib); for (int i = 0; i < length(); i++) { result.addToList(getXmlFromAnnotation(i).child(xmlName)); } return result; } /** * * @return */ int childIndex() { if (length() == 1) { return getXmlFromAnnotation(0).childIndex(); } else { throw ScriptRuntime.typeError("The childIndex method works only on lists containing one item"); } } /** * * @return */ XMLList children() { Vector v = new Vector(); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); if (xml != null) { Object o = xml.children(); if (o instanceof XMLList) { XMLList childList = (XMLList)o; int cChildren = childList.length(); for (int j = 0; j < cChildren; j++) { v.addElement(childList.item(j)); } } } } XMLList allChildren = new XMLList(lib); int sz = v.size(); for (int i = 0; i < sz; i++) { allChildren.addToList(v.get(i)); } return allChildren; } /** * * @return */ XMLList comments() { XMLList result = new XMLList(lib); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.comments()); } return result; } /** * * @param xml * @return */ boolean contains(Object xml) { boolean result = false; for (int i = 0; i < length(); i++) { XML member = getXmlFromAnnotation(i); if (member.equivalentXml(xml)) { result = true; break; } } return result; } /** * * @return */ Object copy() { XMLList result = new XMLList(lib); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.copy()); } return result; } /** * * @return */ XMLList descendants(XMLName xmlName) { XMLList result = new XMLList(lib); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.descendants(xmlName)); } return result; } /** * * @return */ Object[] inScopeNamespaces() { if(length() == 1) { return getXmlFromAnnotation(0).inScopeNamespaces(); } else { throw ScriptRuntime.typeError("The inScopeNamespaces method works only on lists containing one item"); } } /** * * @param child * @param xml */ XML insertChildAfter(Object child, Object xml) { if (length() == 1) { return getXmlFromAnnotation(0).insertChildAfter(child, xml); } else { throw ScriptRuntime.typeError("The insertChildAfter method works only on lists containing one item"); } } /** * * @param child * @param xml */ XML insertChildBefore(Object child, Object xml) { if (length() == 1) { return getXmlFromAnnotation(0).insertChildAfter(child, xml); } else { throw ScriptRuntime.typeError("The insertChildBefore method works only on lists containing one item"); } } /** * * @return */ boolean hasOwnProperty(XMLName xmlName) { boolean hasProperty = false; if (prototypeFlag) { String property = xmlName.localName(); hasProperty = (0 != findPrototypeId(property)); } else { hasProperty = (getPropertyList(xmlName).length() > 0); } return hasProperty; } /** * * @return */ boolean hasComplexContent() { boolean complexContent; int length = length(); if (length == 0) { complexContent = false; } else if (length == 1) { complexContent = getXmlFromAnnotation(0).hasComplexContent(); } else { complexContent = false; for (int i = 0; i < length; i++) { XML nextElement = getXmlFromAnnotation(i); if (nextElement.tokenType() == XmlCursor.TokenType.START) { complexContent = true; break; } } } return complexContent; } /** * * @return */ boolean hasSimpleContent() { boolean simpleContent; int length = length(); if (length == 0) { simpleContent = true; } else if (length == 1) { simpleContent = getXmlFromAnnotation(0).hasSimpleContent(); } else { simpleContent = true; for (int i = 0; i < length; i++) { XML nextElement = getXmlFromAnnotation(i); if (nextElement.tokenType() == XmlCursor.TokenType.START) { simpleContent = false; break; } } } return simpleContent; } /** * * @return */ int length() { int result = 0; if (_annos != null) { result = _annos.length(); } return result; } /** * * @return */ String localName() { if (length() == 1) { return name().localName(); } else { throw ScriptRuntime.typeError("The localName method works only on lists containing one item"); } } /** * * @return */ QName name() { if (length() == 1) { return getXmlFromAnnotation(0).name(); } else { throw ScriptRuntime.typeError("The name method works only on lists containing one item"); } } /** * * @param prefix * @return */ Object namespace(String prefix) { if (length() == 1) { return getXmlFromAnnotation(0).namespace(prefix); } else { throw ScriptRuntime.typeError("The namespace method works only on lists containing one item"); } } /** * * @return */ Object[] namespaceDeclarations() { if (length() == 1) { return getXmlFromAnnotation(0).namespaceDeclarations(); } else { throw ScriptRuntime.typeError("The namespaceDeclarations method works only on lists containing one item"); } } /** * * @return */ Object nodeKind() { if (length() == 1) { return getXmlFromAnnotation(0).nodeKind(); } else { throw ScriptRuntime.typeError("The nodeKind method works only on lists containing one item"); } } /** * */ void normalize() { for (int i = 0; i < length(); i++) { getXmlFromAnnotation(i).normalize(); } } /** * If list is empty, return undefined, if elements have different parents return undefined, * If they all have the same parent, return that parent. * * @return */ Object parent() { Object sameParent = Undefined.instance; if ((length() == 0) && (targetObject != null) && (targetObject instanceof XML)) { sameParent = targetObject; } else { for (int i = 0; i < length(); i++) { Object currParent = getXmlFromAnnotation(i).parent(); if (i == 0) { // Set the first for the rest to compare to. sameParent = currParent; } else if (sameParent != currParent) { sameParent = Undefined.instance; break; } } } // If everything in the list is the sameParent then return that as the parent. return sameParent; } /** * * @param xml * @return */ XML prependChild(Object xml) { if (length() == 1) { return getXmlFromAnnotation(0).prependChild(xml); } else { throw ScriptRuntime.typeError("The prependChild method works only on lists containing one item"); } } /** * * @return */ Object processingInstructions(XMLName xmlName) { XMLList result = new XMLList(lib); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.processingInstructions(xmlName)); } return result; } /** * * @param name * @return */ boolean propertyIsEnumerable(Object name) { long index; if (name instanceof Integer) { index = ((Integer)name).intValue(); } else if (name instanceof Number) { double x = ((Number)name).doubleValue(); index = (long)x; if (index != x) { return false; } if (index == 0 && 1.0 / x < 0) { // Negative 0 return false; } } else { String s = ScriptRuntime.toString(name); index = ScriptRuntime.testUint32String(s); } return (0 <= index && index < length()); } /** * * @param ns */ XML removeNamespace(Namespace ns) { if(length() == 1) { return getXmlFromAnnotation(0).removeNamespace(ns); } else { throw ScriptRuntime.typeError("The removeNamespace method works only on lists containing one item"); } } XML replace(long index, Object xml) { if (length() == 1) { return getXmlFromAnnotation(0).replace(index, xml); } else { throw ScriptRuntime.typeError("The replace method works only on lists containing one item"); } } /** * * @param propertyName * @param xml * @return */ XML replace(XMLName xmlName, Object xml) { if (length() == 1) { return getXmlFromAnnotation(0).replace(xmlName, xml); } else { throw ScriptRuntime.typeError("The replace method works only on lists containing one item"); } } /** * * @param xml */ XML setChildren(Object xml) { if (length() == 1) { return getXmlFromAnnotation(0).setChildren(xml); } else { throw ScriptRuntime.typeError("The setChildren method works only on lists containing one item"); } } /** * * @param name */ void setLocalName(String localName) { if (length() == 1) { getXmlFromAnnotation(0).setLocalName(localName); } else { throw ScriptRuntime.typeError("The setLocalName method works only on lists containing one item"); } } /** * * @param name */ void setName(QName qname) { if (length() == 1) { getXmlFromAnnotation(0).setName(qname); } else { throw ScriptRuntime.typeError("The setName method works only on lists containing one item"); } } /** * * @param ns */ void setNamespace(Namespace ns) { if (length() == 1) { getXmlFromAnnotation(0).setNamespace(ns); } else { throw ScriptRuntime.typeError("The setNamespace method works only on lists containing one item"); } } /** * * * @return */ XMLList text() { XMLList result = new XMLList(lib); for (int i = 0; i < length(); i++) { result.addToList(getXmlFromAnnotation(i).text()); } return result; } /** * * @return */ public String toString() { if (hasSimpleContent()) { StringBuffer sb = new StringBuffer(); for(int i = 0; i < length(); i++) { XML next = getXmlFromAnnotation(i); sb.append(next.toString()); } return sb.toString(); } else { return toXMLString(0); } } String toSource(int indent) { // XXX indent is ignored return "<>"+toXMLString(0)+""; } /** * * @return */ String toXMLString(int indent) { StringBuffer sb = new StringBuffer(); for(int i = 0; i < length(); i++) { if (i > 0) { sb.append('\n'); } sb.append(getXmlFromAnnotation(i).toXMLString(indent)); } return sb.toString(); } /** * * @return */ Object valueOf() { return this; } // // Other public Functions from XMLObject // /** * * @param target * @return */ boolean equivalentXml(Object target) { boolean result = false; // Zero length list should equate to undefined if (target instanceof Undefined && length() == 0) { result = true; } else if (length() == 1) { result = getXmlFromAnnotation(0).equivalentXml(target); } else if (target instanceof XMLList) { XMLList otherList = (XMLList) target; if (otherList.length() == length()) { result = true; for (int i = 0; i < length(); i++) { if (!getXmlFromAnnotation(i).equivalentXml(otherList.getXmlFromAnnotation(i))) { result = false; break; } } } } return result; } /** * * @param name * @param start * @return */ private XMLList getPropertyList(XMLName name) { XMLList propertyList = new XMLList(lib); javax.xml.namespace.QName qname = null; if (!name.isDescendants() && !name.isAttributeName()) { // Only set the targetProperty if this is a regular child get // and not a descendant or attribute get qname = new javax.xml.namespace.QName(name.uri(), name.localName()); } propertyList.setTargets(this, qname); for (int i = 0; i < length(); i++) { propertyList.addToList( getXmlFromAnnotation(i).getPropertyList(name)); } return propertyList; } private Object applyOrCall(boolean isApply, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { String methodName = isApply ? "apply" : "call"; if(!(thisObj instanceof XMLList) || ((XMLList)thisObj).targetProperty == null) throw ScriptRuntime.typeError1("msg.isnt.function", methodName); return ScriptRuntime.applyOrCall(isApply, cx, scope, thisObj, args); } protected Object jsConstructor(Context cx, boolean inNewExpr, Object[] args) { if (args.length == 0) { return new XMLList(lib); } else { Object arg0 = args[0]; if (!inNewExpr && arg0 instanceof XMLList) { // XMLList(XMLList) returns the same object. return arg0; } return new XMLList(lib, arg0); } } org.apache.xmlbeans.XmlObject getXmlObject() { if (length() == 1) { return getXmlFromAnnotation(0).getXmlObject(); } else { throw ScriptRuntime.typeError("getXmlObject method works only on lists containing one item"); } } /** * See ECMA 357, 11_2_2_1, Semantics, 3_e. */ public Scriptable getExtraMethodSource(Context cx) { if (length() == 1) { return getXmlFromAnnotation(0); } return null; } public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { // This XMLList is being called as a Function. // Let's find the real Function object. if(targetProperty == null) throw ScriptRuntime.notFunctionError(this); String methodName = targetProperty.getLocalPart(); boolean isApply = methodName.equals("apply"); if(isApply || methodName.equals("call")) return applyOrCall(isApply, cx, scope, thisObj, args); Callable method = ScriptRuntime.getElemFunctionAndThis( this, methodName, cx); // Call lastStoredScriptable to clear stored thisObj // but ignore the result as the method should use the supplied // thisObj, not one from redirected call ScriptRuntime.lastStoredScriptable(cx); return method.call(cx, scope, thisObj, args); } public Scriptable construct(Context cx, Scriptable scope, Object[] args) { throw ScriptRuntime.typeError1("msg.not.ctor", "XMLList"); } } ././@LongLink0000000000000000000000000000015600000000000011217 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/QName.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/deprecatedsrc/org/mozilla/javascript/xml/impl/xmlbeans/Q0000644000175000017500000002137711314263504035633 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ethan Hugg * Terry Lucas * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml.impl.xmlbeans; import org.mozilla.javascript.*; /** * Class QName * */ final class QName extends IdScriptableObject { static final long serialVersionUID = 416745167693026750L; private static final Object QNAME_TAG = "QName"; XMLLibImpl lib; private String prefix; private String localName; private String uri; QName(XMLLibImpl lib, String uri, String localName, String prefix) { super(lib.globalScope(), lib.qnamePrototype); if (localName == null) throw new IllegalArgumentException(); this.lib = lib; this.uri = uri; this.prefix = prefix; this.localName = localName; } void exportAsJSClass(boolean sealed) { exportAsJSClass(MAX_PROTOTYPE_ID, lib.globalScope(), sealed); } /** * * @return */ public String toString() { String result; if (uri == null) { result = "*::".concat(localName); } else if(uri.length() == 0) { result = localName; } else { result = uri + "::" + localName; } return result; } public String localName() { return localName; } String prefix() { return (prefix == null) ? prefix : ""; } String uri() { return uri; } public boolean equals(Object obj) { if(!(obj instanceof QName)) return false; return equals((QName)obj); } protected Object equivalentValues(Object value) { if(!(value instanceof QName)) return Scriptable.NOT_FOUND; boolean result = equals((QName)value); return result ? Boolean.TRUE : Boolean.FALSE; } private boolean equals(QName q) { boolean result; if (uri == null) { result = q.uri == null && localName.equals(q.localName); } else { result = uri.equals(q.uri) && localName.equals(q.localName); } return result; } /** * * @return */ public String getClassName () { return "QName"; } /** * * @param hint * @return */ public Object getDefaultValue (Class hint) { return toString(); } // #string_id_map# private static final int Id_localName = 1, Id_uri = 2, MAX_INSTANCE_ID = 2; protected int getMaxInstanceId() { return super.getMaxInstanceId() + MAX_INSTANCE_ID; } protected int findInstanceIdInfo(String s) { int id; // #generated# Last update: 2004-07-18 12:32:51 CEST L0: { id = 0; String X = null; int s_length = s.length(); if (s_length==3) { X="uri";id=Id_uri; } else if (s_length==9) { X="localName";id=Id_localName; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# if (id == 0) return super.findInstanceIdInfo(s); int attr; switch (id) { case Id_localName: case Id_uri: attr = PERMANENT | READONLY; break; default: throw new IllegalStateException(); } return instanceIdInfo(attr, super.getMaxInstanceId() + id); } // #/string_id_map# protected String getInstanceIdName(int id) { switch (id - super.getMaxInstanceId()) { case Id_localName: return "localName"; case Id_uri: return "uri"; } return super.getInstanceIdName(id); } protected Object getInstanceIdValue(int id) { switch (id - super.getMaxInstanceId()) { case Id_localName: return localName; case Id_uri: return uri; } return super.getInstanceIdValue(id); } // #string_id_map# private static final int Id_constructor = 1, Id_toString = 2, Id_toSource = 3, MAX_PROTOTYPE_ID = 3; protected int findPrototypeId(String s) { int id; // #generated# Last update: 2004-08-21 12:45:13 CEST L0: { id = 0; String X = null; int c; int s_length = s.length(); if (s_length==8) { c=s.charAt(3); if (c=='o') { X="toSource";id=Id_toSource; } else if (c=='t') { X="toString";id=Id_toString; } } else if (s_length==11) { X="constructor";id=Id_constructor; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# return id; } // #/string_id_map# protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=2; s="constructor"; break; case Id_toString: arity=0; s="toString"; break; case Id_toSource: arity=0; s="toSource"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(QNAME_TAG, id, s, arity); } public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(QNAME_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); switch (id) { case Id_constructor: return jsConstructor(cx, (thisObj == null), args); case Id_toString: return realThis(thisObj, f).toString(); case Id_toSource: return realThis(thisObj, f).js_toSource(); } throw new IllegalArgumentException(String.valueOf(id)); } private QName realThis(Scriptable thisObj, IdFunctionObject f) { if(!(thisObj instanceof QName)) throw incompatibleCallError(f); return (QName)thisObj; } private Object jsConstructor(Context cx, boolean inNewExpr, Object[] args) { if (!inNewExpr && args.length == 1) { return lib.castToQName(cx, args[0]); } if (args.length == 0) { return lib.constructQName(cx, Undefined.instance); } else if (args.length == 1) { return lib.constructQName(cx, args[0]); } else { return lib.constructQName(cx, args[0], args[1]); } } private String js_toSource() { StringBuffer sb = new StringBuffer(); sb.append('('); toSourceImpl(uri, localName, prefix, sb); sb.append(')'); return sb.toString(); } private static void toSourceImpl(String uri, String localName, String prefix, StringBuffer sb) { sb.append("new QName("); if (uri == null && prefix == null) { if (!"*".equals(localName)) { sb.append("null, "); } } else { Namespace.toSourceImpl(prefix, uri, sb); sb.append(", "); } sb.append('\''); sb.append(ScriptRuntime.escapeString(localName, '\'')); sb.append("')"); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/0000755000175000017500000000000011537630013024375 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/build.xml0000644000175000017500000000531411314263504026221 0ustar jamespagejamespage00000000000000 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/0000755000175000017500000000000011537630013025164 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/0000755000175000017500000000000011537630013026633 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/0000755000175000017500000000000011537630013031001 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/0000755000175000017500000000000011537630013032141 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/ToolErrorReporter.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/ToolErrorReporter.j0000644000175000017500000001727711314263504036004 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Kurt Westerfeld * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools; import org.mozilla.javascript.*; import java.text.MessageFormat; import java.io.*; import java.util.*; /** * Error reporter for tools. * * Currently used by both the shell and the compiler. */ public class ToolErrorReporter implements ErrorReporter { public ToolErrorReporter(boolean reportWarnings) { this(reportWarnings, System.err); } public ToolErrorReporter(boolean reportWarnings, PrintStream err) { this.reportWarnings = reportWarnings; this.err = err; } /** * Look up the message corresponding to messageId in the * org.mozilla.javascript.tools.shell.resources.Messages property file. * For internationalization support. */ public static String getMessage(String messageId) { return getMessage(messageId, (Object []) null); } public static String getMessage(String messageId, String argument) { Object[] args = { argument }; return getMessage(messageId, args); } public static String getMessage(String messageId, Object arg1, Object arg2) { Object[] args = { arg1, arg2 }; return getMessage(messageId, args); } public static String getMessage(String messageId, Object[] args) { Context cx = Context.getCurrentContext(); Locale locale = cx == null ? Locale.getDefault() : cx.getLocale(); // ResourceBundle does caching. ResourceBundle rb = ResourceBundle.getBundle ("org.mozilla.javascript.tools.resources.Messages", locale); String formatString; try { formatString = rb.getString(messageId); } catch (java.util.MissingResourceException mre) { throw new RuntimeException("no message resource found for message property " + messageId); } if (args == null) { return formatString; } else { MessageFormat formatter = new MessageFormat(formatString); return formatter.format(args); } } private static String getExceptionMessage(RhinoException ex) { String msg; if (ex instanceof JavaScriptException) { msg = getMessage("msg.uncaughtJSException", ex.details()); } else if (ex instanceof EcmaError) { msg = getMessage("msg.uncaughtEcmaError", ex.details()); } else if (ex instanceof EvaluatorException) { msg = ex.details(); } else { msg = ex.toString(); } return msg; } public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) { if (!reportWarnings) return; reportErrorMessage(message, sourceName, line, lineSource, lineOffset, true); } public void error(String message, String sourceName, int line, String lineSource, int lineOffset) { hasReportedErrorFlag = true; reportErrorMessage(message, sourceName, line, lineSource, lineOffset, false); } public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) { return new EvaluatorException(message, sourceName, line, lineSource, lineOffset); } public boolean hasReportedError() { return hasReportedErrorFlag; } public boolean isReportingWarnings() { return this.reportWarnings; } public void setIsReportingWarnings(boolean reportWarnings) { this.reportWarnings = reportWarnings; } public static void reportException(ErrorReporter er, RhinoException ex) { if (er instanceof ToolErrorReporter) { ((ToolErrorReporter)er).reportException(ex); } else { String msg = getExceptionMessage(ex); er.error(msg, ex.sourceName(), ex.lineNumber(), ex.lineSource(), ex.columnNumber()); } } public void reportException(RhinoException ex) { if (ex instanceof WrappedException) { WrappedException we = (WrappedException)ex; we.printStackTrace(err); } else { String lineSeparator = SecurityUtilities.getSystemProperty("line.separator"); String msg = getExceptionMessage(ex) + lineSeparator + ex.getScriptStackTrace(); reportErrorMessage(msg, ex.sourceName(), ex.lineNumber(), ex.lineSource(), ex.columnNumber(), false); } } private void reportErrorMessage(String message, String sourceName, int line, String lineSource, int lineOffset, boolean justWarning) { if (line > 0) { String lineStr = String.valueOf(line); if (sourceName != null) { Object[] args = { sourceName, lineStr, message }; message = getMessage("msg.format3", args); } else { Object[] args = { lineStr, message }; message = getMessage("msg.format2", args); } } else { Object[] args = { message }; message = getMessage("msg.format1", args); } if (justWarning) { message = getMessage("msg.warning", message); } err.println(messagePrefix + message); if (null != lineSource) { err.println(messagePrefix + lineSource); err.println(messagePrefix + buildIndicator(lineOffset)); } } private String buildIndicator(int offset){ StringBuffer sb = new StringBuffer(); for (int i = 0; i < offset-1; i++) sb.append("."); sb.append("^"); return sb.toString(); } private final String messagePrefix = "js: "; private boolean hasReportedErrorFlag; private boolean reportWarnings; private PrintStream err; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/resources/0000755000175000017500000000000011537630013034153 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000015700000000000011220 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/resources/Messages.propertiesjenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/resources/Messages.0000644000175000017500000002434511314263504035733 0ustar jamespagejamespage00000000000000# # JavaScript tools messages file. # # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is Rhino code, released # May 6, 1999. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1997-1999 # the Initial Developer. All Rights Reserved. # # Contributor(s): # # Alternatively, the contents of this file may be used under the terms of # the GNU General Public License Version 2 or later (the "GPL"), in which # case the provisions of the GPL are applicable instead of those above. If # you wish to allow use of your version of this file only under the terms of # the GPL and not to allow others to use your version of this file under the # MPL, indicate your decision by deleting the provisions above and replacing # them with the notice and other provisions required by the GPL. If you do # not delete the provisions above, a recipient may use your version of this # file under either the MPL or the GPL. # # ***** END LICENSE BLOCK ***** msg.expected.string.arg =\ Expected a string argument. msg.class.not.found =\ Class "{0}" not found. msg.couldnt.open =\ Couldn''t open file "{0}". msg.couldnt.open.url =\ Couldn''t open URL "{0}: {1}". msg.couldnt.read.source =\ Couldn''t read source file "{0}: {1}". msg.no-opt =\ Must have the org.mozilla.javascript.optimizer package available \ to compile to class files. msg.shell.invalid =\ Invalid option "{0}" msg.shell.usage =\ Usage: java {0} [options...] [files]\n\ Valid options are:\n\ \ -?, -help Displays help messages.\n\ \ -w Enable warnings.\n\ \ -version 100|110|120|130|140|150|160|170\n\ \ Set a specific language version.\n\ \ -opt [-1|0-9] Set optimization level.\n\ \ -f script-filename Execute script file, or "-" for interactive.\n\ \ -e script-source Evaluate inline script.\n\ \ -debug Generate debug code.\n\ \ -strict Enable strict mode warnings.\n\ \ -fatal-warnings Treat warnings as errors.\n\ \ -encoding charset Use specified character encoding as default when reading scripts. msg.help =\ \n\ Command Description \n\ ======= =========== \n\ help() Display usage and help messages. \n\ defineClass(className) Define an extension using the Java class \n\ \ named with the string argument. \n\ \ Uses ScriptableObject.defineClass(). \n\ load(["foo.js", ...]) Load JavaScript source files named by \n\ \ string arguments. \n\ loadClass(className) Load a class named by a string argument. \n\ \ The class must be a script compiled to a \n\ \ class file. \n\ print([expr ...]) Evaluate and print expressions. \n\ quit() Quit the shell. \n\ version([number]) Get or set the JavaScript version number. \n\ gc() Runs the garbage collector.\n\ spawn(arg) Evaluate function or script name on a new thread \n\ sync(function) Creates a synchronized version of the function, \n\ \ where the synchronization object is "this" \n\ readFile(fileName [, encoding])\n\ \ Returns the content of the file as a string. \n\ \ Encoding of the string can be optionally specified. \n\ readUrl(url [, encoding]) \n\ \ Similar to readFile, reads the contents of the url.\n\ runCommand(name ...) Runs a specified shell command. Additional arguments are \n\ \ passed to the command \n\ seal(args ...) Seals the supplied objects \n\ toint32(arg) Converts the argument into a 32-bit integer \n\ serialize(obj, fileName) \n\ \ Serializes an object and saves it to a file \n\ deserialize(fileName) Reconstructs a serialized object \n\ environment Returns the current environment object \n\ history Displays the shell command history msg.warning =\ warning: {0} msg.format1 =\ {0} msg.format2 =\ line {0}: {1} msg.format3 =\ "{0}", line {1}: {2} msg.uncaughtJSException =\ exception from uncaught JavaScript throw: {0} msg.uncaughtEcmaError =\ uncaught JavaScript runtime exception: {0} msg.jsc.bad.usage =\ Didn''t understand "{1}". \n\ For more information, try java {0} -h msg.jsc.usage =\ Usage: java {0} [OPTION]... SOURCE...\n\ Valid options are: \n\ \ -version VERSION Use the specified language version.\n\ \ VERSION should be one of 100|110|120|130|140|150|160|170.\n\ \ -opt LEVEL Use optimization with the specified level.\n\ \ LEVEL should be one of 0..9.\n\ \ -debug, -g Include debug information.\n\ \ -nosource Do not include source to function objects.\n\ \ It makes f.toString() useless and violates ECMAScript\n\ \ standard but makes generated classes smaller and\n\ \ saves memory.\n\ \ -o CLASSNAME Use specified name as the last component of the main\n\ \ generated class name. When specified, only one script\n\ \ SOURCE is allowed. If omitted, it defaults to source\n\ \ name with stripped .js suffix.\n\ \ -package PACKAGE Place generated classes in the specified package.\n\ \ -d DIRECTORY Use DIRECTORY as destination directory for generated\n\ \ classes. If omitted, it defaults to parent directory\n\ \ of SOURCE.\n\ \ -encoding charset Sets the character encoding of the source files. \n\ \ -extends CLASS The main generated class will extend the specified\n\ \ class CLASS.\n\ \ -implements INTERFACE1,INTERFACE2,... The main generated class will\n\ \ implement the specified list of interfaces.\n\ \ -main-method-class CLASS Specify the class name used for main method \n\ \ implementation. The class must have a method matching\n\ \ "public static void main(Script sc, String[] args)"\n\ \ -observe-instruction-count Generate code that contains callbacks to \n\ \ accumulate counts of executed instructions. Code \n\ \ compiled with this flag can be monitored using \n\ \ Context.setInstructionObserverThreshold. \n\ \ -help, --help, -h Print this help and exit.\n\ msg.no.file =\ A file name must be specified to compile. msg.invalid.classfile.name =\ File "{0}" is not a valid class file name. msg.extension.not.js =\ File "{0}" is not a valid js file name. msg.jsfile.not.found=\ File "{0}" not found. msg.multiple.js.to.file =\ Cannot compile multiple js files to "{0}". msg.package.name =\ "{0}" is not a valid package name. msg.spawn.args =\ Argument to spawn() must be a function or script. msg.must.implement.Script =\ Argument to loadClass() must be the name of a class that implements \ the Script interface. Class files generated by compiling scripts \ will implement Script. msg.must.implement.Scriptable =\ Argument to defineClass() must be the name of a class that implements \ the Scriptable interface. msg.runCommand.bad.args =\ The first argument to runCommand must be a command name. msg.runCommand.bad.env =\ A value of the env property of option object for runCommnad must be an \ object. msg.shell.seal.not.object =\ seal function can only be applied to objects msg.shell.seal.not.scriptable =\ seal function supports only sealing of ScriptableObject instances msg.shell.readFile.bad.args =\ readFile require at least file path to be specified msg.shell.readUrl.bad.args =\ readUrl require at least file path to be specified msg.shell.bad.function.scope =\ Wrong scope object for shell function: {0} msg.idswitch.same_string =\ The string {0} is used second time in the switch code. \ Previous occurrence was at line {1} msg.idswitch.file_end_in_switch =\ End of file inside tag {0} msg.idswitch.bad_tag_order =\ String switch tag {0} is not allowed here msg.idswitch.no_end_with_value =\ End for tag {0} can not contain value msg.idswitch.no_value_allowed =\ Tag {0} can not contain value msg.idswitch.no_end_usage =\ Tag {0} can not be used as end tag msg.idswitch.no_file_argument =\ File argument should be given msg.idswitch.too_many_arguments =\ Too many arguments are given msg.idswitch.bad_option =\ Invalid option {0} msg.idswitch.bad_option_char =\ Invalid option letter {0} msg.idswitch.bad_invocation =\ StringIdMap: {0}\n\ For more information, try\n\ java org.mozilla.javascript.tools.idswitch.StringIdMap --help msg.idswitch.io_error =\ StringIdMap: IO error, {0} msg.idswitch.usage = \ Usage: java org.mozilla.javascript.tools.idswitch.StringIdMap [OPTIONS] JAVA_SOURCE_FILE\n\ Generates efficient string dispatch code in JAVA_SOURCE_FILE.\n\ The resulting Java source fragment replaces the old dispatch code.\n\ If JAVA_SOURCE_FILE is -, standard input is used for Java source and the\n\ result is sent to standard output.\n\ \n\ \ -h, --help display this help and exit\n\ \ --version display version information and exit\n\ \n\ Note: the original file will be overwritten without any backup actions\n\ \ and all code inside #generated# tag will be replaced by new one. msg.idswitch.version = \ org.mozilla.javascript.tools.idswitch.StringIdMap version 0.2 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/SourceReader.java0000644000175000017500000001101611314263504035366 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tools; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.mozilla.javascript.Kit; import org.mozilla.javascript.tools.shell.ParsedContentType; /** * @author Attila Szegedi * @version $Id: SourceReader.java 3786 2008-11-19 18:23:18Z mguillem $ */ public class SourceReader { public static Object readFileOrUrl(String path, boolean convertToString, String defaultEncoding) throws IOException { URL url = null; // Assume path is URL if it contains dot and there are at least // 2 characters in the protocol part. The later allows under Windows // to interpret paths with driver letter as file, not URL. if (path.indexOf(':') >= 2) { try { url = new URL(path); } catch (MalformedURLException ex) { } } InputStream is = null; int capacityHint = 0; String encoding; final String contentType; byte[] data; try { if (url == null) { File file = new File(path); contentType = encoding = null; capacityHint = (int)file.length(); is = new FileInputStream(file); } else { URLConnection uc = url.openConnection(); is = uc.getInputStream(); if(convertToString) { ParsedContentType pct = new ParsedContentType(uc.getContentType()); contentType = pct.getContentType(); encoding = pct.getEncoding(); } else { contentType = encoding = null; } capacityHint = uc.getContentLength(); // Ignore insane values for Content-Length if (capacityHint > (1 << 20)) { capacityHint = -1; } } if (capacityHint <= 0) { capacityHint = 4096; } data = Kit.readStream(is, capacityHint); } finally { if(is != null) { is.close(); } } Object result; if (!convertToString) { result = data; } else { if(encoding == null) { // None explicitly specified in Content-type header. Use RFC-4329 // 4.2.2 section to autodetect if(data.length > 3 && data[0] == -1 && data[1] == -2 && data[2] == 0 && data[3] == 0) { encoding = "UTF-32LE"; } else if(data.length > 3 && data[0] == 0 && data[1] == 0 && data[2] == -2 && data[3] == -1) { encoding = "UTF-32BE"; } else if(data.length > 2 && data[0] == -17 && data[1] == -69 && data[2] == -65) { encoding = "UTF-8"; } else if(data.length > 1 && data[0] == -1 && data[1] == -2) { encoding = "UTF-16LE"; } else if(data.length > 1 && data[0] == -2 && data[1] == -1) { encoding = "UTF-16BE"; } else { // No autodetect. See if we have explicit value on command line encoding = defaultEncoding; if(encoding == null) { // No explicit encoding specification if(url == null) { // Local files default to system encoding encoding = System.getProperty("file.encoding"); } else if(contentType != null && contentType.startsWith("application/")) { // application/* types default to UTF-8 encoding = "UTF-8"; } else { // text/* MIME types default to US-ASCII encoding = "US-ASCII"; } } } } String strResult = new String(data, encoding); // Skip BOM if(strResult.length() > 0 && strResult.charAt(0) == '\uFEFF') { strResult = strResult.substring(1); } result = strResult; } return result; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/0000755000175000017500000000000011537630013033725 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000015300000000000011214 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/GuiCallback.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/GuiCallbac0000644000175000017500000000515411314263504035643 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov, igor@fastmail.fm * Cameron McCormack * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.debugger; /** * Interface for communication between the debugger and its GUI. This * should be implemented by the GUI. */ public interface GuiCallback { /** * Called when the source text of some script has been changed. */ void updateSourceText(Dim.SourceInfo sourceInfo); /** * Called when the interrupt loop has been entered. */ void enterInterrupt(Dim.StackFrame lastFrame, String threadTitle, String alertMessage); /** * Returns whether the current thread is the GUI's event thread. * This information is required to avoid blocking the event thread * from the debugger. */ boolean isGuiEventThread(); /** * Processes the next GUI event. This manual pumping of GUI events * is necessary when the GUI event thread itself has been stopped. */ void dispatchNextGuiEvent() throws InterruptedException; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/.cvsignore0000644000175000017500000000001211314263504035716 0ustar jamespagejamespage00000000000000downloadedjenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/build.xml0000644000175000017500000001202611314263504035547 0ustar jamespagejamespage00000000000000 import java.awt.Component; package org.mozilla.javascript.tools.debugger.downloaded; import java.awt.event.*; import java.awt.AWTEvent; import java.io.Serializable; import javax.swing.*; package org.mozilla.javascript.tools.debugger.downloaded; import javax.swing.*; class ListToTreeSelectionModelWrapper public class ListToTreeSelectionModelWrapper ListSelectionModel getListSelectionModel public ListSelectionModel getListSelectionModel import java.awt.Rectangle; import javax.swing.tree.TreeModel; package org.mozilla.javascript.tools.debugger.downloaded; import javax.swing.tree.TreeModel; import javax.swing.JTree; package org.mozilla.javascript.tools.debugger.downloaded; import javax.swing.JTree; The following targets are available with this build file: download Download ${swing-ex-url} and extract the necessary files from it. help Print this help. ././@LongLink0000000000000000000000000000015500000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/ScopeProvider.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/ScopeProvi0000644000175000017500000000372011314263504035743 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino JavaScript Debugger code, released * November 21, 2000. * * The Initial Developer of the Original Code is * See Beyond Corporation. * Portions created by the Initial Developer are Copyright (C) 2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Christopher Oliver * Cameron McCormack * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.debugger; import org.mozilla.javascript.Scriptable; /** * Interface to provide a scope object for script evaluation to the debugger. */ public interface ScopeProvider { /** * Returns the scope object to be used for script evaluation. */ Scriptable getScope(); }jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/test.js0000644000175000017500000000756111314263504035253 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov, igor@fastmail.fm * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // Test file for Rhino debugger var x = 12; function sleep(millis) { java.lang.Thread.sleep(millis); } function thread_loop_body(counter, thread_title) { print("["+counter+"] Thread '"+thread_title); sleep(1000); } function make_thread(thread_title, repeat_count, loop_body) { var Thread = java.lang.Thread; var thread = new Thread(function() { for (var i = 0; i < repeat_count; ++i) { loop_body(i, thread_title); } print("[DONE] Thread "+thread_title); }); return thread; } function make_thread2(thread_title, repeat_count, loop_body, loop_end) { var Thread = java.lang.Thread; var thread = new Thread(function() { create_gui(); for (var i = 0; i < repeat_count; ++i) { loop_body(i, thread_title); } loop_end(thread_title); }); return thread; } var loop_body_text = thread_loop_body.toSource(0); var loop_body; eval("loop_body = "+loop_body_text); var thread1 = make_thread("A", 5, loop_body); var thread2 = make_thread("B", 1000, loop_body); var thread3 = make_thread2("C", 2, loop_body, function loop_end(thread_title) { print("[DONE] Thread "+thread_title); // Do somethig to throw exception Math.xxxx(); }); thread1.start(); thread2.start(); thread3.start(); thread1.join(); thread2.join(); thread3.join(); function create_gui() { var swing = Packages.javax.swing; var awt = Packages.java.awt; var frame = new swing.JFrame("SwingApplication"); var labelPrefix = "Number of button clicks: "; var numClicks = 0; var label = new swing.JLabel(labelPrefix + numClicks); var button = new swing.JButton("Click Me!"); button.mnemonic = Packages.java.awt.event.KeyEvent.VK_I; button.addActionListener(function() { numClicks += 1; label.setText(labelPrefix + numClicks); }); label.setLabelFor(button); var pane = new swing.JPanel(); pane.setLayout(new awt.GridLayout(0, 1)); pane.add(button); pane.add(label); frame.getContentPane().add(pane, awt.BorderLayout.CENTER); frame.addWindowListener(function(event, methodName) { print(event + " "+methodName); if (methodName == "windowClosing") { //java.lang.System.exit(0); } }); //Finish setting up the frame, and show it. frame.pack(); frame.setVisible(true); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/treetable/0000755000175000017500000000000011537630013035674 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000016400000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/treetable/JTreeTable.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/treetable/0000644000175000017500000003515411314263504035706 0ustar jamespagejamespage00000000000000/* * @(#)JTreeTable.java 1.2 98/10/27 * * Copyright 1997, 1998 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.mozilla.javascript.tools.debugger.treetable; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; import javax.swing.table.*; import java.awt.Dimension; import java.awt.Component; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.util.EventObject; /** * This example shows how to create a simple JTreeTable component, * by using a JTree as a renderer (and editor) for the cells in a * particular column in the JTable. * * @version 1.2 10/27/98 * * @author Philip Milne * @author Scott Violet */ public class JTreeTable extends JTable { /** * */ private static final long serialVersionUID = -2103973006456695515L; /** A subclass of JTree. */ protected TreeTableCellRenderer tree; public JTreeTable(TreeTableModel treeTableModel) { super(); // Create the tree. It will be used as a renderer and editor. tree = new TreeTableCellRenderer(treeTableModel); // Install a tableModel representing the visible rows in the tree. super.setModel(new TreeTableModelAdapter(treeTableModel, tree)); // Force the JTable and JTree to share their row selection models. ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); tree.setSelectionModel(selectionWrapper); setSelectionModel(selectionWrapper.getListSelectionModel()); // Install the tree editor renderer and editor. setDefaultRenderer(TreeTableModel.class, tree); setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor()); // No grid. setShowGrid(false); // No intercell spacing setIntercellSpacing(new Dimension(0, 0)); // And update the height of the trees row to match that of // the table. if (tree.getRowHeight() < 1) { // Metal looks better like this. setRowHeight(18); } } /** * Overridden to message super and forward the method to the tree. * Since the tree is not actually in the component hierarchy it will * never receive this unless we forward it in this manner. */ @Override public void updateUI() { super.updateUI(); if(tree != null) { tree.updateUI(); } // Use the tree's default foreground and background colors in the // table. LookAndFeel.installColorsAndFont(this, "Tree.background", "Tree.foreground", "Tree.font"); } /* Workaround for BasicTableUI anomaly. Make sure the UI never tries to * paint the editor. The UI currently uses different techniques to * paint the renderers and editors and overriding setBounds() below * is not the right thing to do for an editor. Returning -1 for the * editing row in this case, ensures the editor is never painted. */ @Override public int getEditingRow() { return (getColumnClass(editingColumn) == TreeTableModel.class) ? -1 : editingRow; } /** * Overridden to pass the new rowHeight to the tree. */ @Override public void setRowHeight(int rowHeight) { super.setRowHeight(rowHeight); if (tree != null && tree.getRowHeight() != rowHeight) { tree.setRowHeight(getRowHeight()); } } /** * Returns the tree that is being shared between the model. */ public JTree getTree() { return tree; } /** * A TreeCellRenderer that displays a JTree. */ public class TreeTableCellRenderer extends JTree implements TableCellRenderer { private static final long serialVersionUID = -193867880014600717L; /** Last table/tree row asked to renderer. */ protected int visibleRow; public TreeTableCellRenderer(TreeModel model) { super(model); } /** * updateUI is overridden to set the colors of the Tree's renderer * to match that of the table. */ @Override public void updateUI() { super.updateUI(); // Make the tree's cell renderer use the table's cell selection // colors. TreeCellRenderer tcr = getCellRenderer(); if (tcr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr); // For 1.1 uncomment this, 1.2 has a bug that will cause an // exception to be thrown if the border selection color is // null. // dtcr.setBorderSelectionColor(null); dtcr.setTextSelectionColor(UIManager.getColor ("Table.selectionForeground")); dtcr.setBackgroundSelectionColor(UIManager.getColor ("Table.selectionBackground")); } } /** * Sets the row height of the tree, and forwards the row height to * the table. */ @Override public void setRowHeight(int rowHeight) { if (rowHeight > 0) { super.setRowHeight(rowHeight); if (JTreeTable.this != null && JTreeTable.this.getRowHeight() != rowHeight) { JTreeTable.this.setRowHeight(getRowHeight()); } } } /** * This is overridden to set the height to match that of the JTable. */ @Override public void setBounds(int x, int y, int w, int h) { super.setBounds(x, 0, w, JTreeTable.this.getHeight()); } /** * Sublcassed to translate the graphics such that the last visible * row will be drawn at 0,0. */ @Override public void paint(Graphics g) { g.translate(0, -visibleRow * getRowHeight()); super.paint(g); } /** * TreeCellRenderer method. Overridden to update the visible row. */ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if(isSelected) setBackground(table.getSelectionBackground()); else setBackground(table.getBackground()); visibleRow = row; return this; } } /** * TreeTableCellEditor implementation. Component returned is the * JTree. */ public class TreeTableCellEditor extends AbstractCellEditor implements TableCellEditor { public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int r, int c) { return tree; } /** * Overridden to return false, and if the event is a mouse event * it is forwarded to the tree.

* The behavior for this is debatable, and should really be offered * as a property. By returning false, all keyboard actions are * implemented in terms of the table. By returning true, the * tree would get a chance to do something with the keyboard * events. For the most part this is ok. But for certain keys, * such as left/right, the tree will expand/collapse where as * the table focus should really move to a different column. Page * up/down should also be implemented in terms of the table. * By returning false this also has the added benefit that clicking * outside of the bounds of the tree node, but still in the tree * column will select the row, whereas if this returned true * that wouldn't be the case. *

By returning false we are also enforcing the policy that * the tree will never be editable (at least by a key sequence). */ @Override public boolean isCellEditable(EventObject e) { if (e instanceof MouseEvent) { for (int counter = getColumnCount() - 1; counter >= 0; counter--) { if (getColumnClass(counter) == TreeTableModel.class) { MouseEvent me = (MouseEvent)e; MouseEvent newME = new MouseEvent(tree, me.getID(), me.getWhen(), me.getModifiers(), me.getX() - getCellRect(0, counter, true).x, me.getY(), me.getClickCount(), me.isPopupTrigger()); tree.dispatchEvent(newME); break; } } } return false; } } /** * ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel * to listen for changes in the ListSelectionModel it maintains. Once * a change in the ListSelectionModel happens, the paths are updated * in the DefaultTreeSelectionModel. */ public class ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel { private static final long serialVersionUID = 8168140829623071131L; /** Set to true when we are updating the ListSelectionModel. */ protected boolean updatingListSelectionModel; public ListToTreeSelectionModelWrapper() { super(); getListSelectionModel().addListSelectionListener (createListSelectionListener()); } /** * Returns the list selection model. ListToTreeSelectionModelWrapper * listens for changes to this model and updates the selected paths * accordingly. */ public ListSelectionModel getListSelectionModel() { return listSelectionModel; } /** * This is overridden to set updatingListSelectionModel * and message super. This is the only place DefaultTreeSelectionModel * alters the ListSelectionModel. */ @Override public void resetRowSelection() { if(!updatingListSelectionModel) { updatingListSelectionModel = true; try { super.resetRowSelection(); } finally { updatingListSelectionModel = false; } } // Notice how we don't message super if // updatingListSelectionModel is true. If // updatingListSelectionModel is true, it implies the // ListSelectionModel has already been updated and the // paths are the only thing that needs to be updated. } /** * Creates and returns an instance of ListSelectionHandler. */ protected ListSelectionListener createListSelectionListener() { return new ListSelectionHandler(); } /** * If updatingListSelectionModel is false, this will * reset the selected paths from the selected rows in the list * selection model. */ protected void updateSelectedPathsFromSelectedRows() { if(!updatingListSelectionModel) { updatingListSelectionModel = true; try { // This is way expensive, ListSelectionModel needs an // enumerator for iterating. int min = listSelectionModel.getMinSelectionIndex(); int max = listSelectionModel.getMaxSelectionIndex(); clearSelection(); if(min != -1 && max != -1) { for(int counter = min; counter <= max; counter++) { if(listSelectionModel.isSelectedIndex(counter)) { TreePath selPath = tree.getPathForRow (counter); if(selPath != null) { addSelectionPath(selPath); } } } } } finally { updatingListSelectionModel = false; } } } /** * Class responsible for calling updateSelectedPathsFromSelectedRows * when the selection of the list changse. */ class ListSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { updateSelectedPathsFromSelectedRows(); } } } } ././@LongLink0000000000000000000000000000017000000000000011213 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/treetable/TreeTableModel.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/treetable/0000644000175000017500000000613411314263504035702 0ustar jamespagejamespage00000000000000/* * TreeTableModel.java * * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.mozilla.javascript.tools.debugger.treetable; import javax.swing.tree.TreeModel; /** * TreeTableModel is the model used by a JTreeTable. It extends TreeModel * to add methods for getting inforamtion about the set of columns each * node in the TreeTableModel may have. Each column, like a column in * a TableModel, has a name and a type associated with it. Each node in * the TreeTableModel can return a value for each of the columns and * set that value if isCellEditable() returns true. * * @author Philip Milne * @author Scott Violet */ public interface TreeTableModel extends TreeModel { /** * Returns the number ofs availible column. */ public int getColumnCount(); /** * Returns the name for column number column. */ public String getColumnName(int column); /** * Returns the type for column number column. */ public Class getColumnClass(int column); /** * Returns the value to be displayed for node node, * at column number column. */ public Object getValueAt(Object node, int column); /** * Indicates whether the the value for node node, * at column number column is editable. */ public boolean isCellEditable(Object node, int column); /** * Sets the value for node node, * at column number column. */ public void setValueAt(Object aValue, Object node, int column); } ././@LongLink0000000000000000000000000000017400000000000011217 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/treetable/AbstractCellEditor.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/treetable/0000644000175000017500000000721411314263504035702 0ustar jamespagejamespage00000000000000/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.mozilla.javascript.tools.debugger.treetable; import javax.swing.*; import javax.swing.event.*; import java.util.EventObject; public class AbstractCellEditor implements CellEditor { protected EventListenerList listenerList = new EventListenerList(); public Object getCellEditorValue() { return null; } public boolean isCellEditable(EventObject e) { return true; } public boolean shouldSelectCell(EventObject anEvent) { return false; } public boolean stopCellEditing() { return true; } public void cancelCellEditing() {} public void addCellEditorListener(CellEditorListener l) { listenerList.add(CellEditorListener.class, l); } public void removeCellEditorListener(CellEditorListener l) { listenerList.remove(CellEditorListener.class, l); } /* * Notify all listeners that have registered interest for * notification on this event type. * @see EventListenerList */ protected void fireEditingStopped() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==CellEditorListener.class) { ((CellEditorListener)listeners[i+1]).editingStopped(new ChangeEvent(this)); } } } /* * Notify all listeners that have registered interest for * notification on this event type. * @see EventListenerList */ protected void fireEditingCanceled() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==CellEditorListener.class) { ((CellEditorListener)listeners[i+1]).editingCanceled(new ChangeEvent(this)); } } } } ././@LongLink0000000000000000000000000000017700000000000011222 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/treetable/TreeTableModelAdapter.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/treetable/0000644000175000017500000001237011314263504035701 0ustar jamespagejamespage00000000000000/* * @(#)TreeTableModelAdapter.java 1.2 98/10/27 * * Copyright 1997, 1998 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.mozilla.javascript.tools.debugger.treetable; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; import javax.swing.tree.TreePath; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; /** * This is a wrapper class takes a TreeTableModel and implements * the table model interface. The implementation is trivial, with * all of the event dispatching support provided by the superclass: * the AbstractTableModel. * * @version 1.2 10/27/98 * * @author Philip Milne * @author Scott Violet */ public class TreeTableModelAdapter extends AbstractTableModel { private static final long serialVersionUID = 48741114609209052L; JTree tree; TreeTableModel treeTableModel; public TreeTableModelAdapter(TreeTableModel treeTableModel, JTree tree) { this.tree = tree; this.treeTableModel = treeTableModel; tree.addTreeExpansionListener(new TreeExpansionListener() { // Don't use fireTableRowsInserted() here; the selection model // would get updated twice. public void treeExpanded(TreeExpansionEvent event) { fireTableDataChanged(); } public void treeCollapsed(TreeExpansionEvent event) { fireTableDataChanged(); } }); // Install a TreeModelListener that can update the table when // tree changes. We use delayedFireTableDataChanged as we can // not be guaranteed the tree will have finished processing // the event before us. treeTableModel.addTreeModelListener(new TreeModelListener() { public void treeNodesChanged(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeNodesInserted(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeNodesRemoved(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeStructureChanged(TreeModelEvent e) { delayedFireTableDataChanged(); } }); } // Wrappers, implementing TableModel interface. public int getColumnCount() { return treeTableModel.getColumnCount(); } @Override public String getColumnName(int column) { return treeTableModel.getColumnName(column); } @Override public Class getColumnClass(int column) { return treeTableModel.getColumnClass(column); } public int getRowCount() { return tree.getRowCount(); } protected Object nodeForRow(int row) { TreePath treePath = tree.getPathForRow(row); return treePath.getLastPathComponent(); } public Object getValueAt(int row, int column) { return treeTableModel.getValueAt(nodeForRow(row), column); } @Override public boolean isCellEditable(int row, int column) { return treeTableModel.isCellEditable(nodeForRow(row), column); } @Override public void setValueAt(Object value, int row, int column) { treeTableModel.setValueAt(value, nodeForRow(row), column); } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ protected void delayedFireTableDataChanged() { SwingUtilities.invokeLater(new Runnable() { public void run() { fireTableDataChanged(); } }); } } ././@LongLink0000000000000000000000000000014600000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded/jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded0000755000175000017500000000000011537630013035766 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000016500000000000011217 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded/JTreeTable.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded0000644000175000017500000002536411314263504036002 0ustar jamespagejamespage00000000000000/* * @(#)JTreeTable.java 1.2 98/10/27 * * Copyright 1997, 1998 by Sun Microsystems, Inc., * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. * All rights reserved. * * This software is the confidential and proprietary information * of Sun Microsystems, Inc. ("Confidential Information"). You * shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement * you entered into with Sun. */ package org.mozilla.javascript.tools.debugger.downloaded; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; import javax.swing.table.*; import java.awt.Dimension; import java.awt.Component; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.util.EventObject; /** * This example shows how to create a simple JTreeTable component, * by using a JTree as a renderer (and editor) for the cells in a * particular column in the JTable. * * @version 1.2 10/27/98 * * @author Philip Milne * @author Scott Violet */ public class JTreeTable extends JTable { /** A subclass of JTree. */ protected TreeTableCellRenderer tree; public JTreeTable(TreeTableModel treeTableModel) { super(); // Create the tree. It will be used as a renderer and editor. tree = new TreeTableCellRenderer(treeTableModel); // Install a tableModel representing the visible rows in the tree. super.setModel(new TreeTableModelAdapter(treeTableModel, tree)); // Force the JTable and JTree to share their row selection models. ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); tree.setSelectionModel(selectionWrapper); setSelectionModel(selectionWrapper.getListSelectionModel()); // Install the tree editor renderer and editor. setDefaultRenderer(TreeTableModel.class, tree); setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor()); // No grid. setShowGrid(false); // No intercell spacing setIntercellSpacing(new Dimension(0, 0)); // And update the height of the trees row to match that of // the table. if (tree.getRowHeight() < 1) { // Metal looks better like this. setRowHeight(18); } } /** * Overridden to message super and forward the method to the tree. * Since the tree is not actually in the component hieachy it will * never receive this unless we forward it in this manner. */ public void updateUI() { super.updateUI(); if(tree != null) { tree.updateUI(); } // Use the tree's default foreground and background colors in the // table. LookAndFeel.installColorsAndFont(this, "Tree.background", "Tree.foreground", "Tree.font"); } /* Workaround for BasicTableUI anomaly. Make sure the UI never tries to * paint the editor. The UI currently uses different techniques to * paint the renderers and editors and overriding setBounds() below * is not the right thing to do for an editor. Returning -1 for the * editing row in this case, ensures the editor is never painted. */ public int getEditingRow() { return (getColumnClass(editingColumn) == TreeTableModel.class) ? -1 : editingRow; } /** * Overridden to pass the new rowHeight to the tree. */ public void setRowHeight(int rowHeight) { super.setRowHeight(rowHeight); if (tree != null && tree.getRowHeight() != rowHeight) { tree.setRowHeight(getRowHeight()); } } /** * Returns the tree that is being shared between the model. */ public JTree getTree() { return tree; } /** * A TreeCellRenderer that displays a JTree. */ public class TreeTableCellRenderer extends JTree implements TableCellRenderer { /** Last table/tree row asked to renderer. */ protected int visibleRow; public TreeTableCellRenderer(TreeModel model) { super(model); } /** * updateUI is overridden to set the colors of the Tree's renderer * to match that of the table. */ public void updateUI() { super.updateUI(); // Make the tree's cell renderer use the table's cell selection // colors. TreeCellRenderer tcr = getCellRenderer(); if (tcr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr); // For 1.1 uncomment this, 1.2 has a bug that will cause an // exception to be thrown if the border selection color is // null. // dtcr.setBorderSelectionColor(null); dtcr.setTextSelectionColor(UIManager.getColor ("Table.selectionForeground")); dtcr.setBackgroundSelectionColor(UIManager.getColor ("Table.selectionBackground")); } } /** * Sets the row height of the tree, and forwards the row height to * the table. */ public void setRowHeight(int rowHeight) { if (rowHeight > 0) { super.setRowHeight(rowHeight); if (JTreeTable.this != null && JTreeTable.this.getRowHeight() != rowHeight) { JTreeTable.this.setRowHeight(getRowHeight()); } } } /** * This is overridden to set the height to match that of the JTable. */ public void setBounds(int x, int y, int w, int h) { super.setBounds(x, 0, w, JTreeTable.this.getHeight()); } /** * Sublcassed to translate the graphics such that the last visible * row will be drawn at 0,0. */ public void paint(Graphics g) { g.translate(0, -visibleRow * getRowHeight()); super.paint(g); } /** * TreeCellRenderer method. Overridden to update the visible row. */ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if(isSelected) setBackground(table.getSelectionBackground()); else setBackground(table.getBackground()); visibleRow = row; return this; } } /** * TreeTableCellEditor implementation. Component returned is the * JTree. */ public class TreeTableCellEditor extends AbstractCellEditor implements TableCellEditor { public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int r, int c) { return tree; } /** * Overridden to return false, and if the event is a mouse event * it is forwarded to the tree.

* The behavior for this is debatable, and should really be offered * as a property. By returning false, all keyboard actions are * implemented in terms of the table. By returning true, the * tree would get a chance to do something with the keyboard * events. For the most part this is ok. But for certain keys, * such as left/right, the tree will expand/collapse where as * the table focus should really move to a different column. Page * up/down should also be implemented in terms of the table. * By returning false this also has the added benefit that clicking * outside of the bounds of the tree node, but still in the tree * column will select the row, whereas if this returned true * that wouldn't be the case. *

By returning false we are also enforcing the policy that * the tree will never be editable (at least by a key sequence). */ public boolean isCellEditable(EventObject e) { if (e instanceof MouseEvent) { for (int counter = getColumnCount() - 1; counter >= 0; counter--) { if (getColumnClass(counter) == TreeTableModel.class) { MouseEvent me = (MouseEvent)e; MouseEvent newME = new MouseEvent(tree, me.getID(), me.getWhen(), me.getModifiers(), me.getX() - getCellRect(0, counter, true).x, me.getY(), me.getClickCount(), me.isPopupTrigger()); tree.dispatchEvent(newME); break; } } } return false; } } /** * ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel * to listen for changes in the ListSelectionModel it maintains. Once * a change in the ListSelectionModel happens, the paths are updated * in the DefaultTreeSelectionModel. */ public class ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel { /** Set to true when we are updating the ListSelectionModel. */ protected boolean updatingListSelectionModel; public ListToTreeSelectionModelWrapper() { super(); getListSelectionModel().addListSelectionListener (createListSelectionListener()); } /** * Returns the list selection model. ListToTreeSelectionModelWrapper * listens for changes to this model and updates the selected paths * accordingly. */ public ListSelectionModel getListSelectionModel() { return listSelectionModel; } /** * This is overridden to set updatingListSelectionModel * and message super. This is the only place DefaultTreeSelectionModel * alters the ListSelectionModel. */ public void resetRowSelection() { if(!updatingListSelectionModel) { updatingListSelectionModel = true; try { super.resetRowSelection(); } finally { updatingListSelectionModel = false; } } // Notice how we don't message super if // updatingListSelectionModel is true. If // updatingListSelectionModel is true, it implies the // ListSelectionModel has already been updated and the // paths are the only thing that needs to be updated. } /** * Creates and returns an instance of ListSelectionHandler. */ protected ListSelectionListener createListSelectionListener() { return new ListSelectionHandler(); } /** * If updatingListSelectionModel is false, this will * reset the selected paths from the selected rows in the list * selection model. */ protected void updateSelectedPathsFromSelectedRows() { if(!updatingListSelectionModel) { updatingListSelectionModel = true; try { // This is way expensive, ListSelectionModel needs an // enumerator for iterating. int min = listSelectionModel.getMinSelectionIndex(); int max = listSelectionModel.getMaxSelectionIndex(); clearSelection(); if(min != -1 && max != -1) { for(int counter = min; counter <= max; counter++) { if(listSelectionModel.isSelectedIndex(counter)) { TreePath selPath = tree.getPathForRow (counter); if(selPath != null) { addSelectionPath(selPath); } } } } } finally { updatingListSelectionModel = false; } } } /** * Class responsible for calling updateSelectedPathsFromSelectedRows * when the selection of the list changse. */ class ListSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { updateSelectedPathsFromSelectedRows(); } } } } ././@LongLink0000000000000000000000000000016000000000000011212 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded/.cvsignorejenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded0000644000175000017500000000012711314263504035770 0ustar jamespagejamespage00000000000000AbstractCellEditor.java JTreeTable.java TreeTableModelAdapter.java TreeTableModel.java ././@LongLink0000000000000000000000000000017100000000000011214 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded/TreeTableModel.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded0000644000175000017500000000447211314263504035777 0ustar jamespagejamespage00000000000000/* * TreeTableModel.java * * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. * * This software is the confidential and proprietary information of Sun * Microsystems, Inc. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Sun. * * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING * THIS SOFTWARE OR ITS DERIVATIVES. * */ package org.mozilla.javascript.tools.debugger.downloaded; import javax.swing.tree.TreeModel; /** * TreeTableModel is the model used by a JTreeTable. It extends TreeModel * to add methods for getting inforamtion about the set of columns each * node in the TreeTableModel may have. Each column, like a column in * a TableModel, has a name and a type associated with it. Each node in * the TreeTableModel can return a value for each of the columns and * set that value if isCellEditable() returns true. * * @author Philip Milne * @author Scott Violet */ public interface TreeTableModel extends TreeModel { /** * Returns the number ofs availible column. */ public int getColumnCount(); /** * Returns the name for column number column. */ public String getColumnName(int column); /** * Returns the type for column number column. */ public Class getColumnClass(int column); /** * Returns the value to be displayed for node node, * at column number column. */ public Object getValueAt(Object node, int column); /** * Indicates whether the the value for node node, * at column number column is editable. */ public boolean isCellEditable(Object node, int column); /** * Sets the value for node node, * at column number column. */ public void setValueAt(Object aValue, Object node, int column); } ././@LongLink0000000000000000000000000000017500000000000011220 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded/AbstractCellEditor.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded0000644000175000017500000000407111314263504035772 0ustar jamespagejamespage00000000000000 package org.mozilla.javascript.tools.debugger.downloaded; import java.awt.Component; import java.awt.event.*; import java.awt.AWTEvent; import javax.swing.*; import javax.swing.event.*; import java.util.EventObject; import java.io.Serializable; public class AbstractCellEditor implements CellEditor { protected EventListenerList listenerList = new EventListenerList(); public Object getCellEditorValue() { return null; } public boolean isCellEditable(EventObject e) { return true; } public boolean shouldSelectCell(EventObject anEvent) { return false; } public boolean stopCellEditing() { return true; } public void cancelCellEditing() {} public void addCellEditorListener(CellEditorListener l) { listenerList.add(CellEditorListener.class, l); } public void removeCellEditorListener(CellEditorListener l) { listenerList.remove(CellEditorListener.class, l); } /* * Notify all listeners that have registered interest for * notification on this event type. * @see EventListenerList */ protected void fireEditingStopped() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==CellEditorListener.class) { ((CellEditorListener)listeners[i+1]).editingStopped(new ChangeEvent(this)); } } } /* * Notify all listeners that have registered interest for * notification on this event type. * @see EventListenerList */ protected void fireEditingCanceled() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==CellEditorListener.class) { ((CellEditorListener)listeners[i+1]).editingCanceled(new ChangeEvent(this)); } } } } ././@LongLink0000000000000000000000000000020000000000000011205 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded/TreeTableModelAdapter.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/downloaded0000644000175000017500000000731011314263504035771 0ustar jamespagejamespage00000000000000/* * @(#)TreeTableModelAdapter.java 1.2 98/10/27 * * Copyright 1997, 1998 by Sun Microsystems, Inc., * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. * All rights reserved. * * This software is the confidential and proprietary information * of Sun Microsystems, Inc. ("Confidential Information"). You * shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement * you entered into with Sun. */ package org.mozilla.javascript.tools.debugger.downloaded; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; import javax.swing.tree.TreePath; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; /** * This is a wrapper class takes a TreeTableModel and implements * the table model interface. The implementation is trivial, with * all of the event dispatching support provided by the superclass: * the AbstractTableModel. * * @version 1.2 10/27/98 * * @author Philip Milne * @author Scott Violet */ public class TreeTableModelAdapter extends AbstractTableModel { JTree tree; TreeTableModel treeTableModel; public TreeTableModelAdapter(TreeTableModel treeTableModel, JTree tree) { this.tree = tree; this.treeTableModel = treeTableModel; tree.addTreeExpansionListener(new TreeExpansionListener() { // Don't use fireTableRowsInserted() here; the selection model // would get updated twice. public void treeExpanded(TreeExpansionEvent event) { fireTableDataChanged(); } public void treeCollapsed(TreeExpansionEvent event) { fireTableDataChanged(); } }); // Install a TreeModelListener that can update the table when // tree changes. We use delayedFireTableDataChanged as we can // not be guaranteed the tree will have finished processing // the event before us. treeTableModel.addTreeModelListener(new TreeModelListener() { public void treeNodesChanged(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeNodesInserted(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeNodesRemoved(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeStructureChanged(TreeModelEvent e) { delayedFireTableDataChanged(); } }); } // Wrappers, implementing TableModel interface. public int getColumnCount() { return treeTableModel.getColumnCount(); } public String getColumnName(int column) { return treeTableModel.getColumnName(column); } public Class getColumnClass(int column) { return treeTableModel.getColumnClass(column); } public int getRowCount() { return tree.getRowCount(); } protected Object nodeForRow(int row) { TreePath treePath = tree.getPathForRow(row); return treePath.getLastPathComponent(); } public Object getValueAt(int row, int column) { return treeTableModel.getValueAt(nodeForRow(row), column); } public boolean isCellEditable(int row, int column) { return treeTableModel.isCellEditable(nodeForRow(row), column); } public void setValueAt(Object value, int row, int column) { treeTableModel.setValueAt(value, nodeForRow(row), column); } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ protected void delayedFireTableDataChanged() { SwingUtilities.invokeLater(new Runnable() { public void run() { fireTableDataChanged(); } }); } } ././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/SwingGui.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/SwingGui.j0000644000175000017500000032600211314263504035637 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino JavaScript Debugger code, released * November 21, 2000. * * The Initial Developer of the Original Code is * SeeBeyond Corporation. * Portions created by the Initial Developer are Copyright (C) 2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Matt Gould * Cameron McCormack * Christopher Oliver * Hannes Wallnoefer * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.debugger; import javax.swing.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.table.*; import java.awt.EventQueue; import java.awt.ActiveEvent; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Event; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Frame; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.MenuComponent; import java.awt.Point; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.*; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EventListener; import java.util.EventObject; import java.util.Map; import java.util.HashMap; import java.util.Properties; import java.io.*; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import java.lang.reflect.Method; import org.mozilla.javascript.Kit; import org.mozilla.javascript.SecurityUtilities; import org.mozilla.javascript.tools.shell.ConsoleTextArea; import org.mozilla.javascript.tools.debugger.treetable.JTreeTable; import org.mozilla.javascript.tools.debugger.treetable.TreeTableModel; import org.mozilla.javascript.tools.debugger.treetable.TreeTableModelAdapter; /** * GUI for the Rhino debugger. */ public class SwingGui extends JFrame implements GuiCallback { /** * Serializable magic number. */ private static final long serialVersionUID = -8217029773456711621L; /** * The debugger. */ Dim dim; /** * The action to run when the 'Exit' menu item is chosen or the * frame is closed. */ private Runnable exitAction; /** * The {@link JDesktopPane} that holds the script windows. */ private JDesktopPane desk; /** * The {@link JPanel} that shows information about the context. */ private ContextWindow context; /** * The menu bar. */ private Menubar menubar; /** * The tool bar. */ private JToolBar toolBar; /** * The console that displays I/O from the script. */ private JSInternalConsole console; /** * The {@link JSplitPane} that separates {@link #desk} from * {@link org.mozilla.javascript.Context}. */ private JSplitPane split1; /** * The status bar. */ private JLabel statusBar; /** * Hash table of internal frame names to the internal frames themselves. */ private final Map toplevels = Collections.synchronizedMap(new HashMap()); /** * Hash table of script URLs to their internal frames. */ private final Map fileWindows = Collections.synchronizedMap(new HashMap()); /** * The {@link FileWindow} that last had the focus. */ private FileWindow currentWindow; /** * File choose dialog for loading a script. */ JFileChooser dlg; /** * The AWT EventQueue. Used for manually pumping AWT events from * {@link #dispatchNextGuiEvent()}. */ private EventQueue awtEventQueue; /** * Creates a new SwingGui. */ public SwingGui(Dim dim, String title) { super(title); this.dim = dim; init(); dim.setGuiCallback(this); } /** * Returns the Menubar of this debugger frame. */ public Menubar getMenubar() { return menubar; } /** * Sets the {@link Runnable} that will be run when the "Exit" menu * item is chosen. */ public void setExitAction(Runnable r) { exitAction = r; } /** * Returns the debugger console component. */ public JSInternalConsole getConsole() { return console; } /** * Sets the visibility of the debugger GUI. */ @Override public void setVisible(boolean b) { super.setVisible(b); if (b) { // this needs to be done after the window is visible console.consoleTextArea.requestFocus(); context.split.setDividerLocation(0.5); try { console.setMaximum(true); console.setSelected(true); console.show(); console.consoleTextArea.requestFocus(); } catch (Exception exc) { } } } /** * Records a new internal frame. */ void addTopLevel(String key, JFrame frame) { if (frame != this) { toplevels.put(key, frame); } } /** * Constructs the debugger GUI. */ private void init() { menubar = new Menubar(this); setJMenuBar(menubar); toolBar = new JToolBar(); JButton button; JButton breakButton, goButton, stepIntoButton, stepOverButton, stepOutButton; String [] toolTips = {"Break (Pause)", "Go (F5)", "Step Into (F11)", "Step Over (F7)", "Step Out (F8)"}; int count = 0; button = breakButton = new JButton("Break"); button.setToolTipText("Break"); button.setActionCommand("Break"); button.addActionListener(menubar); button.setEnabled(true); button.setToolTipText(toolTips[count++]); button = goButton = new JButton("Go"); button.setToolTipText("Go"); button.setActionCommand("Go"); button.addActionListener(menubar); button.setEnabled(false); button.setToolTipText(toolTips[count++]); button = stepIntoButton = new JButton("Step Into"); button.setToolTipText("Step Into"); button.setActionCommand("Step Into"); button.addActionListener(menubar); button.setEnabled(false); button.setToolTipText(toolTips[count++]); button = stepOverButton = new JButton("Step Over"); button.setToolTipText("Step Over"); button.setActionCommand("Step Over"); button.setEnabled(false); button.addActionListener(menubar); button.setToolTipText(toolTips[count++]); button = stepOutButton = new JButton("Step Out"); button.setToolTipText("Step Out"); button.setActionCommand("Step Out"); button.setEnabled(false); button.addActionListener(menubar); button.setToolTipText(toolTips[count++]); Dimension dim = stepOverButton.getPreferredSize(); breakButton.setPreferredSize(dim); breakButton.setMinimumSize(dim); breakButton.setMaximumSize(dim); breakButton.setSize(dim); goButton.setPreferredSize(dim); goButton.setMinimumSize(dim); goButton.setMaximumSize(dim); stepIntoButton.setPreferredSize(dim); stepIntoButton.setMinimumSize(dim); stepIntoButton.setMaximumSize(dim); stepOverButton.setPreferredSize(dim); stepOverButton.setMinimumSize(dim); stepOverButton.setMaximumSize(dim); stepOutButton.setPreferredSize(dim); stepOutButton.setMinimumSize(dim); stepOutButton.setMaximumSize(dim); toolBar.add(breakButton); toolBar.add(goButton); toolBar.add(stepIntoButton); toolBar.add(stepOverButton); toolBar.add(stepOutButton); JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); getContentPane().add(toolBar, BorderLayout.NORTH); getContentPane().add(contentPane, BorderLayout.CENTER); desk = new JDesktopPane(); desk.setPreferredSize(new Dimension(600, 300)); desk.setMinimumSize(new Dimension(150, 50)); desk.add(console = new JSInternalConsole("JavaScript Console")); context = new ContextWindow(this); context.setPreferredSize(new Dimension(600, 120)); context.setMinimumSize(new Dimension(50, 50)); split1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, desk, context); split1.setOneTouchExpandable(true); SwingGui.setResizeWeight(split1, 0.66); contentPane.add(split1, BorderLayout.CENTER); statusBar = new JLabel(); statusBar.setText("Thread: "); contentPane.add(statusBar, BorderLayout.SOUTH); dlg = new JFileChooser(); javax.swing.filechooser.FileFilter filter = new javax.swing.filechooser.FileFilter() { @Override public boolean accept(File f) { if (f.isDirectory()) { return true; } String n = f.getName(); int i = n.lastIndexOf('.'); if (i > 0 && i < n.length() -1) { String ext = n.substring(i + 1).toLowerCase(); if (ext.equals("js")) { return true; } } return false; } @Override public String getDescription() { return "JavaScript Files (*.js)"; } }; dlg.addChoosableFileFilter(filter); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { exit(); } }); } /** * Runs the {@link #exitAction}. */ private void exit() { if (exitAction != null) { SwingUtilities.invokeLater(exitAction); } dim.setReturnValue(Dim.EXIT); } /** * Returns the {@link FileWindow} for the given URL. */ FileWindow getFileWindow(String url) { if (url == null || url.equals("")) { return null; } return fileWindows.get(url); } /** * Returns a short version of the given URL. */ static String getShortName(String url) { int lastSlash = url.lastIndexOf('/'); if (lastSlash < 0) { lastSlash = url.lastIndexOf('\\'); } String shortName = url; if (lastSlash >= 0 && lastSlash + 1 < url.length()) { shortName = url.substring(lastSlash + 1); } return shortName; } /** * Closes the given {@link FileWindow}. */ void removeWindow(FileWindow w) { fileWindows.remove(w.getUrl()); JMenu windowMenu = getWindowMenu(); int count = windowMenu.getItemCount(); JMenuItem lastItem = windowMenu.getItem(count -1); String name = getShortName(w.getUrl()); for (int i = 5; i < count; i++) { JMenuItem item = windowMenu.getItem(i); if (item == null) continue; // separator String text = item.getText(); //1 D:\foo.js //2 D:\bar.js int pos = text.indexOf(' '); if (text.substring(pos + 1).equals(name)) { windowMenu.remove(item); // Cascade [0] // Tile [1] // ------- [2] // Console [3] // ------- [4] if (count == 6) { // remove the final separator windowMenu.remove(4); } else { int j = i - 4; for (;i < count -1; i++) { JMenuItem thisItem = windowMenu.getItem(i); if (thisItem != null) { //1 D:\foo.js //2 D:\bar.js text = thisItem.getText(); if (text.equals("More Windows...")) { break; } else { pos = text.indexOf(' '); thisItem.setText((char)('0' + j) + " " + text.substring(pos + 1)); thisItem.setMnemonic('0' + j); j++; } } } if (count - 6 == 0 && lastItem != item) { if (lastItem.getText().equals("More Windows...")) { windowMenu.remove(lastItem); } } } break; } } windowMenu.revalidate(); } /** * Shows the line at which execution in the given stack frame just stopped. */ void showStopLine(Dim.StackFrame frame) { String sourceName = frame.getUrl(); if (sourceName == null || sourceName.equals("")) { if (console.isVisible()) { console.show(); } } else { showFileWindow(sourceName, -1); int lineNumber = frame.getLineNumber(); FileWindow w = getFileWindow(sourceName); if (w != null) { setFilePosition(w, lineNumber); } } } /** * Shows a {@link FileWindow} for the given source, creating it * if it doesn't exist yet. if lineNumber is greater * than -1, it indicates the line number to select and display. * @param sourceUrl the source URL * @param lineNumber the line number to select, or -1 */ protected void showFileWindow(String sourceUrl, int lineNumber) { FileWindow w = getFileWindow(sourceUrl); if (w == null) { Dim.SourceInfo si = dim.sourceInfo(sourceUrl); createFileWindow(si, -1); w = getFileWindow(sourceUrl); } if (lineNumber > -1) { int start = w.getPosition(lineNumber-1); int end = w.getPosition(lineNumber)-1; w.textArea.select(start); w.textArea.setCaretPosition(start); w.textArea.moveCaretPosition(end); } try { if (w.isIcon()) { w.setIcon(false); } w.setVisible(true); w.moveToFront(); w.setSelected(true); requestFocus(); w.requestFocus(); w.textArea.requestFocus(); } catch (Exception exc) { } } /** * Creates and shows a new {@link FileWindow} for the given source. */ protected void createFileWindow(Dim.SourceInfo sourceInfo, int line) { boolean activate = true; String url = sourceInfo.url(); FileWindow w = new FileWindow(this, sourceInfo); fileWindows.put(url, w); if (line != -1) { if (currentWindow != null) { currentWindow.setPosition(-1); } try { w.setPosition(w.textArea.getLineStartOffset(line-1)); } catch (BadLocationException exc) { try { w.setPosition(w.textArea.getLineStartOffset(0)); } catch (BadLocationException ee) { w.setPosition(-1); } } } desk.add(w); if (line != -1) { currentWindow = w; } menubar.addFile(url); w.setVisible(true); if (activate) { try { w.setMaximum(true); w.setSelected(true); w.moveToFront(); } catch (Exception exc) { } } } /** * Update the source text for sourceInfo. This returns true * if a {@link FileWindow} for the given source exists and could be updated. * Otherwise, this does nothing and returns false. * @param sourceInfo the source info * @return true if a {@link FileWindow} for the given source exists * and could be updated, false otherwise. */ protected boolean updateFileWindow(Dim.SourceInfo sourceInfo) { String fileName = sourceInfo.url(); FileWindow w = getFileWindow(fileName); if (w != null) { w.updateText(sourceInfo); w.show(); return true; } return false; } /** * Moves the current position in the given {@link FileWindow} to the * given line. */ private void setFilePosition(FileWindow w, int line) { boolean activate = true; JTextArea ta = w.textArea; try { if (line == -1) { w.setPosition(-1); if (currentWindow == w) { currentWindow = null; } } else { int loc = ta.getLineStartOffset(line-1); if (currentWindow != null && currentWindow != w) { currentWindow.setPosition(-1); } w.setPosition(loc); currentWindow = w; } } catch (BadLocationException exc) { // fix me } if (activate) { if (w.isIcon()) { desk.getDesktopManager().deiconifyFrame(w); } desk.getDesktopManager().activateFrame(w); try { w.show(); w.toFront(); // required for correct frame layering (JDK 1.4.1) w.setSelected(true); } catch (Exception exc) { } } } /** * Handles script interruption. */ void enterInterruptImpl(Dim.StackFrame lastFrame, String threadTitle, String alertMessage) { statusBar.setText("Thread: " + threadTitle); showStopLine(lastFrame); if (alertMessage != null) { MessageDialogWrapper.showMessageDialog(this, alertMessage, "Exception in Script", JOptionPane.ERROR_MESSAGE); } updateEnabled(true); Dim.ContextData contextData = lastFrame.contextData(); JComboBox ctx = context.context; List toolTips = context.toolTips; context.disableUpdate(); int frameCount = contextData.frameCount(); ctx.removeAllItems(); // workaround for JDK 1.4 bug that caches selected value even after // removeAllItems() is called ctx.setSelectedItem(null); toolTips.clear(); for (int i = 0; i < frameCount; i++) { Dim.StackFrame frame = contextData.getFrame(i); String url = frame.getUrl(); int lineNumber = frame.getLineNumber(); String shortName = url; if (url.length() > 20) { shortName = "..." + url.substring(url.length() - 17); } String location = "\"" + shortName + "\", line " + lineNumber; ctx.insertItemAt(location, i); location = "\"" + url + "\", line " + lineNumber; toolTips.add(location); } context.enableUpdate(); ctx.setSelectedIndex(0); ctx.setMinimumSize(new Dimension(50, ctx.getMinimumSize().height)); } /** * Returns the 'Window' menu. */ private JMenu getWindowMenu() { return menubar.getMenu(3); } /** * Displays a {@link JFileChooser} and returns the selected filename. */ private String chooseFile(String title) { dlg.setDialogTitle(title); File CWD = null; String dir = SecurityUtilities.getSystemProperty("user.dir"); if (dir != null) { CWD = new File(dir); } if (CWD != null) { dlg.setCurrentDirectory(CWD); } int returnVal = dlg.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { String result = dlg.getSelectedFile().getCanonicalPath(); CWD = dlg.getSelectedFile().getParentFile(); Properties props = System.getProperties(); props.put("user.dir", CWD.getPath()); System.setProperties(props); return result; } catch (IOException ignored) { } catch (SecurityException ignored) { } } return null; } /** * Returns the current selected internal frame. */ private JInternalFrame getSelectedFrame() { JInternalFrame[] frames = desk.getAllFrames(); for (int i = 0; i < frames.length; i++) { if (frames[i].isShowing()) { return frames[i]; } } return frames[frames.length - 1]; } /** * Enables or disables the menu and tool bars with respect to the * state of script execution. */ private void updateEnabled(boolean interrupted) { ((Menubar)getJMenuBar()).updateEnabled(interrupted); for (int ci = 0, cc = toolBar.getComponentCount(); ci < cc; ci++) { boolean enableButton; if (ci == 0) { // Break enableButton = !interrupted; } else { enableButton = interrupted; } toolBar.getComponent(ci).setEnabled(enableButton); } if (interrupted) { toolBar.setEnabled(true); // raise the debugger window int state = getExtendedState(); if (state == Frame.ICONIFIED) { setExtendedState(Frame.NORMAL); } toFront(); context.enable(); } else { if (currentWindow != null) currentWindow.setPosition(-1); context.disable(); } } /** * Calls {@link JSplitPane#setResizeWeight} via reflection. * For compatibility, since JDK < 1.3 does not have this method. */ static void setResizeWeight(JSplitPane pane, double weight) { try { Method m = JSplitPane.class.getMethod("setResizeWeight", new Class[]{double.class}); m.invoke(pane, new Object[]{new Double(weight)}); } catch (NoSuchMethodException exc) { } catch (IllegalAccessException exc) { } catch (java.lang.reflect.InvocationTargetException exc) { } } /** * Reads the file with the given name and returns its contents as a String. */ private String readFile(String fileName) { String text; try { Reader r = new FileReader(fileName); try { text = Kit.readReader(r); } finally { r.close(); } } catch (IOException ex) { MessageDialogWrapper.showMessageDialog(this, ex.getMessage(), "Error reading "+fileName, JOptionPane.ERROR_MESSAGE); text = null; } return text; } // GuiCallback /** * Called when the source text for a script has been updated. */ public void updateSourceText(Dim.SourceInfo sourceInfo) { RunProxy proxy = new RunProxy(this, RunProxy.UPDATE_SOURCE_TEXT); proxy.sourceInfo = sourceInfo; SwingUtilities.invokeLater(proxy); } /** * Called when the interrupt loop has been entered. */ public void enterInterrupt(Dim.StackFrame lastFrame, String threadTitle, String alertMessage) { if (SwingUtilities.isEventDispatchThread()) { enterInterruptImpl(lastFrame, threadTitle, alertMessage); } else { RunProxy proxy = new RunProxy(this, RunProxy.ENTER_INTERRUPT); proxy.lastFrame = lastFrame; proxy.threadTitle = threadTitle; proxy.alertMessage = alertMessage; SwingUtilities.invokeLater(proxy); } } /** * Returns whether the current thread is the GUI event thread. */ public boolean isGuiEventThread() { return SwingUtilities.isEventDispatchThread(); } /** * Processes the next GUI event. */ public void dispatchNextGuiEvent() throws InterruptedException { EventQueue queue = awtEventQueue; if (queue == null) { queue = Toolkit.getDefaultToolkit().getSystemEventQueue(); awtEventQueue = queue; } AWTEvent event = queue.getNextEvent(); if (event instanceof ActiveEvent) { ((ActiveEvent)event).dispatch(); } else { Object source = event.getSource(); if (source instanceof Component) { Component comp = (Component)source; comp.dispatchEvent(event); } else if (source instanceof MenuComponent) { ((MenuComponent)source).dispatchEvent(event); } } } // ActionListener /** * Performs an action from the menu or toolbar. */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); int returnValue = -1; if (cmd.equals("Cut") || cmd.equals("Copy") || cmd.equals("Paste")) { JInternalFrame f = getSelectedFrame(); if (f != null && f instanceof ActionListener) { ((ActionListener)f).actionPerformed(e); } } else if (cmd.equals("Step Over")) { returnValue = Dim.STEP_OVER; } else if (cmd.equals("Step Into")) { returnValue = Dim.STEP_INTO; } else if (cmd.equals("Step Out")) { returnValue = Dim.STEP_OUT; } else if (cmd.equals("Go")) { returnValue = Dim.GO; } else if (cmd.equals("Break")) { dim.setBreak(); } else if (cmd.equals("Exit")) { exit(); } else if (cmd.equals("Open")) { String fileName = chooseFile("Select a file to compile"); if (fileName != null) { String text = readFile(fileName); if (text != null) { RunProxy proxy = new RunProxy(this, RunProxy.OPEN_FILE); proxy.fileName = fileName; proxy.text = text; new Thread(proxy).start(); } } } else if (cmd.equals("Load")) { String fileName = chooseFile("Select a file to execute"); if (fileName != null) { String text = readFile(fileName); if (text != null) { RunProxy proxy = new RunProxy(this, RunProxy.LOAD_FILE); proxy.fileName = fileName; proxy.text = text; new Thread(proxy).start(); } } } else if (cmd.equals("More Windows...")) { MoreWindows dlg = new MoreWindows(this, fileWindows, "Window", "Files"); dlg.showDialog(this); } else if (cmd.equals("Console")) { if (console.isIcon()) { desk.getDesktopManager().deiconifyFrame(console); } console.show(); desk.getDesktopManager().activateFrame(console); console.consoleTextArea.requestFocus(); } else if (cmd.equals("Cut")) { } else if (cmd.equals("Copy")) { } else if (cmd.equals("Paste")) { } else if (cmd.equals("Go to function...")) { FindFunction dlg = new FindFunction(this, "Go to function", "Function"); dlg.showDialog(this); } else if (cmd.equals("Tile")) { JInternalFrame[] frames = desk.getAllFrames(); int count = frames.length; int rows, cols; rows = cols = (int)Math.sqrt(count); if (rows*cols < count) { cols++; if (rows * cols < count) { rows++; } } Dimension size = desk.getSize(); int w = size.width/cols; int h = size.height/rows; int x = 0; int y = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { int index = (i*cols) + j; if (index >= frames.length) { break; } JInternalFrame f = frames[index]; try { f.setIcon(false); f.setMaximum(false); } catch (Exception exc) { } desk.getDesktopManager().setBoundsForFrame(f, x, y, w, h); x += w; } y += h; x = 0; } } else if (cmd.equals("Cascade")) { JInternalFrame[] frames = desk.getAllFrames(); int count = frames.length; int x, y, w, h; x = y = 0; h = desk.getHeight(); int d = h / count; if (d > 30) d = 30; for (int i = count -1; i >= 0; i--, x += d, y += d) { JInternalFrame f = frames[i]; try { f.setIcon(false); f.setMaximum(false); } catch (Exception exc) { } Dimension dimen = f.getPreferredSize(); w = dimen.width; h = dimen.height; desk.getDesktopManager().setBoundsForFrame(f, x, y, w, h); } } else { Object obj = getFileWindow(cmd); if (obj != null) { FileWindow w = (FileWindow)obj; try { if (w.isIcon()) { w.setIcon(false); } w.setVisible(true); w.moveToFront(); w.setSelected(true); } catch (Exception exc) { } } } if (returnValue != -1) { updateEnabled(false); dim.setReturnValue(returnValue); } } } /** * Helper class for showing a message dialog. */ class MessageDialogWrapper { /** * Shows a message dialog, wrapping the msg at 60 * columns. */ public static void showMessageDialog(Component parent, String msg, String title, int flags) { if (msg.length() > 60) { StringBuffer buf = new StringBuffer(); int len = msg.length(); int j = 0; int i; for (i = 0; i < len; i++, j++) { char c = msg.charAt(i); buf.append(c); if (Character.isWhitespace(c)) { int k; for (k = i + 1; k < len; k++) { if (Character.isWhitespace(msg.charAt(k))) { break; } } if (k < len) { int nextWordLen = k - i; if (j + nextWordLen > 60) { buf.append('\n'); j = 0; } } } } msg = buf.toString(); } JOptionPane.showMessageDialog(parent, msg, title, flags); } } /** * Extension of JTextArea for script evaluation input. */ class EvalTextArea extends JTextArea implements KeyListener, DocumentListener { /** * Serializable magic number. */ private static final long serialVersionUID = -3918033649601064194L; /** * The debugger GUI. */ private SwingGui debugGui; /** * History of expressions that have been evaluated */ private List history; /** * Index of the selected history item. */ private int historyIndex = -1; /** * Position in the display where output should go. */ private int outputMark; /** * Creates a new EvalTextArea. */ public EvalTextArea(SwingGui debugGui) { this.debugGui = debugGui; history = Collections.synchronizedList(new ArrayList()); Document doc = getDocument(); doc.addDocumentListener(this); addKeyListener(this); setLineWrap(true); setFont(new Font("Monospaced", 0, 12)); append("% "); outputMark = doc.getLength(); } /** * Selects a subrange of the text. */ @Override public void select(int start, int end) { //requestFocus(); super.select(start, end); } /** * Called when Enter is pressed. */ private synchronized void returnPressed() { Document doc = getDocument(); int len = doc.getLength(); Segment segment = new Segment(); try { doc.getText(outputMark, len - outputMark, segment); } catch (javax.swing.text.BadLocationException ignored) { ignored.printStackTrace(); } String text = segment.toString(); if (debugGui.dim.stringIsCompilableUnit(text)) { if (text.trim().length() > 0) { history.add(text); historyIndex = history.size(); } append("\n"); String result = debugGui.dim.eval(text); if (result.length() > 0) { append(result); append("\n"); } append("% "); outputMark = doc.getLength(); } else { append("\n"); } } /** * Writes output into the text area. */ public synchronized void write(String str) { insert(str, outputMark); int len = str.length(); outputMark += len; select(outputMark, outputMark); } // KeyListener /** * Called when a key is pressed. */ public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if (code == KeyEvent.VK_BACK_SPACE || code == KeyEvent.VK_LEFT) { if (outputMark == getCaretPosition()) { e.consume(); } } else if (code == KeyEvent.VK_HOME) { int caretPos = getCaretPosition(); if (caretPos == outputMark) { e.consume(); } else if (caretPos > outputMark) { if (!e.isControlDown()) { if (e.isShiftDown()) { moveCaretPosition(outputMark); } else { setCaretPosition(outputMark); } e.consume(); } } } else if (code == KeyEvent.VK_ENTER) { returnPressed(); e.consume(); } else if (code == KeyEvent.VK_UP) { historyIndex--; if (historyIndex >= 0) { if (historyIndex >= history.size()) { historyIndex = history.size() -1; } if (historyIndex >= 0) { String str = history.get(historyIndex); int len = getDocument().getLength(); replaceRange(str, outputMark, len); int caretPos = outputMark + str.length(); select(caretPos, caretPos); } else { historyIndex++; } } else { historyIndex++; } e.consume(); } else if (code == KeyEvent.VK_DOWN) { int caretPos = outputMark; if (history.size() > 0) { historyIndex++; if (historyIndex < 0) {historyIndex = 0;} int len = getDocument().getLength(); if (historyIndex < history.size()) { String str = history.get(historyIndex); replaceRange(str, outputMark, len); caretPos = outputMark + str.length(); } else { historyIndex = history.size(); replaceRange("", outputMark, len); } } select(caretPos, caretPos); e.consume(); } } /** * Called when a key is typed. */ public void keyTyped(KeyEvent e) { int keyChar = e.getKeyChar(); if (keyChar == 0x8 /* KeyEvent.VK_BACK_SPACE */) { if (outputMark == getCaretPosition()) { e.consume(); } } else if (getCaretPosition() < outputMark) { setCaretPosition(outputMark); } } /** * Called when a key is released. */ public synchronized void keyReleased(KeyEvent e) { } // DocumentListener /** * Called when text was inserted into the text area. */ public synchronized void insertUpdate(DocumentEvent e) { int len = e.getLength(); int off = e.getOffset(); if (outputMark > off) { outputMark += len; } } /** * Called when text was removed from the text area. */ public synchronized void removeUpdate(DocumentEvent e) { int len = e.getLength(); int off = e.getOffset(); if (outputMark > off) { if (outputMark >= off + len) { outputMark -= len; } else { outputMark = off; } } } /** * Attempts to clean up the damage done by {@link #updateUI()}. */ public synchronized void postUpdateUI() { //requestFocus(); setCaret(getCaret()); select(outputMark, outputMark); } /** * Called when text has changed in the text area. */ public synchronized void changedUpdate(DocumentEvent e) { } } /** * An internal frame for evaluating script. */ class EvalWindow extends JInternalFrame implements ActionListener { /** * Serializable magic number. */ private static final long serialVersionUID = -2860585845212160176L; /** * The text area into which expressions can be typed. */ private EvalTextArea evalTextArea; /** * Creates a new EvalWindow. */ public EvalWindow(String name, SwingGui debugGui) { super(name, true, false, true, true); evalTextArea = new EvalTextArea(debugGui); evalTextArea.setRows(24); evalTextArea.setColumns(80); JScrollPane scroller = new JScrollPane(evalTextArea); setContentPane(scroller); //scroller.setPreferredSize(new Dimension(600, 400)); pack(); setVisible(true); } /** * Sets whether the text area is enabled. */ @Override public void setEnabled(boolean b) { super.setEnabled(b); evalTextArea.setEnabled(b); } // ActionListener /** * Performs an action on the text area. */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cut")) { evalTextArea.cut(); } else if (cmd.equals("Copy")) { evalTextArea.copy(); } else if (cmd.equals("Paste")) { evalTextArea.paste(); } } } /** * Internal frame for the console. */ class JSInternalConsole extends JInternalFrame implements ActionListener { /** * Serializable magic number. */ private static final long serialVersionUID = -5523468828771087292L; /** * Creates a new JSInternalConsole. */ public JSInternalConsole(String name) { super(name, true, false, true, true); consoleTextArea = new ConsoleTextArea(null); consoleTextArea.setRows(24); consoleTextArea.setColumns(80); JScrollPane scroller = new JScrollPane(consoleTextArea); setContentPane(scroller); pack(); addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameActivated(InternalFrameEvent e) { // hack if (consoleTextArea.hasFocus()) { consoleTextArea.getCaret().setVisible(false); consoleTextArea.getCaret().setVisible(true); } } }); } /** * The console text area. */ ConsoleTextArea consoleTextArea; /** * Returns the input stream of the console text area. */ public InputStream getIn() { return consoleTextArea.getIn(); } /** * Returns the output stream of the console text area. */ public PrintStream getOut() { return consoleTextArea.getOut(); } /** * Returns the error stream of the console text area. */ public PrintStream getErr() { return consoleTextArea.getErr(); } // ActionListener /** * Performs an action on the text area. */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cut")) { consoleTextArea.cut(); } else if (cmd.equals("Copy")) { consoleTextArea.copy(); } else if (cmd.equals("Paste")) { consoleTextArea.paste(); } } } /** * Popup menu class for right-clicking on {@link FileTextArea}s. */ class FilePopupMenu extends JPopupMenu { /** * Serializable magic number. */ private static final long serialVersionUID = 3589525009546013565L; /** * The popup x position. */ int x; /** * The popup y position. */ int y; /** * Creates a new FilePopupMenu. */ public FilePopupMenu(FileTextArea w) { JMenuItem item; add(item = new JMenuItem("Set Breakpoint")); item.addActionListener(w); add(item = new JMenuItem("Clear Breakpoint")); item.addActionListener(w); add(item = new JMenuItem("Run")); item.addActionListener(w); } /** * Displays the menu at the given coordinates. */ public void show(JComponent comp, int x, int y) { this.x = x; this.y = y; super.show(comp, x, y); } } /** * Text area to display script source. */ class FileTextArea extends JTextArea implements ActionListener, PopupMenuListener, KeyListener, MouseListener { /** * Serializable magic number. */ private static final long serialVersionUID = -25032065448563720L; /** * The owning {@link FileWindow}. */ private FileWindow w; /** * The popup menu. */ private FilePopupMenu popup; /** * Creates a new FileTextArea. */ public FileTextArea(FileWindow w) { this.w = w; popup = new FilePopupMenu(this); popup.addPopupMenuListener(this); addMouseListener(this); addKeyListener(this); setFont(new Font("Monospaced", 0, 12)); } /** * Moves the selection to the given offset. */ public void select(int pos) { if (pos >= 0) { try { int line = getLineOfOffset(pos); Rectangle rect = modelToView(pos); if (rect == null) { select(pos, pos); } else { try { Rectangle nrect = modelToView(getLineStartOffset(line + 1)); if (nrect != null) { rect = nrect; } } catch (Exception exc) { } JViewport vp = (JViewport)getParent(); Rectangle viewRect = vp.getViewRect(); if (viewRect.y + viewRect.height > rect.y) { // need to scroll up select(pos, pos); } else { // need to scroll down rect.y += (viewRect.height - rect.height)/2; scrollRectToVisible(rect); select(pos, pos); } } } catch (BadLocationException exc) { select(pos, pos); //exc.printStackTrace(); } } } /** * Checks if the popup menu should be shown. */ private void checkPopup(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(this, e.getX(), e.getY()); } } // MouseListener /** * Called when a mouse button is pressed. */ public void mousePressed(MouseEvent e) { checkPopup(e); } /** * Called when the mouse is clicked. */ public void mouseClicked(MouseEvent e) { checkPopup(e); requestFocus(); getCaret().setVisible(true); } /** * Called when the mouse enters the component. */ public void mouseEntered(MouseEvent e) { } /** * Called when the mouse exits the component. */ public void mouseExited(MouseEvent e) { } /** * Called when a mouse button is released. */ public void mouseReleased(MouseEvent e) { checkPopup(e); } // PopupMenuListener /** * Called before the popup menu will become visible. */ public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } /** * Called before the popup menu will become invisible. */ public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { } /** * Called when the popup menu is cancelled. */ public void popupMenuCanceled(PopupMenuEvent e) { } // ActionListener /** * Performs an action. */ public void actionPerformed(ActionEvent e) { int pos = viewToModel(new Point(popup.x, popup.y)); popup.setVisible(false); String cmd = e.getActionCommand(); int line = -1; try { line = getLineOfOffset(pos); } catch (Exception exc) { } if (cmd.equals("Set Breakpoint")) { w.setBreakPoint(line + 1); } else if (cmd.equals("Clear Breakpoint")) { w.clearBreakPoint(line + 1); } else if (cmd.equals("Run")) { w.load(); } } // KeyListener /** * Called when a key is pressed. */ public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_ENTER: case KeyEvent.VK_DELETE: case KeyEvent.VK_TAB: e.consume(); break; } } /** * Called when a key is typed. */ public void keyTyped(KeyEvent e) { e.consume(); } /** * Called when a key is released. */ public void keyReleased(KeyEvent e) { e.consume(); } } /** * Dialog to list the available windows. */ class MoreWindows extends JDialog implements ActionListener { /** * Serializable magic number. */ private static final long serialVersionUID = 5177066296457377546L; /** * Last selected value. */ private String value; /** * The list component. */ private JList list; /** * Our parent frame. */ private SwingGui swingGui; /** * The "Select" button. */ private JButton setButton; /** * The "Cancel" button. */ private JButton cancelButton; /** * Creates a new MoreWindows. */ MoreWindows(SwingGui frame, Map fileWindows, String title, String labelText) { super(frame, title, true); this.swingGui = frame; //buttons cancelButton = new JButton("Cancel"); setButton = new JButton("Select"); cancelButton.addActionListener(this); setButton.addActionListener(this); getRootPane().setDefaultButton(setButton); //dim part of the dialog list = new JList(new DefaultListModel()); DefaultListModel model = (DefaultListModel)list.getModel(); model.clear(); //model.fireIntervalRemoved(model, 0, size); for (String data: fileWindows.keySet()) { model.addElement(data); } list.setSelectedIndex(0); //model.fireIntervalAdded(model, 0, data.length); setButton.setEnabled(true); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.addMouseListener(new MouseHandler()); JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(320, 240)); //XXX: Must do the following, too, or else the scroller thinks //XXX: it's taller than it is: listScroller.setMinimumSize(new Dimension(250, 80)); listScroller.setAlignmentX(LEFT_ALIGNMENT); //Create a container so that we can add a title around //the scroll pane. Can't add a title directly to the //scroll pane because its background would be white. //Lay out the label and scroll pane from top to button. JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS)); JLabel label = new JLabel(labelText); label.setLabelFor (list); listPane.add(label); listPane.add(Box.createRigidArea(new Dimension(0,5))); listPane.add(listScroller); listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //Lay out the buttons from left to right. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(cancelButton); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(setButton); //Put everything together, using the content pane's BorderLayout. Container contentPane = getContentPane(); contentPane.add(listPane, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.SOUTH); pack(); addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent ke) { int code = ke.getKeyCode(); if (code == KeyEvent.VK_ESCAPE) { ke.consume(); value = null; setVisible(false); } } }); } /** * Shows the dialog. */ public String showDialog(Component comp) { value = null; setLocationRelativeTo(comp); setVisible(true); return value; } // ActionListener /** * Performs an action. */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cancel")) { setVisible(false); value = null; } else if (cmd.equals("Select")) { value = (String)list.getSelectedValue(); setVisible(false); swingGui.showFileWindow(value, -1); } } /** * MouseListener implementation for {@link #list}. */ private class MouseHandler extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { setButton.doClick(); } } } } /** * Find function dialog. */ class FindFunction extends JDialog implements ActionListener { /** * Serializable magic number. */ private static final long serialVersionUID = 559491015232880916L; /** * Last selected function. */ private String value; /** * List of functions. */ private JList list; /** * The debug GUI frame. */ private SwingGui debugGui; /** * The "Select" button. */ private JButton setButton; /** * The "Cancel" button. */ private JButton cancelButton; /** * Creates a new FindFunction. */ public FindFunction(SwingGui debugGui, String title, String labelText) { super(debugGui, title, true); this.debugGui = debugGui; cancelButton = new JButton("Cancel"); setButton = new JButton("Select"); cancelButton.addActionListener(this); setButton.addActionListener(this); getRootPane().setDefaultButton(setButton); list = new JList(new DefaultListModel()); DefaultListModel model = (DefaultListModel)list.getModel(); model.clear(); String[] a = debugGui.dim.functionNames(); java.util.Arrays.sort(a); for (int i = 0; i < a.length; i++) { model.addElement(a[i]); } list.setSelectedIndex(0); setButton.setEnabled(a.length > 0); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.addMouseListener(new MouseHandler()); JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(320, 240)); listScroller.setMinimumSize(new Dimension(250, 80)); listScroller.setAlignmentX(LEFT_ALIGNMENT); //Create a container so that we can add a title around //the scroll pane. Can't add a title directly to the //scroll pane because its background would be white. //Lay out the label and scroll pane from top to button. JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS)); JLabel label = new JLabel(labelText); label.setLabelFor (list); listPane.add(label); listPane.add(Box.createRigidArea(new Dimension(0,5))); listPane.add(listScroller); listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //Lay out the buttons from left to right. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(cancelButton); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(setButton); //Put everything together, using the content pane's BorderLayout. Container contentPane = getContentPane(); contentPane.add(listPane, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.SOUTH); pack(); addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent ke) { int code = ke.getKeyCode(); if (code == KeyEvent.VK_ESCAPE) { ke.consume(); value = null; setVisible(false); } } }); } /** * Shows the dialog. */ public String showDialog(Component comp) { value = null; setLocationRelativeTo(comp); setVisible(true); return value; } // ActionListener /** * Performs an action. */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cancel")) { setVisible(false); value = null; } else if (cmd.equals("Select")) { if (list.getSelectedIndex() < 0) { return; } try { value = (String)list.getSelectedValue(); } catch (ArrayIndexOutOfBoundsException exc) { return; } setVisible(false); Dim.FunctionSource item = debugGui.dim.functionSourceByName(value); if (item != null) { Dim.SourceInfo si = item.sourceInfo(); String url = si.url(); int lineNumber = item.firstLine(); debugGui.showFileWindow(url, lineNumber); } } } /** * MouseListener implementation for {@link #list}. */ class MouseHandler extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { setButton.doClick(); } } } } /** * Gutter for FileWindows. */ class FileHeader extends JPanel implements MouseListener { /** * Serializable magic number. */ private static final long serialVersionUID = -2858905404778259127L; /** * The line that the mouse was pressed on. */ private int pressLine = -1; /** * The owning FileWindow. */ private FileWindow fileWindow; /** * Creates a new FileHeader. */ public FileHeader(FileWindow fileWindow) { this.fileWindow = fileWindow; addMouseListener(this); update(); } /** * Updates the gutter. */ public void update() { FileTextArea textArea = fileWindow.textArea; Font font = textArea.getFont(); setFont(font); FontMetrics metrics = getFontMetrics(font); int h = metrics.getHeight(); int lineCount = textArea.getLineCount() + 1; String dummy = Integer.toString(lineCount); if (dummy.length() < 2) { dummy = "99"; } Dimension d = new Dimension(); d.width = metrics.stringWidth(dummy) + 16; d.height = lineCount * h + 100; setPreferredSize(d); setSize(d); } /** * Paints the component. */ @Override public void paint(Graphics g) { super.paint(g); FileTextArea textArea = fileWindow.textArea; Font font = textArea.getFont(); g.setFont(font); FontMetrics metrics = getFontMetrics(font); Rectangle clip = g.getClipBounds(); g.setColor(getBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); int ascent = metrics.getMaxAscent(); int h = metrics.getHeight(); int lineCount = textArea.getLineCount() + 1; String dummy = Integer.toString(lineCount); if (dummy.length() < 2) { dummy = "99"; } int startLine = clip.y / h; int endLine = (clip.y + clip.height) / h + 1; int width = getWidth(); if (endLine > lineCount) endLine = lineCount; for (int i = startLine; i < endLine; i++) { String text; int pos = -2; try { pos = textArea.getLineStartOffset(i); } catch (BadLocationException ignored) { } boolean isBreakPoint = fileWindow.isBreakPoint(i + 1); text = Integer.toString(i + 1) + " "; int y = i * h; g.setColor(Color.blue); g.drawString(text, 0, y + ascent); int x = width - ascent; if (isBreakPoint) { g.setColor(new Color(0x80, 0x00, 0x00)); int dy = y + ascent - 9; g.fillOval(x, dy, 9, 9); g.drawOval(x, dy, 8, 8); g.drawOval(x, dy, 9, 9); } if (pos == fileWindow.currentPos) { Polygon arrow = new Polygon(); int dx = x; y += ascent - 10; int dy = y; arrow.addPoint(dx, dy + 3); arrow.addPoint(dx + 5, dy + 3); for (x = dx + 5; x <= dx + 10; x++, y++) { arrow.addPoint(x, y); } for (x = dx + 9; x >= dx + 5; x--, y++) { arrow.addPoint(x, y); } arrow.addPoint(dx + 5, dy + 7); arrow.addPoint(dx, dy + 7); g.setColor(Color.yellow); g.fillPolygon(arrow); g.setColor(Color.black); g.drawPolygon(arrow); } } } // MouseListener /** * Called when the mouse enters the component. */ public void mouseEntered(MouseEvent e) { } /** * Called when a mouse button is pressed. */ public void mousePressed(MouseEvent e) { Font font = fileWindow.textArea.getFont(); FontMetrics metrics = getFontMetrics(font); int h = metrics.getHeight(); pressLine = e.getY() / h; } /** * Called when the mouse is clicked. */ public void mouseClicked(MouseEvent e) { } /** * Called when the mouse exits the component. */ public void mouseExited(MouseEvent e) { } /** * Called when a mouse button is released. */ public void mouseReleased(MouseEvent e) { if (e.getComponent() == this && (e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) { int y = e.getY(); Font font = fileWindow.textArea.getFont(); FontMetrics metrics = getFontMetrics(font); int h = metrics.getHeight(); int line = y/h; if (line == pressLine) { fileWindow.toggleBreakPoint(line + 1); } else { pressLine = -1; } } } } /** * An internal frame for script files. */ class FileWindow extends JInternalFrame implements ActionListener { /** * Serializable magic number. */ private static final long serialVersionUID = -6212382604952082370L; /** * The debugger GUI. */ private SwingGui debugGui; /** * The SourceInfo object that describes the file. */ private Dim.SourceInfo sourceInfo; /** * The FileTextArea that displays the file. */ FileTextArea textArea; /** * The FileHeader that is the gutter for {@link #textArea}. */ private FileHeader fileHeader; /** * Scroll pane for containing {@link #textArea}. */ private JScrollPane p; /** * The current offset position. */ int currentPos; /** * Loads the file. */ void load() { String url = getUrl(); if (url != null) { RunProxy proxy = new RunProxy(debugGui, RunProxy.LOAD_FILE); proxy.fileName = url; proxy.text = sourceInfo.source(); new Thread(proxy).start(); } } /** * Returns the offset position for the given line. */ public int getPosition(int line) { int result = -1; try { result = textArea.getLineStartOffset(line); } catch (javax.swing.text.BadLocationException exc) { } return result; } /** * Returns whether the given line has a breakpoint. */ public boolean isBreakPoint(int line) { return sourceInfo.breakableLine(line) && sourceInfo.breakpoint(line); } /** * Toggles the breakpoint on the given line. */ public void toggleBreakPoint(int line) { if (!isBreakPoint(line)) { setBreakPoint(line); } else { clearBreakPoint(line); } } /** * Sets a breakpoint on the given line. */ public void setBreakPoint(int line) { if (sourceInfo.breakableLine(line)) { boolean changed = sourceInfo.breakpoint(line, true); if (changed) { fileHeader.repaint(); } } } /** * Clears a breakpoint from the given line. */ public void clearBreakPoint(int line) { if (sourceInfo.breakableLine(line)) { boolean changed = sourceInfo.breakpoint(line, false); if (changed) { fileHeader.repaint(); } } } /** * Creates a new FileWindow. */ public FileWindow(SwingGui debugGui, Dim.SourceInfo sourceInfo) { super(SwingGui.getShortName(sourceInfo.url()), true, true, true, true); this.debugGui = debugGui; this.sourceInfo = sourceInfo; updateToolTip(); currentPos = -1; textArea = new FileTextArea(this); textArea.setRows(24); textArea.setColumns(80); p = new JScrollPane(); fileHeader = new FileHeader(this); p.setViewportView(textArea); p.setRowHeaderView(fileHeader); setContentPane(p); pack(); updateText(sourceInfo); textArea.select(0); } /** * Updates the tool tip contents. */ private void updateToolTip() { // Try to set tool tip on frame. On Mac OS X 10.5, // the number of components is different, so try to be safe. int n = getComponentCount() - 1; if (n > 1) { n = 1; } else if (n < 0) { return; } Component c = getComponent(n); // this will work at least for Metal L&F if (c != null && c instanceof JComponent) { ((JComponent)c).setToolTipText(getUrl()); } } /** * Returns the URL of the source. */ public String getUrl() { return sourceInfo.url(); } /** * Called when the text of the script has changed. */ public void updateText(Dim.SourceInfo sourceInfo) { this.sourceInfo = sourceInfo; String newText = sourceInfo.source(); if (!textArea.getText().equals(newText)) { textArea.setText(newText); int pos = 0; if (currentPos != -1) { pos = currentPos; } textArea.select(pos); } fileHeader.update(); fileHeader.repaint(); } /** * Sets the cursor position. */ public void setPosition(int pos) { textArea.select(pos); currentPos = pos; fileHeader.repaint(); } /** * Selects a range of characters. */ public void select(int start, int end) { int docEnd = textArea.getDocument().getLength(); textArea.select(docEnd, docEnd); textArea.select(start, end); } /** * Disposes this FileWindow. */ @Override public void dispose() { debugGui.removeWindow(this); super.dispose(); } // ActionListener /** * Performs an action. */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cut")) { // textArea.cut(); } else if (cmd.equals("Copy")) { textArea.copy(); } else if (cmd.equals("Paste")) { // textArea.paste(); } } } /** * Table model class for watched expressions. */ class MyTableModel extends AbstractTableModel { /** * Serializable magic number. */ private static final long serialVersionUID = 2971618907207577000L; /** * The debugger GUI. */ private SwingGui debugGui; /** * List of watched expressions. */ private List expressions; /** * List of values from evaluated from {@link #expressions}. */ private List values; /** * Creates a new MyTableModel. */ public MyTableModel(SwingGui debugGui) { this.debugGui = debugGui; expressions = Collections.synchronizedList(new ArrayList()); values = Collections.synchronizedList(new ArrayList()); expressions.add(""); values.add(""); } /** * Returns the number of columns in the table (2). */ public int getColumnCount() { return 2; } /** * Returns the number of rows in the table. */ public int getRowCount() { return expressions.size(); } /** * Returns the name of the given column. */ @Override public String getColumnName(int column) { switch (column) { case 0: return "Expression"; case 1: return "Value"; } return null; } /** * Returns whether the given cell is editable. */ @Override public boolean isCellEditable(int row, int column) { return true; } /** * Returns the value in the given cell. */ public Object getValueAt(int row, int column) { switch (column) { case 0: return expressions.get(row); case 1: return values.get(row); } return ""; } /** * Sets the value in the given cell. */ @Override public void setValueAt(Object value, int row, int column) { switch (column) { case 0: String expr = value.toString(); expressions.set(row, expr); String result = ""; if (expr.length() > 0) { result = debugGui.dim.eval(expr); if (result == null) result = ""; } values.set(row, result); updateModel(); if (row + 1 == expressions.size()) { expressions.add(""); values.add(""); fireTableRowsInserted(row + 1, row + 1); } break; case 1: // just reset column 2; ignore edits fireTableDataChanged(); } } /** * Re-evaluates the expressions in the table. */ void updateModel() { for (int i = 0; i < expressions.size(); ++i) { String expr = expressions.get(i); String result = ""; if (expr.length() > 0) { result = debugGui.dim.eval(expr); if (result == null) result = ""; } else { result = ""; } result = result.replace('\n', ' '); values.set(i, result); } fireTableDataChanged(); } } /** * A table for evaluated expressions. */ class Evaluator extends JTable { /** * Serializable magic number. */ private static final long serialVersionUID = 8133672432982594256L; /** * The {@link TableModel} for this table. */ MyTableModel tableModel; /** * Creates a new Evaluator. */ public Evaluator(SwingGui debugGui) { super(new MyTableModel(debugGui)); tableModel = (MyTableModel)getModel(); } } /** * Tree model for script object inspection. */ class VariableModel implements TreeTableModel { /** * Serializable magic number. */ private static final String[] cNames = { " Name", " Value" }; /** * Tree column types. */ private static final Class[] cTypes = { TreeTableModel.class, String.class }; /** * Empty {@link VariableNode} array. */ private static final VariableNode[] CHILDLESS = new VariableNode[0]; /** * The debugger. */ private Dim debugger; /** * The root node. */ private VariableNode root; /** * Creates a new VariableModel. */ public VariableModel() { } /** * Creates a new VariableModel. */ public VariableModel(Dim debugger, Object scope) { this.debugger = debugger; this.root = new VariableNode(scope, "this"); } // TreeTableModel /** * Returns the root node of the tree. */ public Object getRoot() { if (debugger == null) { return null; } return root; } /** * Returns the number of children of the given node. */ public int getChildCount(Object nodeObj) { if (debugger == null) { return 0; } VariableNode node = (VariableNode) nodeObj; return children(node).length; } /** * Returns a child of the given node. */ public Object getChild(Object nodeObj, int i) { if (debugger == null) { return null; } VariableNode node = (VariableNode) nodeObj; return children(node)[i]; } /** * Returns whether the given node is a leaf node. */ public boolean isLeaf(Object nodeObj) { if (debugger == null) { return true; } VariableNode node = (VariableNode) nodeObj; return children(node).length == 0; } /** * Returns the index of a node under its parent. */ public int getIndexOfChild(Object parentObj, Object childObj) { if (debugger == null) { return -1; } VariableNode parent = (VariableNode) parentObj; VariableNode child = (VariableNode) childObj; VariableNode[] children = children(parent); for (int i = 0; i != children.length; i++) { if (children[i] == child) { return i; } } return -1; } /** * Returns whether the given cell is editable. */ public boolean isCellEditable(Object node, int column) { return column == 0; } /** * Sets the value at the given cell. */ public void setValueAt(Object value, Object node, int column) { } /** * Adds a TreeModelListener to this tree. */ public void addTreeModelListener(TreeModelListener l) { } /** * Removes a TreeModelListener from this tree. */ public void removeTreeModelListener(TreeModelListener l) { } public void valueForPathChanged(TreePath path, Object newValue) { } // TreeTableNode /** * Returns the number of columns. */ public int getColumnCount() { return cNames.length; } /** * Returns the name of the given column. */ public String getColumnName(int column) { return cNames[column]; } /** * Returns the type of value stored in the given column. */ public Class getColumnClass(int column) { return cTypes[column]; } /** * Returns the value at the given cell. */ public Object getValueAt(Object nodeObj, int column) { if (debugger == null) { return null; } VariableNode node = (VariableNode)nodeObj; switch (column) { case 0: // Name return node.toString(); case 1: // Value String result; try { result = debugger.objectToString(getValue(node)); } catch (RuntimeException exc) { result = exc.getMessage(); } StringBuffer buf = new StringBuffer(); int len = result.length(); for (int i = 0; i < len; i++) { char ch = result.charAt(i); if (Character.isISOControl(ch)) { ch = ' '; } buf.append(ch); } return buf.toString(); } return null; } /** * Returns an array of the children of the given node. */ private VariableNode[] children(VariableNode node) { if (node.children != null) { return node.children; } VariableNode[] children; Object value = getValue(node); Object[] ids = debugger.getObjectIds(value); if (ids == null || ids.length == 0) { children = CHILDLESS; } else { Arrays.sort(ids, new Comparator() { public int compare(Object l, Object r) { if (l instanceof String) { if (r instanceof Integer) { return -1; } return ((String)l).compareToIgnoreCase((String)r); } else { if (r instanceof String) { return 1; } int lint = ((Integer)l).intValue(); int rint = ((Integer)r).intValue(); return lint - rint; } } }); children = new VariableNode[ids.length]; for (int i = 0; i != ids.length; ++i) { children[i] = new VariableNode(value, ids[i]); } } node.children = children; return children; } /** * Returns the value of the given node. */ public Object getValue(VariableNode node) { try { return debugger.getObjectProperty(node.object, node.id); } catch (Exception exc) { return "undefined"; } } /** * A variable node in the tree. */ private static class VariableNode { /** * The script object. */ private Object object; /** * The object name. Either a String or an Integer. */ private Object id; /** * Array of child nodes. This is filled with the properties of * the object. */ private VariableNode[] children; /** * Creates a new VariableNode. */ public VariableNode(Object object, Object id) { this.object = object; this.id = id; } /** * Returns a string representation of this node. */ @Override public String toString() { return id instanceof String ? (String) id : "[" + ((Integer) id).intValue() + "]"; } } } /** * A tree table for browsing script objects. */ class MyTreeTable extends JTreeTable { /** * Serializable magic number. */ private static final long serialVersionUID = 3457265548184453049L; /** * Creates a new MyTreeTable. */ public MyTreeTable(VariableModel model) { super(model); } /** * Initializes a tree for this tree table. */ public JTree resetTree(TreeTableModel treeTableModel) { tree = new TreeTableCellRenderer(treeTableModel); // Install a tableModel representing the visible rows in the tree. super.setModel(new TreeTableModelAdapter(treeTableModel, tree)); // Force the JTable and JTree to share their row selection models. ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); tree.setSelectionModel(selectionWrapper); setSelectionModel(selectionWrapper.getListSelectionModel()); // Make the tree and table row heights the same. if (tree.getRowHeight() < 1) { // Metal looks better like this. setRowHeight(18); } // Install the tree editor renderer and editor. setDefaultRenderer(TreeTableModel.class, tree); setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor()); setShowGrid(true); setIntercellSpacing(new Dimension(1,1)); tree.setRootVisible(false); tree.setShowsRootHandles(true); DefaultTreeCellRenderer r = (DefaultTreeCellRenderer)tree.getCellRenderer(); r.setOpenIcon(null); r.setClosedIcon(null); r.setLeafIcon(null); return tree; } /** * Returns whether the cell under the coordinates of the mouse * in the {@link EventObject} is editable. */ public boolean isCellEditable(EventObject e) { if (e instanceof MouseEvent) { MouseEvent me = (MouseEvent)e; // If the modifiers are not 0 (or the left mouse button), // tree may try and toggle the selection, and table // will then try and toggle, resulting in the // selection remaining the same. To avoid this, we // only dispatch when the modifiers are 0 (or the left mouse // button). if (me.getModifiers() == 0 || ((me.getModifiers() & (InputEvent.BUTTON1_MASK|1024)) != 0 && (me.getModifiers() & (InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.ALT_MASK | InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK | 64 | //SHIFT_DOWN_MASK 128 | //CTRL_DOWN_MASK 512 | // ALT_DOWN_MASK 2048 | //BUTTON2_DOWN_MASK 4096 //BUTTON3_DOWN_MASK )) == 0)) { int row = rowAtPoint(me.getPoint()); for (int counter = getColumnCount() - 1; counter >= 0; counter--) { if (TreeTableModel.class == getColumnClass(counter)) { MouseEvent newME = new MouseEvent (MyTreeTable.this.tree, me.getID(), me.getWhen(), me.getModifiers(), me.getX() - getCellRect(row, counter, true).x, me.getY(), me.getClickCount(), me.isPopupTrigger()); MyTreeTable.this.tree.dispatchEvent(newME); break; } } } if (me.getClickCount() >= 3) { return true; } return false; } if (e == null) { return true; } return false; } } /** * Panel that shows information about the context. */ class ContextWindow extends JPanel implements ActionListener { /** * Serializable magic number. */ private static final long serialVersionUID = 2306040975490228051L; /** * The debugger GUI. */ private SwingGui debugGui; /** * The combo box that holds the stack frames. */ JComboBox context; /** * Tool tips for the stack frames. */ List toolTips; /** * Tabbed pane for "this" and "locals". */ private JTabbedPane tabs; /** * Tabbed pane for "watch" and "evaluate". */ private JTabbedPane tabs2; /** * The table showing the "this" object. */ private MyTreeTable thisTable; /** * The table showing the stack local variables. */ private MyTreeTable localsTable; /** * The {@link #evaluator}'s table model. */ private MyTableModel tableModel; /** * The script evaluator table. */ private Evaluator evaluator; /** * The script evaluation text area. */ private EvalTextArea cmdLine; /** * The split pane. */ JSplitPane split; /** * Whether the ContextWindow is enabled. */ private boolean enabled; /** * Creates a new ContextWindow. */ public ContextWindow(final SwingGui debugGui) { this.debugGui = debugGui; enabled = false; JPanel left = new JPanel(); JToolBar t1 = new JToolBar(); t1.setName("Variables"); t1.setLayout(new GridLayout()); t1.add(left); JPanel p1 = new JPanel(); p1.setLayout(new GridLayout()); JPanel p2 = new JPanel(); p2.setLayout(new GridLayout()); p1.add(t1); JLabel label = new JLabel("Context:"); context = new JComboBox(); context.setLightWeightPopupEnabled(false); toolTips = Collections.synchronizedList(new java.util.ArrayList()); label.setBorder(context.getBorder()); context.addActionListener(this); context.setActionCommand("ContextSwitch"); GridBagLayout layout = new GridBagLayout(); left.setLayout(layout); GridBagConstraints lc = new GridBagConstraints(); lc.insets.left = 5; lc.anchor = GridBagConstraints.WEST; lc.ipadx = 5; layout.setConstraints(label, lc); left.add(label); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.WEST; layout.setConstraints(context, c); left.add(context); tabs = new JTabbedPane(SwingConstants.BOTTOM); tabs.setPreferredSize(new Dimension(500,300)); thisTable = new MyTreeTable(new VariableModel()); JScrollPane jsp = new JScrollPane(thisTable); jsp.getViewport().setViewSize(new Dimension(5,2)); tabs.add("this", jsp); localsTable = new MyTreeTable(new VariableModel()); localsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); localsTable.setPreferredSize(null); jsp = new JScrollPane(localsTable); tabs.add("Locals", jsp); c.weightx = c.weighty = 1; c.gridheight = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.WEST; layout.setConstraints(tabs, c); left.add(tabs); evaluator = new Evaluator(debugGui); cmdLine = new EvalTextArea(debugGui); //cmdLine.requestFocus(); tableModel = evaluator.tableModel; jsp = new JScrollPane(evaluator); JToolBar t2 = new JToolBar(); t2.setName("Evaluate"); tabs2 = new JTabbedPane(SwingConstants.BOTTOM); tabs2.add("Watch", jsp); tabs2.add("Evaluate", new JScrollPane(cmdLine)); tabs2.setPreferredSize(new Dimension(500,300)); t2.setLayout(new GridLayout()); t2.add(tabs2); p2.add(t2); evaluator.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, p1, p2); split.setOneTouchExpandable(true); SwingGui.setResizeWeight(split, 0.5); setLayout(new BorderLayout()); add(split, BorderLayout.CENTER); final JToolBar finalT1 = t1; final JToolBar finalT2 = t2; final JPanel finalP1 = p1; final JPanel finalP2 = p2; final JSplitPane finalSplit = split; final JPanel finalThis = this; ComponentListener clistener = new ComponentListener() { boolean t2Docked = true; void check(Component comp) { Component thisParent = finalThis.getParent(); if (thisParent == null) { return; } Component parent = finalT1.getParent(); boolean leftDocked = true; boolean rightDocked = true; boolean adjustVerticalSplit = false; if (parent != null) { if (parent != finalP1) { while (!(parent instanceof JFrame)) { parent = parent.getParent(); } JFrame frame = (JFrame)parent; debugGui.addTopLevel("Variables", frame); // We need the following hacks because: // - We want an undocked toolbar to be // resizable. // - We are using JToolbar as a container of a // JComboBox. Without this JComboBox's popup // can get left floating when the toolbar is // re-docked. // // We make the frame resizable and then // remove JToolbar's window listener // and insert one of our own that first ensures // the JComboBox's popup window is closed // and then calls JToolbar's window listener. if (!frame.isResizable()) { frame.setResizable(true); frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); final EventListener[] l = frame.getListeners(WindowListener.class); frame.removeWindowListener((WindowListener)l[0]); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { context.hidePopup(); ((WindowListener)l[0]).windowClosing(e); } }); //adjustVerticalSplit = true; } leftDocked = false; } else { leftDocked = true; } } parent = finalT2.getParent(); if (parent != null) { if (parent != finalP2) { while (!(parent instanceof JFrame)) { parent = parent.getParent(); } JFrame frame = (JFrame)parent; debugGui.addTopLevel("Evaluate", frame); frame.setResizable(true); rightDocked = false; } else { rightDocked = true; } } if (leftDocked && t2Docked && rightDocked && t2Docked) { // no change return; } t2Docked = rightDocked; JSplitPane split = (JSplitPane)thisParent; if (leftDocked) { if (rightDocked) { finalSplit.setDividerLocation(0.5); } else { finalSplit.setDividerLocation(1.0); } if (adjustVerticalSplit) { split.setDividerLocation(0.66); } } else if (rightDocked) { finalSplit.setDividerLocation(0.0); split.setDividerLocation(0.66); } else { // both undocked split.setDividerLocation(1.0); } } public void componentHidden(ComponentEvent e) { check(e.getComponent()); } public void componentMoved(ComponentEvent e) { check(e.getComponent()); } public void componentResized(ComponentEvent e) { check(e.getComponent()); } public void componentShown(ComponentEvent e) { check(e.getComponent()); } }; p1.addContainerListener(new ContainerListener() { public void componentAdded(ContainerEvent e) { Component thisParent = finalThis.getParent(); JSplitPane split = (JSplitPane)thisParent; if (e.getChild() == finalT1) { if (finalT2.getParent() == finalP2) { // both docked finalSplit.setDividerLocation(0.5); } else { // left docked only finalSplit.setDividerLocation(1.0); } split.setDividerLocation(0.66); } } public void componentRemoved(ContainerEvent e) { Component thisParent = finalThis.getParent(); JSplitPane split = (JSplitPane)thisParent; if (e.getChild() == finalT1) { if (finalT2.getParent() == finalP2) { // right docked only finalSplit.setDividerLocation(0.0); split.setDividerLocation(0.66); } else { // both undocked split.setDividerLocation(1.0); } } } }); t1.addComponentListener(clistener); t2.addComponentListener(clistener); disable(); } /** * Disables the component. */ @Override public void disable() { context.setEnabled(false); thisTable.setEnabled(false); localsTable.setEnabled(false); evaluator.setEnabled(false); cmdLine.setEnabled(false); } /** * Enables the component. */ @Override public void enable() { context.setEnabled(true); thisTable.setEnabled(true); localsTable.setEnabled(true); evaluator.setEnabled(true); cmdLine.setEnabled(true); } /** * Disables updating of the component. */ public void disableUpdate() { enabled = false; } /** * Enables updating of the component. */ public void enableUpdate() { enabled = true; } // ActionListener /** * Performs an action. */ public void actionPerformed(ActionEvent e) { if (!enabled) return; if (e.getActionCommand().equals("ContextSwitch")) { Dim.ContextData contextData = debugGui.dim.currentContextData(); if (contextData == null) { return; } int frameIndex = context.getSelectedIndex(); context.setToolTipText(toolTips.get(frameIndex)); int frameCount = contextData.frameCount(); if (frameIndex >= frameCount) { return; } Dim.StackFrame frame = contextData.getFrame(frameIndex); Object scope = frame.scope(); Object thisObj = frame.thisObj(); thisTable.resetTree(new VariableModel(debugGui.dim, thisObj)); VariableModel scopeModel; if (scope != thisObj) { scopeModel = new VariableModel(debugGui.dim, scope); } else { scopeModel = new VariableModel(); } localsTable.resetTree(scopeModel); debugGui.dim.contextSwitch(frameIndex); debugGui.showStopLine(frame); tableModel.updateModel(); } } } /** * The debugger frame menu bar. */ class Menubar extends JMenuBar implements ActionListener { /** * Serializable magic number. */ private static final long serialVersionUID = 3217170497245911461L; /** * Items that are enabled only when interrupted. */ private List interruptOnlyItems = Collections.synchronizedList(new ArrayList()); /** * Items that are enabled only when running. */ private List runOnlyItems = Collections.synchronizedList(new ArrayList()); /** * The debugger GUI. */ private SwingGui debugGui; /** * The menu listing the internal frames. */ private JMenu windowMenu; /** * The "Break on exceptions" menu item. */ private JCheckBoxMenuItem breakOnExceptions; /** * The "Break on enter" menu item. */ private JCheckBoxMenuItem breakOnEnter; /** * The "Break on return" menu item. */ private JCheckBoxMenuItem breakOnReturn; /** * Creates a new Menubar. */ Menubar(SwingGui debugGui) { super(); this.debugGui = debugGui; String[] fileItems = {"Open...", "Run...", "", "Exit"}; String[] fileCmds = {"Open", "Load", "", "Exit"}; char[] fileShortCuts = {'0', 'N', 0, 'X'}; int[] fileAccelerators = {KeyEvent.VK_O, KeyEvent.VK_N, 0, KeyEvent.VK_Q}; String[] editItems = {"Cut", "Copy", "Paste", "Go to function..."}; char[] editShortCuts = {'T', 'C', 'P', 'F'}; String[] debugItems = {"Break", "Go", "Step Into", "Step Over", "Step Out"}; char[] debugShortCuts = {'B', 'G', 'I', 'O', 'T'}; String[] plafItems = {"Metal", "Windows", "Motif"}; char [] plafShortCuts = {'M', 'W', 'F'}; int[] debugAccelerators = {KeyEvent.VK_PAUSE, KeyEvent.VK_F5, KeyEvent.VK_F11, KeyEvent.VK_F7, KeyEvent.VK_F8, 0, 0}; JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('E'); JMenu plafMenu = new JMenu("Platform"); plafMenu.setMnemonic('P'); JMenu debugMenu = new JMenu("Debug"); debugMenu.setMnemonic('D'); windowMenu = new JMenu("Window"); windowMenu.setMnemonic('W'); for (int i = 0; i < fileItems.length; ++i) { if (fileItems[i].length() == 0) { fileMenu.addSeparator(); } else { JMenuItem item = new JMenuItem(fileItems[i], fileShortCuts[i]); item.setActionCommand(fileCmds[i]); item.addActionListener(this); fileMenu.add(item); if (fileAccelerators[i] != 0) { KeyStroke k = KeyStroke.getKeyStroke(fileAccelerators[i], Event.CTRL_MASK); item.setAccelerator(k); } } } for (int i = 0; i < editItems.length; ++i) { JMenuItem item = new JMenuItem(editItems[i], editShortCuts[i]); item.addActionListener(this); editMenu.add(item); } for (int i = 0; i < plafItems.length; ++i) { JMenuItem item = new JMenuItem(plafItems[i], plafShortCuts[i]); item.addActionListener(this); plafMenu.add(item); } for (int i = 0; i < debugItems.length; ++i) { JMenuItem item = new JMenuItem(debugItems[i], debugShortCuts[i]); item.addActionListener(this); if (debugAccelerators[i] != 0) { KeyStroke k = KeyStroke.getKeyStroke(debugAccelerators[i], 0); item.setAccelerator(k); } if (i != 0) { interruptOnlyItems.add(item); } else { runOnlyItems.add(item); } debugMenu.add(item); } breakOnExceptions = new JCheckBoxMenuItem("Break on Exceptions"); breakOnExceptions.setMnemonic('X'); breakOnExceptions.addActionListener(this); breakOnExceptions.setSelected(false); debugMenu.add(breakOnExceptions); breakOnEnter = new JCheckBoxMenuItem("Break on Function Enter"); breakOnEnter.setMnemonic('E'); breakOnEnter.addActionListener(this); breakOnEnter.setSelected(false); debugMenu.add(breakOnEnter); breakOnReturn = new JCheckBoxMenuItem("Break on Function Return"); breakOnReturn.setMnemonic('R'); breakOnReturn.addActionListener(this); breakOnReturn.setSelected(false); debugMenu.add(breakOnReturn); add(fileMenu); add(editMenu); //add(plafMenu); add(debugMenu); JMenuItem item; windowMenu.add(item = new JMenuItem("Cascade", 'A')); item.addActionListener(this); windowMenu.add(item = new JMenuItem("Tile", 'T')); item.addActionListener(this); windowMenu.addSeparator(); windowMenu.add(item = new JMenuItem("Console", 'C')); item.addActionListener(this); add(windowMenu); updateEnabled(false); } /** * Returns the "Break on exceptions" menu item. */ public JCheckBoxMenuItem getBreakOnExceptions() { return breakOnExceptions; } /** * Returns the "Break on enter" menu item. */ public JCheckBoxMenuItem getBreakOnEnter() { return breakOnEnter; } /** * Returns the "Break on return" menu item. */ public JCheckBoxMenuItem getBreakOnReturn() { return breakOnReturn; } /** * Returns the "Debug" menu. */ public JMenu getDebugMenu() { return getMenu(2); } // ActionListener /** * Performs an action. */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); String plaf_name = null; if (cmd.equals("Metal")) { plaf_name = "javax.swing.plaf.metal.MetalLookAndFeel"; } else if (cmd.equals("Windows")) { plaf_name = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; } else if (cmd.equals("Motif")) { plaf_name = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; } else { Object source = e.getSource(); if (source == breakOnExceptions) { debugGui.dim.setBreakOnExceptions(breakOnExceptions.isSelected()); } else if (source == breakOnEnter) { debugGui.dim.setBreakOnEnter(breakOnEnter.isSelected()); } else if (source == breakOnReturn) { debugGui.dim.setBreakOnReturn(breakOnReturn.isSelected()); } else { debugGui.actionPerformed(e); } return; } try { UIManager.setLookAndFeel(plaf_name); SwingUtilities.updateComponentTreeUI(debugGui); SwingUtilities.updateComponentTreeUI(debugGui.dlg); } catch (Exception ignored) { //ignored.printStackTrace(); } } /** * Adds a file to the window menu. */ public void addFile(String url) { int count = windowMenu.getItemCount(); JMenuItem item; if (count == 4) { windowMenu.addSeparator(); count++; } JMenuItem lastItem = windowMenu.getItem(count -1); boolean hasMoreWin = false; int maxWin = 5; if (lastItem != null && lastItem.getText().equals("More Windows...")) { hasMoreWin = true; maxWin++; } if (!hasMoreWin && count - 4 == 5) { windowMenu.add(item = new JMenuItem("More Windows...", 'M')); item.setActionCommand("More Windows..."); item.addActionListener(this); return; } else if (count - 4 <= maxWin) { if (hasMoreWin) { count--; windowMenu.remove(lastItem); } String shortName = SwingGui.getShortName(url); windowMenu.add(item = new JMenuItem((char)('0' + (count-4)) + " " + shortName, '0' + (count - 4))); if (hasMoreWin) { windowMenu.add(lastItem); } } else { return; } item.setActionCommand(url); item.addActionListener(this); } /** * Updates the enabledness of menu items. */ public void updateEnabled(boolean interrupted) { for (int i = 0; i != interruptOnlyItems.size(); ++i) { JMenuItem item = interruptOnlyItems.get(i); item.setEnabled(interrupted); } for (int i = 0; i != runOnlyItems.size(); ++i) { JMenuItem item = runOnlyItems.get(i); item.setEnabled(!interrupted); } } } /** * Class to consolidate all cases that require to implement Runnable * to avoid class generation bloat. */ class RunProxy implements Runnable { // Constants for 'type'. static final int OPEN_FILE = 1; static final int LOAD_FILE = 2; static final int UPDATE_SOURCE_TEXT = 3; static final int ENTER_INTERRUPT = 4; /** * The debugger GUI. */ private SwingGui debugGui; /** * The type of Runnable this object is. Takes one of the constants * defined in this class. */ private int type; /** * The name of the file to open or load. */ String fileName; /** * The source text to update. */ String text; /** * The source for which to update the text. */ Dim.SourceInfo sourceInfo; /** * The frame to interrupt in. */ Dim.StackFrame lastFrame; /** * The name of the interrupted thread. */ String threadTitle; /** * The message of the exception thrown that caused the thread * interruption, if any. */ String alertMessage; /** * Creates a new RunProxy. */ public RunProxy(SwingGui debugGui, int type) { this.debugGui = debugGui; this.type = type; } /** * Runs this Runnable. */ public void run() { switch (type) { case OPEN_FILE: try { debugGui.dim.compileScript(fileName, text); } catch (RuntimeException ex) { MessageDialogWrapper.showMessageDialog( debugGui, ex.getMessage(), "Error Compiling "+fileName, JOptionPane.ERROR_MESSAGE); } break; case LOAD_FILE: try { debugGui.dim.evalScript(fileName, text); } catch (RuntimeException ex) { MessageDialogWrapper.showMessageDialog( debugGui, ex.getMessage(), "Run error for "+fileName, JOptionPane.ERROR_MESSAGE); } break; case UPDATE_SOURCE_TEXT: { String fileName = sourceInfo.url(); if (!debugGui.updateFileWindow(sourceInfo) && !fileName.equals("")) { debugGui.createFileWindow(sourceInfo, -1); } } break; case ENTER_INTERRUPT: debugGui.enterInterruptImpl(lastFrame, threadTitle, alertMessage); break; default: throw new IllegalArgumentException(String.valueOf(type)); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/Main.java0000644000175000017500000002744311314263504035466 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino JavaScript Debugger code, released * November 21, 2000. * * The Initial Developer of the Original Code is * SeeBeyond Corporation. * Portions created by the Initial Developer are Copyright (C) 2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Matt Gould * Christopher Oliver * Cameron McCormack * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.debugger; import java.io.InputStream; import java.io.PrintStream; import javax.swing.JFrame; import org.mozilla.javascript.*; import org.mozilla.javascript.tools.shell.Global; /** * Rhino script debugger main class. This class links together a * debugger object ({@link Dim}) and a debugger GUI object ({@link SwingGui}). */ public class Main { /** * The debugger. */ private Dim dim; /** * The debugger frame. */ private SwingGui debugGui; /** * Creates a new Main. */ public Main(String title) { dim = new Dim(); debugGui = new SwingGui(dim, title); } /** * Returns the debugger window {@link JFrame}. */ public JFrame getDebugFrame() { return debugGui; } /** * Breaks execution of the script. */ public void doBreak() { dim.setBreak(); } /** * Sets whether execution should break when a script exception is thrown. */ public void setBreakOnExceptions(boolean value) { dim.setBreakOnExceptions(value); debugGui.getMenubar().getBreakOnExceptions().setSelected(value); } /** * Sets whether execution should break when a function is entered. */ public void setBreakOnEnter(boolean value) { dim.setBreakOnEnter(value); debugGui.getMenubar().getBreakOnEnter().setSelected(value); } /** * Sets whether execution should break when a function is left. */ public void setBreakOnReturn(boolean value) { dim.setBreakOnReturn(value); debugGui.getMenubar().getBreakOnReturn().setSelected(value); } /** * Removes all breakpoints. */ public void clearAllBreakpoints() { dim.clearAllBreakpoints(); } /** * Resumes execution of the script. */ public void go() { dim.go(); } /** * Sets the scope to be used for script evaluation. */ public void setScope(Scriptable scope) { setScopeProvider(IProxy.newScopeProvider(scope)); } /** * Sets the {@link ScopeProvider} that provides a scope to be used * for script evaluation. */ public void setScopeProvider(ScopeProvider p) { dim.setScopeProvider(p); } /** * Assign a Runnable object that will be invoked when the user * selects "Exit..." or closes the Debugger main window. */ public void setExitAction(Runnable r) { debugGui.setExitAction(r); } /** * Returns an {@link InputStream} for stdin from the debugger's internal * Console window. */ public InputStream getIn() { return debugGui.getConsole().getIn(); } /** * Returns a {@link PrintStream} for stdout to the debugger's internal * Console window. */ public PrintStream getOut() { return debugGui.getConsole().getOut(); } /** * Returns a {@link PrintStream} for stderr in the Debugger's internal * Console window. */ public PrintStream getErr() { return debugGui.getConsole().getErr(); } /** * Packs the debugger GUI frame. */ public void pack() { debugGui.pack(); } /** * Sets the debugger GUI frame dimensions. */ public void setSize(int w, int h) { debugGui.setSize(w, h); } /** * Sets the visibility of the debugger GUI frame. */ public void setVisible(boolean flag) { debugGui.setVisible(flag); } /** * Returns whether the debugger GUI frame is visible. */ public boolean isVisible() { return debugGui.isVisible(); } /** * Frees any resources held by the debugger. */ public void dispose() { clearAllBreakpoints(); dim.go(); debugGui.dispose(); dim = null; } /** * Attaches the debugger to the given {@link ContextFactory}. */ public void attachTo(ContextFactory factory) { dim.attachTo(factory); } /** * Detaches from the current {@link ContextFactory}. */ public void detach() { dim.detach(); } /** * Main entry point. Creates a debugger attached to a Rhino * {@link org.mozilla.javascript.tools.shell.Main} shell session. */ public static void main(String[] args) { Main main = new Main("Rhino JavaScript Debugger"); main.doBreak(); main.setExitAction(new IProxy(IProxy.EXIT_ACTION)); System.setIn(main.getIn()); System.setOut(main.getOut()); System.setErr(main.getErr()); Global global = org.mozilla.javascript.tools.shell.Main.getGlobal(); global.setIn(main.getIn()); global.setOut(main.getOut()); global.setErr(main.getErr()); main.attachTo( org.mozilla.javascript.tools.shell.Main.shellContextFactory); main.setScope(global); main.pack(); main.setSize(600, 460); main.setVisible(true); org.mozilla.javascript.tools.shell.Main.exec(args); } /** * Entry point for embedded applications. This method attaches * to the global {@link ContextFactory} with a scope of a newly * created {@link Global} object. No I/O redirection is performed * as with {@link #main(String[])}. */ public static void mainEmbedded(String title) { ContextFactory factory = ContextFactory.getGlobal(); Global global = new Global(); global.init(factory); mainEmbedded(factory, global, title); } /** * Entry point for embedded applications. This method attaches * to the given {@link ContextFactory} with the given scope. No * I/O redirection is performed as with {@link #main(String[])}. */ public static void mainEmbedded(ContextFactory factory, Scriptable scope, String title) { mainEmbeddedImpl(factory, scope, title); } /** * Entry point for embedded applications. This method attaches * to the given {@link ContextFactory} with the given scope. No * I/O redirection is performed as with {@link #main(String[])}. */ public static void mainEmbedded(ContextFactory factory, ScopeProvider scopeProvider, String title) { mainEmbeddedImpl(factory, scopeProvider, title); } /** * Helper method for {@link #mainEmbedded(String)}, etc. */ private static void mainEmbeddedImpl(ContextFactory factory, Object scopeProvider, String title) { if (title == null) { title = "Rhino JavaScript Debugger (embedded usage)"; } Main main = new Main(title); main.doBreak(); main.setExitAction(new IProxy(IProxy.EXIT_ACTION)); main.attachTo(factory); if (scopeProvider instanceof ScopeProvider) { main.setScopeProvider((ScopeProvider)scopeProvider); } else { Scriptable scope = (Scriptable)scopeProvider; if (scope instanceof Global) { Global global = (Global)scope; global.setIn(main.getIn()); global.setOut(main.getOut()); global.setErr(main.getErr()); } main.setScope(scope); } main.pack(); main.setSize(600, 460); main.setVisible(true); } // Deprecated methods /** * @deprecated Use {@link #setSize(int, int)} instead. */ public void setSize(java.awt.Dimension dimension) { debugGui.setSize(dimension.width, dimension.height); } /** * @deprecated * The method does nothing and is only present for compatibility. */ public void setOptimizationLevel(int level) { } /** * @deprecated * The method is only present for compatibility and should not be called. */ public void contextEntered(Context cx) { throw new IllegalStateException(); } /** * @deprecated * The method is only present for compatibility and should not be called. */ public void contextExited(Context cx) { throw new IllegalStateException(); } /** * @deprecated * The method is only present for compatibility and should not be called. */ public void contextCreated(Context cx) { throw new IllegalStateException(); } /** * @deprecated * The method is only present for compatibility and should not be called. */ public void contextReleased(Context cx) { throw new IllegalStateException(); } /** * Class to consolidate all internal implementations of interfaces * to avoid class generation bloat. */ private static class IProxy implements Runnable, ScopeProvider { // Constants for 'type'. public static final int EXIT_ACTION = 1; public static final int SCOPE_PROVIDER = 2; /** * The type of interface. */ private final int type; /** * The scope object to expose when {@link #type} = * {@link #SCOPE_PROVIDER}. */ private Scriptable scope; /** * Creates a new IProxy. */ public IProxy(int type) { this.type = type; } /** * Creates a new IProxy that acts as a {@link ScopeProvider}. */ public static ScopeProvider newScopeProvider(Scriptable scope) { IProxy scopeProvider = new IProxy(SCOPE_PROVIDER); scopeProvider.scope = scope; return scopeProvider; } // ContextAction /** * Exit action. */ public void run() { if (type != EXIT_ACTION) Kit.codeBug(); System.exit(0); } // ScopeProvider /** * Returns the scope for script evaluations. */ public Scriptable getScope() { if (type != SCOPE_PROVIDER) Kit.codeBug(); if (scope == null) Kit.codeBug(); return scope; } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/debugger/Dim.java0000644000175000017500000013650111314263504035307 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino JavaScript Debugger code, released * November 21, 2000. * * The Initial Developer of the Original Code is * SeeBeyond Corporation. * Portions created by the Initial Developer are Copyright (C) 2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Matt Gould * Christopher Oliver * Cameron McCormack * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.debugger; import org.mozilla.javascript.*; import org.mozilla.javascript.debug.*; import java.util.*; import java.io.*; import java.net.URL; /** * Dim or Debugger Implementation for Rhino. */ public class Dim { // Constants for instructing the debugger what action to perform // to end interruption. Used by 'returnValue'. public static final int STEP_OVER = 0; public static final int STEP_INTO = 1; public static final int STEP_OUT = 2; public static final int GO = 3; public static final int BREAK = 4; public static final int EXIT = 5; // Constants for the DimIProxy interface implementation class. private static final int IPROXY_DEBUG = 0; private static final int IPROXY_LISTEN = 1; private static final int IPROXY_COMPILE_SCRIPT = 2; private static final int IPROXY_EVAL_SCRIPT = 3; private static final int IPROXY_STRING_IS_COMPILABLE = 4; private static final int IPROXY_OBJECT_TO_STRING = 5; private static final int IPROXY_OBJECT_PROPERTY = 6; private static final int IPROXY_OBJECT_IDS = 7; /** * Interface to the debugger GUI. */ private GuiCallback callback; /** * Whether the debugger should break. */ private boolean breakFlag; /** * The ScopeProvider object that provides the scope in which to * evaluate script. */ private ScopeProvider scopeProvider; /** * The index of the current stack frame. */ private int frameIndex = -1; /** * Information about the current stack at the point of interruption. */ private volatile ContextData interruptedContextData; /** * The ContextFactory to listen to for debugging information. */ private ContextFactory contextFactory; /** * Synchronization object used to allow script evaluations to * happen when a thread is resumed. */ private Object monitor = new Object(); /** * Synchronization object used to wait for valid * {@link #interruptedContextData}. */ private Object eventThreadMonitor = new Object(); /** * The action to perform to end the interruption loop. */ private volatile int returnValue = -1; /** * Whether the debugger is inside the interruption loop. */ private boolean insideInterruptLoop; /** * The requested script string to be evaluated when the thread * has been resumed. */ private String evalRequest; /** * The stack frame in which to evaluate {@link #evalRequest}. */ private StackFrame evalFrame; /** * The result of evaluating {@link #evalRequest}. */ private String evalResult; /** * Whether the debugger should break when a script exception is thrown. */ private boolean breakOnExceptions; /** * Whether the debugger should break when a script function is entered. */ private boolean breakOnEnter; /** * Whether the debugger should break when a script function is returned * from. */ private boolean breakOnReturn; /** * Table mapping URLs to information about the script source. */ private final Map urlToSourceInfo = Collections.synchronizedMap(new HashMap()); /** * Table mapping function names to information about the function. */ private final Map functionNames = Collections.synchronizedMap(new HashMap()); /** * Table mapping functions to information about the function. */ private final Map functionToSource = Collections.synchronizedMap(new HashMap()); /** * ContextFactory.Listener instance attached to {@link #contextFactory}. */ private DimIProxy listener; /** * Sets the GuiCallback object to use. */ public void setGuiCallback(GuiCallback callback) { this.callback = callback; } /** * Tells the debugger to break at the next opportunity. */ public void setBreak() { this.breakFlag = true; } /** * Sets the ScopeProvider to be used. */ public void setScopeProvider(ScopeProvider scopeProvider) { this.scopeProvider = scopeProvider; } /** * Switches context to the stack frame with the given index. */ public void contextSwitch(int frameIndex) { this.frameIndex = frameIndex; } /** * Sets whether the debugger should break on exceptions. */ public void setBreakOnExceptions(boolean breakOnExceptions) { this.breakOnExceptions = breakOnExceptions; } /** * Sets whether the debugger should break on function entering. */ public void setBreakOnEnter(boolean breakOnEnter) { this.breakOnEnter = breakOnEnter; } /** * Sets whether the debugger should break on function return. */ public void setBreakOnReturn(boolean breakOnReturn) { this.breakOnReturn = breakOnReturn; } /** * Attaches the debugger to the given ContextFactory. */ public void attachTo(ContextFactory factory) { detach(); this.contextFactory = factory; this.listener = new DimIProxy(this, IPROXY_LISTEN); factory.addListener(this.listener); } /** * Detaches the debugger from the current ContextFactory. */ public void detach() { if (listener != null) { contextFactory.removeListener(listener); contextFactory = null; listener = null; } } /** * Releases resources associated with this debugger. */ public void dispose() { detach(); } /** * Returns the FunctionSource object for the given script or function. */ private FunctionSource getFunctionSource(DebuggableScript fnOrScript) { FunctionSource fsource = functionSource(fnOrScript); if (fsource == null) { String url = getNormalizedUrl(fnOrScript); SourceInfo si = sourceInfo(url); if (si == null) { if (!fnOrScript.isGeneratedScript()) { // Not eval or Function, try to load it from URL String source = loadSource(url); if (source != null) { DebuggableScript top = fnOrScript; for (;;) { DebuggableScript parent = top.getParent(); if (parent == null) { break; } top = parent; } registerTopScript(top, source); fsource = functionSource(fnOrScript); } } } } return fsource; } /** * Loads the script at the given URL. */ private String loadSource(String sourceUrl) { String source = null; int hash = sourceUrl.indexOf('#'); if (hash >= 0) { sourceUrl = sourceUrl.substring(0, hash); } try { InputStream is; openStream: { if (sourceUrl.indexOf(':') < 0) { // Can be a file name try { if (sourceUrl.startsWith("~/")) { String home = SecurityUtilities.getSystemProperty("user.home"); if (home != null) { String pathFromHome = sourceUrl.substring(2); File f = new File(new File(home), pathFromHome); if (f.exists()) { is = new FileInputStream(f); break openStream; } } } File f = new File(sourceUrl); if (f.exists()) { is = new FileInputStream(f); break openStream; } } catch (SecurityException ex) { } // No existing file, assume missed http:// if (sourceUrl.startsWith("//")) { sourceUrl = "http:" + sourceUrl; } else if (sourceUrl.startsWith("/")) { sourceUrl = "http://127.0.0.1" + sourceUrl; } else { sourceUrl = "http://" + sourceUrl; } } is = (new URL(sourceUrl)).openStream(); } try { source = Kit.readReader(new InputStreamReader(is)); } finally { is.close(); } } catch (IOException ex) { System.err.println ("Failed to load source from "+sourceUrl+": "+ ex); } return source; } /** * Registers the given script as a top-level script in the debugger. */ private void registerTopScript(DebuggableScript topScript, String source) { if (!topScript.isTopLevel()) { throw new IllegalArgumentException(); } String url = getNormalizedUrl(topScript); DebuggableScript[] functions = getAllFunctions(topScript); final SourceInfo sourceInfo = new SourceInfo(source, functions, url); synchronized (urlToSourceInfo) { SourceInfo old = urlToSourceInfo.get(url); if (old != null) { sourceInfo.copyBreakpointsFrom(old); } urlToSourceInfo.put(url, sourceInfo); for (int i = 0; i != sourceInfo.functionSourcesTop(); ++i) { FunctionSource fsource = sourceInfo.functionSource(i); String name = fsource.name(); if (name.length() != 0) { functionNames.put(name, fsource); } } } synchronized (functionToSource) { for (int i = 0; i != functions.length; ++i) { FunctionSource fsource = sourceInfo.functionSource(i); functionToSource.put(functions[i], fsource); } } callback.updateSourceText(sourceInfo); } /** * Returns the FunctionSource object for the given function or script. */ private FunctionSource functionSource(DebuggableScript fnOrScript) { return functionToSource.get(fnOrScript); } /** * Returns an array of all function names. */ public String[] functionNames() { synchronized (urlToSourceInfo) { return functionNames.keySet().toArray(new String[functionNames.size()]); } } /** * Returns the FunctionSource object for the function with the given name. */ public FunctionSource functionSourceByName(String functionName) { return functionNames.get(functionName); } /** * Returns the SourceInfo object for the given URL. */ public SourceInfo sourceInfo(String url) { return urlToSourceInfo.get(url); } /** * Returns the source URL for the given script or function. */ private String getNormalizedUrl(DebuggableScript fnOrScript) { String url = fnOrScript.getSourceName(); if (url == null) { url = ""; } else { // Not to produce window for eval from different lines, // strip line numbers, i.e. replace all #[0-9]+\(eval\) by // (eval) // Option: similar teatment for Function? char evalSeparator = '#'; StringBuffer sb = null; int urlLength = url.length(); int cursor = 0; for (;;) { int searchStart = url.indexOf(evalSeparator, cursor); if (searchStart < 0) { break; } String replace = null; int i = searchStart + 1; while (i != urlLength) { int c = url.charAt(i); if (!('0' <= c && c <= '9')) { break; } ++i; } if (i != searchStart + 1) { // i points after #[0-9]+ if ("(eval)".regionMatches(0, url, i, 6)) { cursor = i + 6; replace = "(eval)"; } } if (replace == null) { break; } if (sb == null) { sb = new StringBuffer(); sb.append(url.substring(0, searchStart)); } sb.append(replace); } if (sb != null) { if (cursor != urlLength) { sb.append(url.substring(cursor)); } url = sb.toString(); } } return url; } /** * Returns an array of all functions in the given script. */ private static DebuggableScript[] getAllFunctions (DebuggableScript function) { ObjArray functions = new ObjArray(); collectFunctions_r(function, functions); DebuggableScript[] result = new DebuggableScript[functions.size()]; functions.toArray(result); return result; } /** * Helper function for {@link #getAllFunctions(DebuggableScript)}. */ private static void collectFunctions_r(DebuggableScript function, ObjArray array) { array.add(function); for (int i = 0; i != function.getFunctionCount(); ++i) { collectFunctions_r(function.getFunction(i), array); } } /** * Clears all breakpoints. */ public void clearAllBreakpoints() { for (SourceInfo si: urlToSourceInfo.values()) { si.removeAllBreakpoints(); } } /** * Called when a breakpoint has been hit. */ private void handleBreakpointHit(StackFrame frame, Context cx) { breakFlag = false; interrupted(cx, frame, null); } /** * Called when a script exception has been thrown. */ private void handleExceptionThrown(Context cx, Throwable ex, StackFrame frame) { if (breakOnExceptions) { ContextData cd = frame.contextData(); if (cd.lastProcessedException != ex) { interrupted(cx, frame, ex); cd.lastProcessedException = ex; } } } /** * Returns the current ContextData object. */ public ContextData currentContextData() { return interruptedContextData; } /** * Sets the action to perform to end interruption. */ public void setReturnValue(int returnValue) { synchronized (monitor) { this.returnValue = returnValue; monitor.notify(); } } /** * Resumes execution of script. */ public void go() { synchronized (monitor) { this.returnValue = GO; monitor.notifyAll(); } } /** * Evaluates the given script. */ public String eval(String expr) { String result = "undefined"; if (expr == null) { return result; } ContextData contextData = currentContextData(); if (contextData == null || frameIndex >= contextData.frameCount()) { return result; } StackFrame frame = contextData.getFrame(frameIndex); if (contextData.eventThreadFlag) { Context cx = Context.getCurrentContext(); result = do_eval(cx, frame, expr); } else { synchronized (monitor) { if (insideInterruptLoop) { evalRequest = expr; evalFrame = frame; monitor.notify(); do { try { monitor.wait(); } catch (InterruptedException exc) { Thread.currentThread().interrupt(); break; } } while (evalRequest != null); result = evalResult; } } } return result; } /** * Compiles the given script. */ public void compileScript(String url, String text) { DimIProxy action = new DimIProxy(this, IPROXY_COMPILE_SCRIPT); action.url = url; action.text = text; action.withContext(); } /** * Evaluates the given script. */ public void evalScript(final String url, final String text) { DimIProxy action = new DimIProxy(this, IPROXY_EVAL_SCRIPT); action.url = url; action.text = text; action.withContext(); } /** * Converts the given script object to a string. */ public String objectToString(Object object) { DimIProxy action = new DimIProxy(this, IPROXY_OBJECT_TO_STRING); action.object = object; action.withContext(); return action.stringResult; } /** * Returns whether the given string is syntactically valid script. */ public boolean stringIsCompilableUnit(String str) { DimIProxy action = new DimIProxy(this, IPROXY_STRING_IS_COMPILABLE); action.text = str; action.withContext(); return action.booleanResult; } /** * Returns the value of a property on the given script object. */ public Object getObjectProperty(Object object, Object id) { DimIProxy action = new DimIProxy(this, IPROXY_OBJECT_PROPERTY); action.object = object; action.id = id; action.withContext(); return action.objectResult; } /** * Returns an array of the property names on the given script object. */ public Object[] getObjectIds(Object object) { DimIProxy action = new DimIProxy(this, IPROXY_OBJECT_IDS); action.object = object; action.withContext(); return action.objectArrayResult; } /** * Returns the value of a property on the given script object. */ private Object getObjectPropertyImpl(Context cx, Object object, Object id) { Scriptable scriptable = (Scriptable)object; Object result; if (id instanceof String) { String name = (String)id; if (name.equals("this")) { result = scriptable; } else if (name.equals("__proto__")) { result = scriptable.getPrototype(); } else if (name.equals("__parent__")) { result = scriptable.getParentScope(); } else { result = ScriptableObject.getProperty(scriptable, name); if (result == ScriptableObject.NOT_FOUND) { result = Undefined.instance; } } } else { int index = ((Integer)id).intValue(); result = ScriptableObject.getProperty(scriptable, index); if (result == ScriptableObject.NOT_FOUND) { result = Undefined.instance; } } return result; } /** * Returns an array of the property names on the given script object. */ private Object[] getObjectIdsImpl(Context cx, Object object) { if (!(object instanceof Scriptable) || object == Undefined.instance) { return Context.emptyArgs; } Object[] ids; Scriptable scriptable = (Scriptable)object; if (scriptable instanceof DebuggableObject) { ids = ((DebuggableObject)scriptable).getAllIds(); } else { ids = scriptable.getIds(); } Scriptable proto = scriptable.getPrototype(); Scriptable parent = scriptable.getParentScope(); int extra = 0; if (proto != null) { ++extra; } if (parent != null) { ++extra; } if (extra != 0) { Object[] tmp = new Object[extra + ids.length]; System.arraycopy(ids, 0, tmp, extra, ids.length); ids = tmp; extra = 0; if (proto != null) { ids[extra++] = "__proto__"; } if (parent != null) { ids[extra++] = "__parent__"; } } return ids; } /** * Interrupts script execution. */ private void interrupted(Context cx, final StackFrame frame, Throwable scriptException) { ContextData contextData = frame.contextData(); boolean eventThreadFlag = callback.isGuiEventThread(); contextData.eventThreadFlag = eventThreadFlag; boolean recursiveEventThreadCall = false; interruptedCheck: synchronized (eventThreadMonitor) { if (eventThreadFlag) { if (interruptedContextData != null) { recursiveEventThreadCall = true; break interruptedCheck; } } else { while (interruptedContextData != null) { try { eventThreadMonitor.wait(); } catch (InterruptedException exc) { return; } } } interruptedContextData = contextData; } if (recursiveEventThreadCall) { // XXX: For now the following is commented out as on Linux // too deep recursion of dispatchNextGuiEvent causes GUI lockout. // Note: it can make GUI unresponsive if long-running script // will be called on GUI thread while processing another interrupt if (false) { // Run event dispatch until gui sets a flag to exit the initial // call to interrupted. while (this.returnValue == -1) { try { callback.dispatchNextGuiEvent(); } catch (InterruptedException exc) { } } } return; } if (interruptedContextData == null) Kit.codeBug(); try { do { int frameCount = contextData.frameCount(); this.frameIndex = frameCount -1; final String threadTitle = Thread.currentThread().toString(); final String alertMessage; if (scriptException == null) { alertMessage = null; } else { alertMessage = scriptException.toString(); } int returnValue = -1; if (!eventThreadFlag) { synchronized (monitor) { if (insideInterruptLoop) Kit.codeBug(); this.insideInterruptLoop = true; this.evalRequest = null; this.returnValue = -1; callback.enterInterrupt(frame, threadTitle, alertMessage); try { for (;;) { try { monitor.wait(); } catch (InterruptedException exc) { Thread.currentThread().interrupt(); break; } if (evalRequest != null) { this.evalResult = null; try { evalResult = do_eval(cx, evalFrame, evalRequest); } finally { evalRequest = null; evalFrame = null; monitor.notify(); } continue; } if (this.returnValue != -1) { returnValue = this.returnValue; break; } } } finally { insideInterruptLoop = false; } } } else { this.returnValue = -1; callback.enterInterrupt(frame, threadTitle, alertMessage); while (this.returnValue == -1) { try { callback.dispatchNextGuiEvent(); } catch (InterruptedException exc) { } } returnValue = this.returnValue; } switch (returnValue) { case STEP_OVER: contextData.breakNextLine = true; contextData.stopAtFrameDepth = contextData.frameCount(); break; case STEP_INTO: contextData.breakNextLine = true; contextData.stopAtFrameDepth = -1; break; case STEP_OUT: if (contextData.frameCount() > 1) { contextData.breakNextLine = true; contextData.stopAtFrameDepth = contextData.frameCount() -1; } break; } } while (false); } finally { synchronized (eventThreadMonitor) { interruptedContextData = null; eventThreadMonitor.notifyAll(); } } } /** * Evaluates script in the given stack frame. */ private static String do_eval(Context cx, StackFrame frame, String expr) { String resultString; Debugger saved_debugger = cx.getDebugger(); Object saved_data = cx.getDebuggerContextData(); int saved_level = cx.getOptimizationLevel(); cx.setDebugger(null, null); cx.setOptimizationLevel(-1); cx.setGeneratingDebug(false); try { Callable script = (Callable)cx.compileString(expr, "", 0, null); Object result = script.call(cx, frame.scope, frame.thisObj, ScriptRuntime.emptyArgs); if (result == Undefined.instance) { resultString = ""; } else { resultString = ScriptRuntime.toString(result); } } catch (Exception exc) { resultString = exc.getMessage(); } finally { cx.setGeneratingDebug(true); cx.setOptimizationLevel(saved_level); cx.setDebugger(saved_debugger, saved_data); } if (resultString == null) { resultString = "null"; } return resultString; } /** * Proxy class to implement debug interfaces without bloat of class * files. */ private static class DimIProxy implements ContextAction, ContextFactory.Listener, Debugger { /** * The debugger. */ private Dim dim; /** * The interface implementation type. One of the IPROXY_* constants * defined in {@link Dim}. */ private int type; /** * The URL origin of the script to compile or evaluate. */ private String url; /** * The text of the script to compile, evaluate or test for compilation. */ private String text; /** * The object to convert, get a property from or enumerate. */ private Object object; /** * The property to look up in {@link #object}. */ private Object id; /** * The boolean result of the action. */ private boolean booleanResult; /** * The String result of the action. */ private String stringResult; /** * The Object result of the action. */ private Object objectResult; /** * The Object[] result of the action. */ private Object[] objectArrayResult; /** * Creates a new DimIProxy. */ private DimIProxy(Dim dim, int type) { this.dim = dim; this.type = type; } // ContextAction /** * Performs the action given by {@link #type}. */ public Object run(Context cx) { switch (type) { case IPROXY_COMPILE_SCRIPT: cx.compileString(text, url, 1, null); break; case IPROXY_EVAL_SCRIPT: { Scriptable scope = null; if (dim.scopeProvider != null) { scope = dim.scopeProvider.getScope(); } if (scope == null) { scope = new ImporterTopLevel(cx); } cx.evaluateString(scope, text, url, 1, null); } break; case IPROXY_STRING_IS_COMPILABLE: booleanResult = cx.stringIsCompilableUnit(text); break; case IPROXY_OBJECT_TO_STRING: if (object == Undefined.instance) { stringResult = "undefined"; } else if (object == null) { stringResult = "null"; } else if (object instanceof NativeCall) { stringResult = "[object Call]"; } else { stringResult = Context.toString(object); } break; case IPROXY_OBJECT_PROPERTY: objectResult = dim.getObjectPropertyImpl(cx, object, id); break; case IPROXY_OBJECT_IDS: objectArrayResult = dim.getObjectIdsImpl(cx, object); break; default: throw Kit.codeBug(); } return null; } /** * Performs the action given by {@link #type} with the attached * {@link ContextFactory}. */ private void withContext() { dim.contextFactory.call(this); } // ContextFactory.Listener /** * Called when a Context is created. */ public void contextCreated(Context cx) { if (type != IPROXY_LISTEN) Kit.codeBug(); ContextData contextData = new ContextData(); Debugger debugger = new DimIProxy(dim, IPROXY_DEBUG); cx.setDebugger(debugger, contextData); cx.setGeneratingDebug(true); cx.setOptimizationLevel(-1); } /** * Called when a Context is destroyed. */ public void contextReleased(Context cx) { if (type != IPROXY_LISTEN) Kit.codeBug(); } // Debugger /** * Returns a StackFrame for the given function or script. */ public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript) { if (type != IPROXY_DEBUG) Kit.codeBug(); FunctionSource item = dim.getFunctionSource(fnOrScript); if (item == null) { // Can not debug if source is not available return null; } return new StackFrame(cx, dim, item); } /** * Called when compilation is finished. */ public void handleCompilationDone(Context cx, DebuggableScript fnOrScript, String source) { if (type != IPROXY_DEBUG) Kit.codeBug(); if (!fnOrScript.isTopLevel()) { return; } dim.registerTopScript(fnOrScript, source); } } /** * Class to store information about a stack. */ public static class ContextData { /** * The stack frames. */ private ObjArray frameStack = new ObjArray(); /** * Whether the debugger should break at the next line in this context. */ private boolean breakNextLine; /** * The frame depth the debugger should stop at. Used to implement * "step over" and "step out". */ private int stopAtFrameDepth = -1; /** * Whether this context is in the event thread. */ private boolean eventThreadFlag; /** * The last exception that was processed. */ private Throwable lastProcessedException; /** * Returns the ContextData for the given Context. */ public static ContextData get(Context cx) { return (ContextData) cx.getDebuggerContextData(); } /** * Returns the number of stack frames. */ public int frameCount() { return frameStack.size(); } /** * Returns the stack frame with the given index. */ public StackFrame getFrame(int frameNumber) { int num = frameStack.size() - frameNumber - 1; return (StackFrame) frameStack.get(num); } /** * Pushes a stack frame on to the stack. */ private void pushFrame(StackFrame frame) { frameStack.push(frame); } /** * Pops a stack frame from the stack. */ private void popFrame() { frameStack.pop(); } } /** * Object to represent one stack frame. */ public static class StackFrame implements DebugFrame { /** * The debugger. */ private Dim dim; /** * The ContextData for the Context being debugged. */ private ContextData contextData; /** * The scope. */ private Scriptable scope; /** * The 'this' object. */ private Scriptable thisObj; /** * Information about the function. */ private FunctionSource fsource; /** * Array of breakpoint state for each source line. */ private boolean[] breakpoints; /** * Current line number. */ private int lineNumber; /** * Creates a new StackFrame. */ private StackFrame(Context cx, Dim dim, FunctionSource fsource) { this.dim = dim; this.contextData = ContextData.get(cx); this.fsource = fsource; this.breakpoints = fsource.sourceInfo().breakpoints; this.lineNumber = fsource.firstLine(); } /** * Called when the stack frame is entered. */ public void onEnter(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { contextData.pushFrame(this); this.scope = scope; this.thisObj = thisObj; if (dim.breakOnEnter) { dim.handleBreakpointHit(this, cx); } } /** * Called when the current position has changed. */ public void onLineChange(Context cx, int lineno) { this.lineNumber = lineno; if (!breakpoints[lineno] && !dim.breakFlag) { boolean lineBreak = contextData.breakNextLine; if (lineBreak && contextData.stopAtFrameDepth >= 0) { lineBreak = (contextData.frameCount() <= contextData.stopAtFrameDepth); } if (!lineBreak) { return; } contextData.stopAtFrameDepth = -1; contextData.breakNextLine = false; } dim.handleBreakpointHit(this, cx); } /** * Called when an exception has been thrown. */ public void onExceptionThrown(Context cx, Throwable exception) { dim.handleExceptionThrown(cx, exception, this); } /** * Called when the stack frame has been left. */ public void onExit(Context cx, boolean byThrow, Object resultOrException) { if (dim.breakOnReturn && !byThrow) { dim.handleBreakpointHit(this, cx); } contextData.popFrame(); } /** * Called when a 'debugger' statement is executed. */ public void onDebuggerStatement(Context cx) { dim.handleBreakpointHit(this, cx); } /** * Returns the SourceInfo object for the function. */ public SourceInfo sourceInfo() { return fsource.sourceInfo(); } /** * Returns the ContextData object for the Context. */ public ContextData contextData() { return contextData; } /** * Returns the scope object for this frame. */ public Object scope() { return scope; } /** * Returns the 'this' object for this frame. */ public Object thisObj() { return thisObj; } /** * Returns the source URL. */ public String getUrl() { return fsource.sourceInfo().url(); } /** * Returns the current line number. */ public int getLineNumber() { return lineNumber; } } /** * Class to store information about a function. */ public static class FunctionSource { /** * Information about the source of the function. */ private SourceInfo sourceInfo; /** * Line number of the first line of the function. */ private int firstLine; /** * The function name. */ private String name; /** * Creates a new FunctionSource. */ private FunctionSource(SourceInfo sourceInfo, int firstLine, String name) { if (name == null) throw new IllegalArgumentException(); this.sourceInfo = sourceInfo; this.firstLine = firstLine; this.name = name; } /** * Returns the SourceInfo object that describes the source of the * function. */ public SourceInfo sourceInfo() { return sourceInfo; } /** * Returns the line number of the first line of the function. */ public int firstLine() { return firstLine; } /** * Returns the name of the function. */ public String name() { return name; } } /** * Class to store information about a script source. */ public static class SourceInfo { /** * An empty array of booleans. */ private static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; /** * The script. */ private String source; /** * The URL of the script. */ private String url; /** * Array indicating which lines can have breakpoints set. */ private boolean[] breakableLines; /** * Array indicating whether a breakpoint is set on the line. */ private boolean[] breakpoints; /** * Array of FunctionSource objects for the functions in the script. */ private FunctionSource[] functionSources; /** * Creates a new SourceInfo object. */ private SourceInfo(String source, DebuggableScript[] functions, String normilizedUrl) { this.source = source; this.url = normilizedUrl; int N = functions.length; int[][] lineArrays = new int[N][]; for (int i = 0; i != N; ++i) { lineArrays[i] = functions[i].getLineNumbers(); } int minAll = 0, maxAll = -1; int[] firstLines = new int[N]; for (int i = 0; i != N; ++i) { int[] lines = lineArrays[i]; if (lines == null || lines.length == 0) { firstLines[i] = -1; } else { int min, max; min = max = lines[0]; for (int j = 1; j != lines.length; ++j) { int line = lines[j]; if (line < min) { min = line; } else if (line > max) { max = line; } } firstLines[i] = min; if (minAll > maxAll) { minAll = min; maxAll = max; } else { if (min < minAll) { minAll = min; } if (max > maxAll) { maxAll = max; } } } } if (minAll > maxAll) { // No line information this.breakableLines = EMPTY_BOOLEAN_ARRAY; this.breakpoints = EMPTY_BOOLEAN_ARRAY; } else { if (minAll < 0) { // Line numbers can not be negative throw new IllegalStateException(String.valueOf(minAll)); } int linesTop = maxAll + 1; this.breakableLines = new boolean[linesTop]; this.breakpoints = new boolean[linesTop]; for (int i = 0; i != N; ++i) { int[] lines = lineArrays[i]; if (lines != null && lines.length != 0) { for (int j = 0; j != lines.length; ++j) { int line = lines[j]; this.breakableLines[line] = true; } } } } this.functionSources = new FunctionSource[N]; for (int i = 0; i != N; ++i) { String name = functions[i].getFunctionName(); if (name == null) { name = ""; } this.functionSources[i] = new FunctionSource(this, firstLines[i], name); } } /** * Returns the source text. */ public String source() { return this.source; } /** * Returns the script's origin URL. */ public String url() { return this.url; } /** * Returns the number of FunctionSource objects stored in this object. */ public int functionSourcesTop() { return functionSources.length; } /** * Returns the FunctionSource object with the given index. */ public FunctionSource functionSource(int i) { return functionSources[i]; } /** * Copies the breakpoints from the given SourceInfo object into this * one. */ private void copyBreakpointsFrom(SourceInfo old) { int end = old.breakpoints.length; if (end > this.breakpoints.length) { end = this.breakpoints.length; } for (int line = 0; line != end; ++line) { if (old.breakpoints[line]) { this.breakpoints[line] = true; } } } /** * Returns whether the given line number can have a breakpoint set on * it. */ public boolean breakableLine(int line) { return (line < this.breakableLines.length) && this.breakableLines[line]; } /** * Returns whether there is a breakpoint set on the given line. */ public boolean breakpoint(int line) { if (!breakableLine(line)) { throw new IllegalArgumentException(String.valueOf(line)); } return line < this.breakpoints.length && this.breakpoints[line]; } /** * Sets or clears the breakpoint flag for the given line. */ public boolean breakpoint(int line, boolean value) { if (!breakableLine(line)) { throw new IllegalArgumentException(String.valueOf(line)); } boolean changed; synchronized (breakpoints) { if (breakpoints[line] != value) { breakpoints[line] = value; changed = true; } else { changed = false; } } return changed; } /** * Removes all breakpoints from the script. */ public void removeAllBreakpoints() { synchronized (breakpoints) { for (int line = 0; line != breakpoints.length; ++line) { breakpoints[line] = false; } } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/jsc/0000755000175000017500000000000011537630013032720 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/jsc/Main.java0000644000175000017500000003311311314263504034450 0ustar jamespagejamespage00000000000000/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Christine Begle * Norris Boyd * Roger Lawrence * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.jsc; import java.io.*; import java.util.*; import org.mozilla.javascript.*; import org.mozilla.javascript.optimizer.ClassCompiler; import org.mozilla.javascript.tools.SourceReader; import org.mozilla.javascript.tools.ToolErrorReporter; /** * @author Norris Boyd */ public class Main { /** * Main entry point. * * Process arguments as would a normal Java program. * Then set up the execution environment and begin to * compile scripts. */ public static void main(String args[]) { Main main = new Main(); args = main.processOptions(args); if (args == null) { if (main.printHelp) { System.out.println(ToolErrorReporter.getMessage( "msg.jsc.usage", Main.class.getName())); System.exit(0); } System.exit(1); } if (!main.reporter.hasReportedError()) { main.processSource(args); } } public Main() { reporter = new ToolErrorReporter(true); compilerEnv = new CompilerEnvirons(); compilerEnv.setErrorReporter(reporter); compiler = new ClassCompiler(compilerEnv); } /** * Parse arguments. * */ public String[] processOptions(String args[]) { targetPackage = ""; // default to no package compilerEnv.setGenerateDebugInfo(false); // default to no symbols for (int i=0; i < args.length; i++) { String arg = args[i]; if (!arg.startsWith("-")) { int tail = args.length - i; if (targetName != null && tail > 1) { addError("msg.multiple.js.to.file", targetName); return null; } String[] result = new String[tail]; for (int j = 0; j != tail; ++j) { result[j] = args[i + j]; } return result; } if (arg.equals("-help") || arg.equals("-h") || arg.equals("--help")) { printHelp = true; return null; } try { if (arg.equals("-version") && ++i < args.length) { int version = Integer.parseInt(args[i]); compilerEnv.setLanguageVersion(version); continue; } if ((arg.equals("-opt") || arg.equals("-O")) && ++i < args.length) { int optLevel = Integer.parseInt(args[i]); compilerEnv.setOptimizationLevel(optLevel); continue; } } catch (NumberFormatException e) { badUsage(args[i]); return null; } if (arg.equals("-nosource")) { compilerEnv.setGeneratingSource(false); continue; } if (arg.equals("-debug") || arg.equals("-g")) { compilerEnv.setGenerateDebugInfo(true); continue; } if (arg.equals("-main-method-class") && ++i < args.length) { compiler.setMainMethodClass(args[i]); continue; } if (arg.equals("-encoding") && ++i < args.length) { characterEncoding = args[i]; continue; } if (arg.equals("-o") && ++i < args.length) { String name = args[i]; int end = name.length(); if (end == 0 || !Character.isJavaIdentifierStart(name.charAt(0))) { addError("msg.invalid.classfile.name", name); continue; } for (int j = 1; j < end; j++) { char c = name.charAt(j); if (!Character.isJavaIdentifierPart(c)) { if (c == '.') { // check if it is the dot in .class if (j == end - 6 && name.endsWith(".class")) { name = name.substring(0, j); break; } } addError("msg.invalid.classfile.name", name); break; } } targetName = name; continue; } if (arg.equals("-observe-instruction-count")) { compilerEnv.setGenerateObserverCount(true); } if (arg.equals("-package") && ++i < args.length) { String pkg = args[i]; int end = pkg.length(); for (int j = 0; j != end; ++j) { char c = pkg.charAt(j); if (Character.isJavaIdentifierStart(c)) { for (++j; j != end; ++j) { c = pkg.charAt(j); if (!Character.isJavaIdentifierPart(c)) { break; } } if (j == end) { break; } if (c == '.' && j != end - 1) { continue; } } addError("msg.package.name", targetPackage); return null; } targetPackage = pkg; continue; } if (arg.equals("-extends") && ++i < args.length) { String targetExtends = args[i]; Class superClass; try { superClass = Class.forName(targetExtends); } catch (ClassNotFoundException e) { throw new Error(e.toString()); // TODO: better error } compiler.setTargetExtends(superClass); continue; } if (arg.equals("-implements") && ++i < args.length) { // TODO: allow for multiple comma-separated interfaces. String targetImplements = args[i]; StringTokenizer st = new StringTokenizer(targetImplements, ","); List> list = new ArrayList>(); while (st.hasMoreTokens()) { String className = st.nextToken(); try { list.add(Class.forName(className)); } catch (ClassNotFoundException e) { throw new Error(e.toString()); // TODO: better error } } Class[] implementsClasses = list.toArray(new Class[list.size()]); compiler.setTargetImplements(implementsClasses); continue; } if (arg.equals("-d") && ++i < args.length) { destinationDir = args[i]; continue; } badUsage(arg); return null; } // no file name p(ToolErrorReporter.getMessage("msg.no.file")); return null; } /** * Print a usage message. */ private static void badUsage(String s) { System.err.println(ToolErrorReporter.getMessage( "msg.jsc.bad.usage", Main.class.getName(), s)); } /** * Compile JavaScript source. * */ public void processSource(String[] filenames) { for (int i = 0; i != filenames.length; ++i) { String filename = filenames[i]; if (!filename.endsWith(".js")) { addError("msg.extension.not.js", filename); return; } File f = new File(filename); String source = readSource(f); if (source == null) return; String mainClassName = targetName; if (mainClassName == null) { String name = f.getName(); String nojs = name.substring(0, name.length() - 3); mainClassName = getClassName(nojs); } if (targetPackage.length() != 0) { mainClassName = targetPackage+"."+mainClassName; } Object[] compiled = compiler.compileToClassFiles(source, filename, 1, mainClassName); if (compiled == null || compiled.length == 0) { return; } File targetTopDir = null; if (destinationDir != null) { targetTopDir = new File(destinationDir); } else { String parent = f.getParent(); if (parent != null) { targetTopDir = new File(parent); } } for (int j = 0; j != compiled.length; j += 2) { String className = (String)compiled[j]; byte[] bytes = (byte[])compiled[j + 1]; File outfile = getOutputFile(targetTopDir, className); try { FileOutputStream os = new FileOutputStream(outfile); try { os.write(bytes); } finally { os.close(); } } catch (IOException ioe) { addFormatedError(ioe.toString()); } } } } private String readSource(File f) { String absPath = f.getAbsolutePath(); if (!f.isFile()) { addError("msg.jsfile.not.found", absPath); return null; } try { return (String)SourceReader.readFileOrUrl(absPath, true, characterEncoding); } catch (FileNotFoundException ex) { addError("msg.couldnt.open", absPath); } catch (IOException ioe) { addFormatedError(ioe.toString()); } return null; } private File getOutputFile(File parentDir, String className) { String path = className.replace('.', File.separatorChar); path = path.concat(".class"); File f = new File(parentDir, path); String dirPath = f.getParent(); if (dirPath != null) { File dir = new File(dirPath); if (!dir.exists()) { dir.mkdirs(); } } return f; } /** * Verify that class file names are legal Java identifiers. Substitute * illegal characters with underscores, and prepend the name with an * underscore if the file name does not begin with a JavaLetter. */ String getClassName(String name) { char[] s = new char[name.length()+1]; char c; int j = 0; if (!Character.isJavaIdentifierStart(name.charAt(0))) { s[j++] = '_'; } for (int i=0; i < name.length(); i++, j++) { c = name.charAt(i); if ( Character.isJavaIdentifierPart(c) ) { s[j] = c; } else { s[j] = '_'; } } return (new String(s)).trim(); } private static void p(String s) { System.out.println(s); } private void addError(String messageId, String arg) { String msg; if (arg == null) { msg = ToolErrorReporter.getMessage(messageId); } else { msg = ToolErrorReporter.getMessage(messageId, arg); } addFormatedError(msg); } private void addFormatedError(String message) { reporter.error(message, null, -1, null, -1); } private boolean printHelp; private ToolErrorReporter reporter; private CompilerEnvirons compilerEnv; private ClassCompiler compiler; private String targetName; private String targetPackage; private String destinationDir; private String characterEncoding; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/idswitch/0000755000175000017500000000000011537630013033757 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/idswitch/FileBody.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/idswitch/FileBody.j0000644000175000017500000001326011314263504035631 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 4; indent-tabs-mode: 1; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.idswitch; import java.io.IOException; import java.io.Reader; import java.io.Writer; public class FileBody { private static class ReplaceItem { ReplaceItem next; int begin; int end; String replacement; ReplaceItem(int begin, int end, String text) { this.begin = begin; this.end = end; this.replacement = text; } } private char[] buffer = new char[1 << 14]; // 16K private int bufferEnd; private int lineBegin; private int lineEnd; private int nextLineStart; private int lineNumber; ReplaceItem firstReplace; ReplaceItem lastReplace; public char[] getBuffer() { return buffer; } public void readData(Reader r) throws IOException { int capacity = buffer.length; int offset = 0; for (;;) { int n_read = r.read(buffer, offset, capacity - offset); if (n_read < 0) { break; } offset += n_read; if (capacity == offset) { capacity *= 2; char[] tmp = new char[capacity]; System.arraycopy(buffer, 0, tmp, 0, offset); buffer = tmp; } } bufferEnd = offset; } public void writeInitialData(Writer w) throws IOException { w.write(buffer, 0, bufferEnd); } public void writeData(Writer w) throws IOException { int offset = 0; for (ReplaceItem x = firstReplace; x != null; x = x.next) { int before_replace = x.begin - offset; if (before_replace > 0) { w.write(buffer, offset, before_replace); } w.write(x.replacement); offset = x.end; } int tail = bufferEnd - offset; if (tail != 0) { w.write(buffer, offset, tail); } } public boolean wasModified() { return firstReplace != null; } public boolean setReplacement(int begin, int end, String text) { if (equals(text, buffer, begin, end)) { return false; } ReplaceItem item = new ReplaceItem(begin, end, text); if (firstReplace == null) { firstReplace = lastReplace = item; } else if (begin < firstReplace.begin) { item.next = firstReplace; firstReplace = item; } else { ReplaceItem cursor = firstReplace; ReplaceItem next = cursor.next; while (next != null) { if (begin < next.begin) { item.next = next; cursor.next = item; break; } cursor = next; next = next.next; } if (next == null) { lastReplace.next = item; } } return true; } public int getLineNumber() { return lineNumber; } public int getLineBegin() { return lineBegin; } public int getLineEnd() { return lineEnd; } public void startLineLoop() { lineNumber = 0; lineBegin = lineEnd = nextLineStart = 0; } public boolean nextLine() { if (nextLineStart == bufferEnd) { lineNumber = 0; return false; } int i; int c = 0; for (i = nextLineStart; i != bufferEnd; ++i) { c = buffer[i]; if (c == '\n' || c == '\r') { break; } } lineBegin = nextLineStart; lineEnd = i; if (i == bufferEnd) { nextLineStart = i; } else if (c == '\r' && i + 1 != bufferEnd && buffer[i + 1] == '\n') { nextLineStart = i + 2; } else { nextLineStart = i + 1; } ++lineNumber; return true; } private static boolean equals(String str, char[] array, int begin, int end) { if (str.length() == end - begin) { for (int i = begin, j = 0; i != end; ++i, ++j) { if (array[i] != str.charAt(j)) { return false; } } return true; } return false; } } ././@LongLink0000000000000000000000000000015700000000000011220 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/idswitch/SwitchGenerator.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/idswitch/SwitchGene0000644000175000017500000004056511314263504035754 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 4; indent-tabs-mode: 1; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.idswitch; import org.mozilla.javascript.EvaluatorException; import org.mozilla.javascript.tools.ToolErrorReporter; public class SwitchGenerator { String v_switch_label = "L0"; String v_label = "L"; String v_s = "s"; String v_c = "c"; String v_guess = "X"; String v_id = "id"; String v_length_suffix = "_length"; int use_if_threshold = 3; int char_tail_test_threshold = 2; private IdValuePair[] pairs; private String default_value; private int[] columns; private boolean c_was_defined; private CodePrinter P; private ToolErrorReporter R; private String source_file; public CodePrinter getCodePrinter() { return P; } public void setCodePrinter(CodePrinter value) { P = value; } public ToolErrorReporter getReporter() { return R; } public void setReporter(ToolErrorReporter value) { R = value; } public String getSourceFileName() { return source_file; } public void setSourceFileName(String value) { source_file = value; } public void generateSwitch(String[] pairs, String default_value) { int N = pairs.length / 2; IdValuePair[] id_pairs = new IdValuePair[N]; for (int i = 0; i != N; ++i) { id_pairs[i] = new IdValuePair(pairs[2 * i], pairs[2 * i + 1]); } generateSwitch(id_pairs, default_value); } public void generateSwitch(IdValuePair[] pairs, String default_value) { int begin = 0; int end = pairs.length; if (begin == end) { return; } this.pairs = pairs; this.default_value = default_value; generate_body(begin, end, 2); } private void generate_body(int begin, int end, int indent_level) { P.indent(indent_level); P.p(v_switch_label); P.p(": { "); P.p(v_id); P.p(" = "); P.p(default_value); P.p("; String "); P.p(v_guess); P.p(" = null;"); c_was_defined = false; int c_def_begin = P.getOffset(); P.p(" int "); P.p(v_c); P.p(';'); int c_def_end = P.getOffset(); P.nl(); generate_length_switch(begin, end, indent_level + 1); if (!c_was_defined) { P.erase(c_def_begin, c_def_end); } P.indent(indent_level + 1); P.p("if ("); P.p(v_guess); P.p("!=null && "); P.p(v_guess); P.p("!="); P.p(v_s); P.p(" && !"); P.p(v_guess); P.p(".equals("); P.p(v_s); P.p(")) "); P.p(v_id); P.p(" = "); P.p(default_value); P.p(";"); P.nl(); // Add break at end of block to suppress warning for unused label P.indent(indent_level + 1); P.p("break "); P.p(v_switch_label); P.p(";"); P.nl(); P.line(indent_level, "}"); } private void generate_length_switch(int begin, int end, int indent_level) { sort_pairs(begin, end, -1); check_all_is_different(begin, end); int lengths_count = count_different_lengths(begin, end); columns = new int[pairs[end - 1].idLength]; boolean use_if; if (lengths_count <= use_if_threshold) { use_if = true; if (lengths_count != 1) { P.indent(indent_level); P.p("int "); P.p(v_s); P.p(v_length_suffix); P.p(" = "); P.p(v_s); P.p(".length();"); P.nl(); } } else { use_if = false; P.indent(indent_level); P.p(v_label); P.p(": switch ("); P.p(v_s); P.p(".length()) {"); P.nl(); } int same_length_begin = begin; int cur_l = pairs[begin].idLength, l = 0; for (int i = begin;;) { ++i; if (i == end || (l = pairs[i].idLength) != cur_l) { int next_indent; if (use_if) { P.indent(indent_level); if (same_length_begin != begin) { P.p("else "); } P.p("if ("); if (lengths_count == 1) { P.p(v_s); P.p(".length()=="); } else { P.p(v_s); P.p(v_length_suffix); P.p("=="); } P.p(cur_l); P.p(") {"); next_indent = indent_level + 1; } else { P.indent(indent_level); P.p("case "); P.p(cur_l); P.p(":"); next_indent = indent_level + 1; } generate_letter_switch (same_length_begin, i, next_indent, !use_if, use_if); if (use_if) { P.p("}"); P.nl(); } else { P.p("break "); P.p(v_label); P.p(";"); P.nl(); } if (i == end) { break; } same_length_begin = i; cur_l = l; } } if (!use_if) { P.indent(indent_level); P.p("}"); P.nl(); } } private void generate_letter_switch (int begin, int end, int indent_level, boolean label_was_defined, boolean inside_if) { int L = pairs[begin].idLength; for (int i = 0; i != L; ++i) { columns[i] = i; } generate_letter_switch_r (begin, end, L, indent_level, label_was_defined, inside_if); } private boolean generate_letter_switch_r (int begin, int end, int L, int indent_level, boolean label_was_defined, boolean inside_if) { boolean next_is_unreachable = false; if (begin + 1 == end) { P.p(' '); IdValuePair pair = pairs[begin]; if (L > char_tail_test_threshold) { P.p(v_guess); P.p("="); P.qstring(pair.id); P.p(";"); P.p(v_id); P.p("="); P.p(pair.value); P.p(";"); } else { if (L == 0) { next_is_unreachable = true; P.p(v_id); P.p("="); P.p(pair.value); P.p("; break "); P.p(v_switch_label); P.p(";"); } else { P.p("if ("); int column = columns[0]; P.p(v_s); P.p(".charAt("); P.p(column); P.p(")=="); P.qchar(pair.id.charAt(column)); for (int i = 1; i != L; ++i) { P.p(" && "); column = columns[i]; P.p(v_s); P.p(".charAt("); P.p(column); P.p(")=="); P.qchar(pair.id.charAt(column)); } P.p(") {"); P.p(v_id); P.p("="); P.p(pair.value); P.p("; break "); P.p(v_switch_label); P.p(";}"); } } P.p(' '); return next_is_unreachable; } int max_column_index = find_max_different_column(begin, end, L); int max_column = columns[max_column_index]; int count = count_different_chars(begin, end, max_column); columns[max_column_index] = columns[L - 1]; if (inside_if) { P.nl(); P.indent(indent_level); } else { P.p(' '); } boolean use_if; if (count <= use_if_threshold) { use_if = true; c_was_defined = true; P.p(v_c); P.p("="); P.p(v_s); P.p(".charAt("); P.p(max_column); P.p(");"); } else { use_if = false; if (!label_was_defined) { label_was_defined = true; P.p(v_label); P.p(": "); } P.p("switch ("); P.p(v_s); P.p(".charAt("); P.p(max_column); P.p(")) {"); } int same_char_begin = begin; int cur_ch = pairs[begin].id.charAt(max_column), ch = 0; for (int i = begin;;) { ++i; if (i == end || (ch = pairs[i].id.charAt(max_column)) != cur_ch) { int next_indent; if (use_if) { P.nl(); P.indent(indent_level); if (same_char_begin != begin) { P.p("else "); } P.p("if ("); P.p(v_c); P.p("=="); P.qchar(cur_ch); P.p(") {"); next_indent = indent_level + 1; } else { P.nl(); P.indent(indent_level); P.p("case "); P.qchar(cur_ch); P.p(":"); next_indent = indent_level + 1; } boolean after_unreachable = generate_letter_switch_r (same_char_begin, i, L - 1, next_indent, label_was_defined, use_if); if (use_if) { P.p("}"); } else { if (!after_unreachable) { P.p("break "); P.p(v_label); P.p(";"); } } if (i == end) { break; } same_char_begin = i; cur_ch = ch; } } if (use_if) { P.nl(); if (inside_if) { P.indent(indent_level - 1); } else { P.indent(indent_level); } } else { P.nl(); P.indent(indent_level); P.p("}"); if (inside_if) { P.nl(); P.indent(indent_level - 1);} else { P.p(' '); } } columns[max_column_index] = max_column; return next_is_unreachable; } private int count_different_lengths(int begin, int end) { int lengths_count = 0; int cur_l = -1; for (; begin != end; ++begin) { int l = pairs[begin].idLength; if (cur_l != l) { ++lengths_count; cur_l = l; } } return lengths_count; } private int find_max_different_column(int begin, int end, int L) { int max_count = 0; int max_index = 0; for (int i = 0; i != L; ++i) { int column = columns[i]; sort_pairs(begin, end, column); int count = count_different_chars(begin, end, column); if (count == end - begin) { return i; } if (max_count < count) { max_count = count; max_index = i; } } if (max_index != L - 1) { sort_pairs(begin, end, columns[max_index]); } return max_index; } private int count_different_chars(int begin, int end, int column) { int chars_count = 0; int cur_ch = -1; for (; begin != end; ++begin) { int ch = pairs[begin].id.charAt(column); if (ch != cur_ch) { ++chars_count; cur_ch = ch; } } return chars_count; } private void check_all_is_different(int begin, int end) { if (begin != end) { IdValuePair prev = pairs[begin]; while (++begin != end) { IdValuePair current = pairs[begin]; if (prev.id.equals(current.id)) { throw on_same_pair_fail(prev, current); } prev = current; } } } private EvaluatorException on_same_pair_fail(IdValuePair a, IdValuePair b) { int line1 = a.getLineNumber(), line2 = b.getLineNumber(); if (line2 > line1) { int tmp = line1; line1 = line2; line2 = tmp; } String error_text = ToolErrorReporter.getMessage( "msg.idswitch.same_string", a.id, new Integer(line2)); return R.runtimeError(error_text, source_file, line1, null, 0); } private void sort_pairs(int begin, int end, int comparator) { heap4Sort(pairs, begin, end - begin, comparator); } private static boolean bigger (IdValuePair a, IdValuePair b, int comparator) { if (comparator < 0) { // For length selection switch it is enough to compare just length, // but to detect same strings full comparison is essential //return a.idLength > b.idLength; int diff = a.idLength - b.idLength; if (diff != 0) { return diff > 0; } return a.id.compareTo(b.id) > 0; } else { return a.id.charAt(comparator) > b.id.charAt(comparator); } } private static void heap4Sort (IdValuePair[] array, int offset, int size, int comparator) { if (size <= 1) { return; } makeHeap4(array, offset, size, comparator); while (size > 1) { --size; IdValuePair v1 = array[offset + size]; IdValuePair v2 = array[offset + 0]; array[offset + size] = v2; array[offset + 0] = v1; heapify4(array, offset, size, 0, comparator); } } private static void makeHeap4 (IdValuePair[] array, int offset, int size, int comparator) { for (int i = ((size + 2) >> 2); i != 0;) { --i; heapify4(array, offset, size, i, comparator); } } private static void heapify4 (IdValuePair[] array, int offset, int size, int i, int comparator) { int new_i1, new_i2, new_i3; IdValuePair i_val = array[offset + i]; for (;;) { int base = (i << 2); new_i1 = base | 1; new_i2 = base | 2; new_i3 = base | 3; int new_i4 = base + 4; if (new_i4 >= size) { break; } IdValuePair val1 = array[offset + new_i1]; IdValuePair val2 = array[offset + new_i2]; IdValuePair val3 = array[offset + new_i3]; IdValuePair val4 = array[offset + new_i4]; if (bigger(val2, val1, comparator)) { val1 = val2; new_i1 = new_i2; } if (bigger(val4, val3, comparator)) { val3 = val4; new_i3 = new_i4; } if (bigger(val3, val1, comparator)) { val1 = val3; new_i1 = new_i3; } if (bigger(i_val, val1, comparator)) { return; } array[offset + i] = val1; array[offset + new_i1] = i_val; i = new_i1; } if (new_i1 < size) { IdValuePair val1 = array[offset + new_i1]; if (new_i2 != size) { IdValuePair val2 = array[offset + new_i2]; if (bigger(val2, val1, comparator)) { val1 = val2; new_i1 = new_i2; } if (new_i3 != size) { IdValuePair val3 = array[offset + new_i3]; if (bigger(val3, val1, comparator)) { val1 = val3; new_i1 = new_i3; } } } if (bigger(val1, i_val, comparator)) { array[offset + i] = val1; array[offset + new_i1] = i_val; } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/idswitch/Main.java0000644000175000017500000005070311314263504035513 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 4; indent-tabs-mode: 1; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.idswitch; import java.io.*; import java.util.*; import java.text.SimpleDateFormat; import org.mozilla.javascript.EvaluatorException; import org.mozilla.javascript.tools.ToolErrorReporter; public class Main { private static final String SWITCH_TAG_STR = "string_id_map"; private static final String GENERATED_TAG_STR = "generated"; private static final String STRING_TAG_STR = "string"; private static final int NORMAL_LINE = 0, SWITCH_TAG = 1, GENERATED_TAG = 2, STRING_TAG = 3; private final List all_pairs = new ArrayList(); private ToolErrorReporter R; private CodePrinter P; private FileBody body; private String source_file; private int tag_definition_end; private int tag_value_start; private int tag_value_end; private static boolean is_value_type(int id) { if (id == STRING_TAG) { return true; } return false; } private static String tag_name(int id) { switch (id) { case SWITCH_TAG: return SWITCH_TAG_STR; case -SWITCH_TAG: return "/" + SWITCH_TAG_STR; case GENERATED_TAG: return GENERATED_TAG_STR; case -GENERATED_TAG: return "/" + GENERATED_TAG_STR; } return ""; } void process_file(String file_path) throws IOException { source_file = file_path; body = new FileBody(); InputStream is; if (file_path.equals("-")) { is = System.in; } else { is = new FileInputStream(file_path); } try { Reader r = new InputStreamReader(is, "ASCII"); body.readData(r); } finally { is.close(); } process_file(); if (body.wasModified()) { OutputStream os; if (file_path.equals("-")) { os = System.out; } else { os = new FileOutputStream(file_path); } try { Writer w = new OutputStreamWriter(os); body.writeData(w); w.flush(); } finally { os.close(); } } } private void process_file() { int cur_state = 0; char[] buffer = body.getBuffer(); int generated_begin = -1, generated_end = -1; int time_stamp_begin = -1, time_stamp_end = -1; body.startLineLoop(); while (body.nextLine()) { int begin = body.getLineBegin(); int end = body.getLineEnd(); int tag_id = extract_line_tag_id(buffer, begin, end); boolean bad_tag = false; switch (cur_state) { case NORMAL_LINE: if (tag_id == SWITCH_TAG) { cur_state = SWITCH_TAG; all_pairs.clear(); generated_begin = -1; } else if (tag_id == -SWITCH_TAG) { bad_tag = true; } break; case SWITCH_TAG: if (tag_id == 0) { look_for_id_definitions(buffer, begin, end, false); } else if (tag_id == STRING_TAG) { look_for_id_definitions(buffer, begin, end, true); } else if (tag_id == GENERATED_TAG) { if (generated_begin >= 0) { bad_tag = true; } else { cur_state = GENERATED_TAG; time_stamp_begin = tag_definition_end; time_stamp_end = end; } } else if (tag_id == -SWITCH_TAG) { cur_state = 0; if (generated_begin >= 0 && !all_pairs.isEmpty()) { generate_java_code(); String code = P.toString(); boolean different = body.setReplacement (generated_begin, generated_end, code); if (different) { String stamp = get_time_stamp(); body.setReplacement (time_stamp_begin, time_stamp_end, stamp); } } break; } else { bad_tag = true; } break; case GENERATED_TAG: if (tag_id == 0) { if (generated_begin < 0) { generated_begin = begin; } } else if (tag_id == -GENERATED_TAG) { if (generated_begin < 0) { generated_begin = begin; } cur_state = SWITCH_TAG; generated_end = begin; } else { bad_tag = true; } break; } if (bad_tag) { String text = ToolErrorReporter.getMessage( "msg.idswitch.bad_tag_order", tag_name(tag_id)); throw R.runtimeError (text, source_file, body.getLineNumber(), null, 0); } } if (cur_state != 0) { String text = ToolErrorReporter.getMessage( "msg.idswitch.file_end_in_switch", tag_name(cur_state)); throw R.runtimeError (text, source_file, body.getLineNumber(), null, 0); } } private String get_time_stamp() { SimpleDateFormat f = new SimpleDateFormat (" 'Last update:' yyyy-MM-dd HH:mm:ss z"); return f.format(new Date()); } private void generate_java_code() { P.clear(); IdValuePair[] pairs = new IdValuePair[all_pairs.size()]; all_pairs.toArray(pairs); SwitchGenerator g = new SwitchGenerator(); g.char_tail_test_threshold = 2; g.setReporter(R); g.setCodePrinter(P); g.generateSwitch(pairs, "0"); } private int extract_line_tag_id(char[] array, int cursor, int end) { int id = 0; cursor = skip_white_space(array, cursor, end); int after_leading_white_space = cursor; cursor = look_for_slash_slash(array, cursor, end); if (cursor != end) { boolean at_line_start = (after_leading_white_space + 2 == cursor); cursor = skip_white_space(array, cursor, end); if (cursor != end && array[cursor] == '#') { ++cursor; boolean end_tag = false; if (cursor != end && array[cursor] == '/') { ++cursor; end_tag = true; } int tag_start = cursor; for (; cursor != end; ++cursor) { int c = array[cursor]; if (c == '#' || c == '=' ||is_white_space(c)) { break; } } if (cursor != end) { int tag_end = cursor; cursor = skip_white_space(array, cursor, end); if (cursor != end) { int c = array[cursor]; if (c == '=' || c == '#') { id = get_tag_id (array, tag_start, tag_end, at_line_start); if (id != 0) { String bad = null; if (c == '#') { if (end_tag) { id = -id; if (is_value_type(id)) { bad = "msg.idswitch.no_end_usage"; } } tag_definition_end = cursor + 1; } else { if (end_tag) { bad = "msg.idswitch.no_end_with_value"; } else if (!is_value_type(id)) { bad = "msg.idswitch.no_value_allowed"; } id = extract_tag_value (array, cursor + 1, end, id); } if (bad != null) { String s = ToolErrorReporter.getMessage( bad, tag_name(id)); throw R.runtimeError (s, source_file, body.getLineNumber(), null, 0); } } } } } } } return id; } // Return position after first of // or end if not found private int look_for_slash_slash(char[] array, int cursor, int end) { while (cursor + 2 <= end) { int c = array[cursor++]; if (c == '/') { c = array[cursor++]; if (c == '/') { return cursor; } } } return end; } private int extract_tag_value(char[] array, int cursor, int end, int id) { // cursor points after #[^#=]+= // ALERT: implement support for quoted strings boolean found = false; cursor = skip_white_space(array, cursor, end); if (cursor != end) { int value_start = cursor; int value_end = cursor; while (cursor != end) { int c = array[cursor]; if (is_white_space(c)) { int after_space = skip_white_space(array, cursor + 1, end); if (after_space != end && array[after_space] == '#') { value_end = cursor; cursor = after_space; break; } cursor = after_space + 1; } else if (c == '#') { value_end = cursor; break; } else { ++cursor; } } if (cursor != end) { // array[cursor] is '#' here found = true; tag_value_start = value_start; tag_value_end = value_end; tag_definition_end = cursor + 1; } } return (found) ? id : 0; } private int get_tag_id (char[] array, int begin, int end, boolean at_line_start) { if (at_line_start) { if (equals(SWITCH_TAG_STR, array, begin, end)) { return SWITCH_TAG; } if (equals(GENERATED_TAG_STR, array, begin, end)) { return GENERATED_TAG; } } if (equals(STRING_TAG_STR, array, begin, end)) { return STRING_TAG; } return 0; } private void look_for_id_definitions (char[] array, int begin, int end, boolean use_tag_value_as_string) { // Look for the pattern // '^[ \t]+Id_([a-zA-Z0-9_]+)[ \t]*=.*$' // where \1 gives field or method name int cursor = begin; // Skip tab and spaces at the beginning cursor = skip_white_space(array, cursor, end); int id_start = cursor; int name_start = skip_matched_prefix("Id_", array, cursor, end); if (name_start >= 0) { // Found Id_ prefix cursor = name_start; cursor = skip_name_char(array, cursor, end); int name_end = cursor; if (name_start != name_end) { cursor = skip_white_space(array, cursor, end); if (cursor != end) { if (array[cursor] == '=') { int id_end = name_end; if (use_tag_value_as_string) { name_start = tag_value_start; name_end = tag_value_end; } // Got the match add_id(array, id_start, id_end, name_start, name_end); } } } } } private void add_id (char[] array, int id_start, int id_end, int name_start, int name_end) { String name = new String(array, name_start, name_end - name_start); String value = new String(array, id_start, id_end - id_start); IdValuePair pair = new IdValuePair(name, value); pair.setLineNumber(body.getLineNumber()); all_pairs.add(pair); } private static boolean is_white_space(int c) { return c == ' ' || c == '\t'; } private static int skip_white_space(char[] array, int begin, int end) { int cursor = begin; for (; cursor != end; ++cursor) { int c = array[cursor]; if (!is_white_space(c)) { break; } } return cursor; } private static int skip_matched_prefix (String prefix, char[] array, int begin, int end) { int cursor = -1; int prefix_length = prefix.length(); if (prefix_length <= end - begin) { cursor = begin; for (int i = 0; i != prefix_length; ++i, ++cursor) { if (prefix.charAt(i) != array[cursor]) { cursor = -1; break; } } } return cursor; } private static boolean equals(String str, char[] array, int begin, int end) { if (str.length() == end - begin) { for (int i = begin, j = 0; i != end; ++i, ++j) { if (array[i] != str.charAt(j)) { return false; } } return true; } return false; } private static int skip_name_char(char[] array, int begin, int end) { int cursor = begin; for (; cursor != end; ++cursor) { int c = array[cursor]; if (!('a' <= c && c <= 'z') && !('A' <= c && c <= 'Z')) { if (!('0' <= c && c <= '9')) { if (c != '_') { break; } } } } return cursor; } public static void main(String[] args) { Main self = new Main(); int status = self.exec(args); System.exit(status); } private int exec(String[] args) { R = new ToolErrorReporter(true, System.err); int arg_count = process_options(args); if (arg_count == 0) { option_error(ToolErrorReporter.getMessage( "msg.idswitch.no_file_argument")); return -1; } if (arg_count > 1) { option_error(ToolErrorReporter.getMessage( "msg.idswitch.too_many_arguments")); return -1; } P = new CodePrinter(); P.setIndentStep(4); P.setIndentTabSize(0); try { process_file(args[0]); } catch (IOException ex) { print_error(ToolErrorReporter.getMessage( "msg.idswitch.io_error", ex.toString())); return -1; } catch (EvaluatorException ex) { return -1; } return 0; } private int process_options(String[] args) { int status = 1; boolean show_usage = false; boolean show_version = false; int N = args.length; L: for (int i = 0; i != N; ++i) { String arg = args[i]; int arg_length = arg.length(); if (arg_length >= 2) { if (arg.charAt(0) == '-') { if (arg.charAt(1) == '-') { if (arg_length == 2) { args[i] = null; break; } if (arg.equals("--help")) { show_usage = true; } else if (arg.equals("--version")) { show_version = true; } else { option_error(ToolErrorReporter.getMessage( "msg.idswitch.bad_option", arg)); status = -1; break L; } } else { for (int j = 1; j != arg_length; ++j) { char c = arg.charAt(j); switch (c) { case 'h': show_usage = true; break; default: option_error( ToolErrorReporter.getMessage( "msg.idswitch.bad_option_char", String.valueOf(c))); status = -1; break L; } } } args[i] = null; } } } if (status == 1) { if (show_usage) { show_usage(); status = 0; } if (show_version) { show_version(); status = 0; } } if (status != 1) { System.exit(status); } return remove_nulls(args); } private void show_usage() { System.out.println( ToolErrorReporter.getMessage("msg.idswitch.usage")); System.out.println(); } private void show_version() { System.out.println( ToolErrorReporter.getMessage("msg.idswitch.version")); } private void option_error(String str) { print_error( ToolErrorReporter.getMessage("msg.idswitch.bad_invocation", str)); } private void print_error(String text) { System.err.println(text); } private int remove_nulls(String[] array) { int N = array.length; int cursor = 0; for (; cursor != N; ++cursor) { if (array[cursor] == null) { break; } } int destination = cursor; if (cursor != N) { ++cursor; for (; cursor != N; ++cursor) { String elem = array[cursor]; if (elem != null) { array[destination] = elem; ++destination; } } } return destination; } } ././@LongLink0000000000000000000000000000015300000000000011214 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/idswitch/IdValuePair.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/idswitch/IdValuePai0000644000175000017500000000406611314263504035673 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 4; indent-tabs-mode: 1; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.idswitch; public class IdValuePair { public final int idLength; public final String id; public final String value; private int lineNumber; public IdValuePair(String id, String value) { this.idLength = id.length(); this.id = id; this.value = value; } public int getLineNumber() { return lineNumber; } public void setLineNumber(int value) { lineNumber = value; } } ././@LongLink0000000000000000000000000000015300000000000011214 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/idswitch/CodePrinter.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/idswitch/CodePrinte0000644000175000017500000001472411314263504035746 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 4; indent-tabs-mode: 1; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.idswitch; class CodePrinter { // length of u-type escape like \u12AB private static final int LITERAL_CHAR_MAX_SIZE = 6; private String lineTerminator = "\n"; private int indentStep = 4; private int indentTabSize = 8; private char[] buffer = new char[1 << 12]; // 4K private int offset; public String getLineTerminator() { return lineTerminator; } public void setLineTerminator(String value) { lineTerminator = value; } public int getIndentStep() { return indentStep; } public void setIndentStep(int char_count) { indentStep = char_count; } public int getIndentTabSize() { return indentTabSize; } public void setIndentTabSize(int tab_size) { indentTabSize = tab_size; } public void clear() { offset = 0; } private int ensure_area(int area_size) { int begin = offset; int end = begin + area_size; if (end > buffer.length) { int new_capacity = buffer.length * 2; if (end > new_capacity) { new_capacity = end; } char[] tmp = new char[new_capacity]; System.arraycopy(buffer, 0, tmp, 0, begin); buffer = tmp; } return begin; } private int add_area(int area_size) { int pos = ensure_area(area_size); offset = pos + area_size; return pos; } public int getOffset() { return offset; } public int getLastChar() { return offset == 0 ? -1 : buffer[offset - 1]; } public void p(char c) { int pos = add_area(1); buffer[pos] = c; } public void p(String s) { int l = s.length(); int pos = add_area(l); s.getChars(0, l, buffer, pos); } public final void p(char[] array) { p(array, 0, array.length); } public void p(char[] array, int begin, int end) { int l = end - begin; int pos = add_area(l); System.arraycopy(array, begin, buffer, pos, l); } public void p(int i) { p(Integer.toString(i)); } public void qchar(int c) { int pos = ensure_area(2 + LITERAL_CHAR_MAX_SIZE); buffer[pos] = '\''; pos = put_string_literal_char(pos + 1, c, false); buffer[pos] = '\''; offset = pos + 1; } public void qstring(String s) { int l = s.length(); int pos = ensure_area(2 + LITERAL_CHAR_MAX_SIZE * l); buffer[pos] = '"'; ++pos; for (int i = 0; i != l; ++i) { pos = put_string_literal_char(pos, s.charAt(i), true); } buffer[pos] = '"'; offset = pos + 1; } private int put_string_literal_char(int pos, int c, boolean in_string) { boolean backslash_symbol = true; switch (c) { case '\b': c = 'b'; break; case '\t': c = 't'; break; case '\n': c = 'n'; break; case '\f': c = 'f'; break; case '\r': c = 'r'; break; case '\'': backslash_symbol = !in_string; break; case '"': backslash_symbol = in_string; break; default: backslash_symbol = false; } if (backslash_symbol) { buffer[pos] = '\\'; buffer[pos + 1] = (char)c; pos += 2; } else if (' ' <= c && c <= 126) { buffer[pos] = (char)c; ++pos; } else { buffer[pos] = '\\'; buffer[pos + 1] = 'u'; buffer[pos + 2] = digit_to_hex_letter(0xF & (c >> 12)); buffer[pos + 3] = digit_to_hex_letter(0xF & (c >> 8)); buffer[pos + 4] = digit_to_hex_letter(0xF & (c >> 4)); buffer[pos + 5] = digit_to_hex_letter(0xF & c); pos += 6; } return pos; } private static char digit_to_hex_letter(int d) { return (char)((d < 10) ? '0' + d : 'A' - 10 + d); } public void indent(int level) { int visible_size = indentStep * level; int indent_size, tab_count; if (indentTabSize <= 0) { tab_count = 0; indent_size = visible_size; } else { tab_count = visible_size / indentTabSize; indent_size = tab_count + visible_size % indentTabSize; } int pos = add_area(indent_size); int tab_end = pos + tab_count; int indent_end = pos + indent_size; for (; pos != tab_end; ++pos) { buffer[pos] = '\t'; } for (; pos != indent_end; ++pos) { buffer[pos] = ' '; } } public void nl() { p('\n'); } public void line(int indent_level, String s) { indent(indent_level); p(s); nl(); } public void erase(int begin, int end) { System.arraycopy(buffer, end, buffer, begin, offset - end); offset -= end - begin; } @Override public String toString() { return new String(buffer, 0, offset); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/idswitch/README0000644000175000017500000001401611314263504034641 0ustar jamespagejamespage00000000000000 ***** BEGIN LICENSE BLOCK ***** Version: MPL 1.1/GPL 2.0 The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is Rhino code, released May 6, 1999. The Initial Developer of the Original Code is Netscape Communications Corporation. Portions created by the Initial Developer are Copyright (C) 1997-1999 the Initial Developer. All Rights Reserved. Contributor(s): Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replacing them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. ***** END LICENSE BLOCK ***** USING IDSWITCH GENERATOR TOOL Usage: java org.mozilla.javascript.tools.idswitch.Main The main purpose of this utility is to generate Java code to map strings to some ids that can be used, for example, in a switch statement. The utility scans the input file for lines with the following structure: // #string_id_map# ... // #generated# ... // #/generated# ... // #/string_id_map# Then every line in is scanned for the pattern: ^[ \t]*Id_([0-9a-zA-Z_]+)[ \t]*=.*$ Each such patterns adds a mapping form string $1 to Id_\$ or if the line also contains the pattern //\s*#string=\s*([^#]+)\s*#, then it adds map of $1 in this pattern to Id_\$ After that lines in are replaced by a code block that sets variable "id" to Id_ if variable "s" equals (or value defined by //#string=...# construction in the line with Id_) or 0 otherwise. If the new code for is identical to old one, the file is not touched otherwise is overwritten by the new code and a time stamp is appended after #generated#. For example, if file x.java contains: // #string_id_map# private int getId(String s) { int id; // #generated# Initial version // #/generated# return id; } private static final int Id_x = 1, Id_y = 2, Id_hello = 3, // #string = Hello, World! # Id_symbols = 4, // #string=<<*Symbols*>># Id_nice = 5, Id_for = 6, Id_bar = 7; // #/string_id_map# .... private double getFieldValue(String s) { // #string_id_map# final int Id_field1 = 1, Id_field2 = 2, Id_field3 = 3, Id_one_more_field = 4; // #string = ONE%MORE%FIELD# int id; // #generated# Initial version // #/generated# // #/string_id_map# switch (id) { case Id_field1: return field1; case Id_field2: return field2; case Id_field3: return field3; case Id_one_more_field: return one_more_field; } throw new RuntimeException("No such field"); } then invocation java org.mozilla.javascript.tools.idswitch.Main x.java would replace that by a code fragment similar to: // #string_id_map# private int getId(String s) { int id; // #generated# Last update: 2001-05-25 18:00:24 GMT+02:00 L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 1: c=s.charAt(0); if (c=='x') { id=Id_x; break L0; } else if (c=='y') { id=Id_y; break L0; } break L; case 3: c=s.charAt(0); if (c=='b') { if (s.charAt(2)=='r' && s.charAt(1)=='a') {id=Id_bar; break L0;} } else if (c=='f') { if (s.charAt(2)=='r' && s.charAt(1)=='o') {id=Id_for; break L0;} } break L; case 4: X="nice";id=Id_nice; break L; case 13: c=s.charAt(0); if (c=='<') { X="<<*Symbols*>>";id=Id_symbols; } else if (c=='H') { X="Hello, World!";id=Id_hello; } break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# return id; } private static final int Id_x = 1, Id_y = 2, Id_hello = 3, // #string = Hello, World! # Id_symbols = 4, // #string=<<*Symbols*>># Id_nice = 5, Id_for = 6, Id_bar = 7; // #/string_id_map# .... private double getFieldValue(String s) { // #string_id_map# final int Id_field1 = 1, Id_field2 = 2, Id_field3 = 3, Id_one_more_field = 4; // #string = ONE%MORE%FIELD# int id; // #generated# Last update: 2001-05-25 16:48:50 GMT+02:00 L0: { id = 0; String X = null; int c; int s_length = s.length(); if (s_length==6) { c=s.charAt(5); if (c=='1') { X="field1";id=Id_field1; } else if (c=='2') { X="field2";id=Id_field2; } else if (c=='3') { X="field3";id=Id_field3; } } else if (s_length==14) { X="ONE%MORE%FIELD";id=Id_one_more_field; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# // #/string_id_map# switch (id) { case Id_field1: return field1; case Id_field2: return field2; case Id_field3: return field3; case Id_one_more_field: return one_more_field; } throw new RuntimeException("No such field"); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/0000755000175000017500000000000011537630013033250 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000016000000000000011212 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/ShellContextFactory.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/ShellContextF0000644000175000017500000000763611314263504035731 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Bob Jervis * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.shell; import org.mozilla.javascript.*; public class ShellContextFactory extends ContextFactory { private boolean strictMode; private boolean warningAsError; private int languageVersion; private int optimizationLevel; private boolean generatingDebug; private ErrorReporter errorReporter; private String characterEncoding; @Override protected boolean hasFeature(Context cx, int featureIndex) { switch (featureIndex) { case Context.FEATURE_STRICT_VARS: case Context.FEATURE_STRICT_EVAL: case Context.FEATURE_STRICT_MODE: return strictMode; case Context.FEATURE_WARNING_AS_ERROR: return warningAsError; } return super.hasFeature(cx, featureIndex); } @Override protected void onContextCreated(Context cx) { cx.setLanguageVersion(languageVersion); cx.setOptimizationLevel(optimizationLevel); if (errorReporter != null) { cx.setErrorReporter(errorReporter); } cx.setGeneratingDebug(generatingDebug); super.onContextCreated(cx); } public void setStrictMode(boolean flag) { checkNotSealed(); this.strictMode = flag; } public void setWarningAsError(boolean flag) { checkNotSealed(); this.warningAsError = flag; } public void setLanguageVersion(int version) { Context.checkLanguageVersion(version); checkNotSealed(); this.languageVersion = version; } public void setOptimizationLevel(int optimizationLevel) { Context.checkOptimizationLevel(optimizationLevel); checkNotSealed(); this.optimizationLevel = optimizationLevel; } public void setErrorReporter(ErrorReporter errorReporter) { if (errorReporter == null) throw new IllegalArgumentException(); this.errorReporter = errorReporter; } public void setGeneratingDebug(boolean generatingDebug) { this.generatingDebug = generatingDebug; } public String getCharacterEncoding() { return characterEncoding; } public void setCharacterEncoding(String characterEncoding) { this.characterEncoding = characterEncoding; } } ././@LongLink0000000000000000000000000000014600000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/JSConsole.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/JSConsole.jav0000644000175000017500000002075111314263504035616 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino JavaScript Debugger code, released * November 21, 2000. * * The Initial Developer of the Original Code is * See Beyond Corporation. * Portions created by the Initial Developer are Copyright (C) 2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Christopher Oliver * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.shell; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import javax.swing.ButtonGroup; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.mozilla.javascript.SecurityUtilities; public class JSConsole extends JFrame implements ActionListener { static final long serialVersionUID = 2551225560631876300L; private File CWD; private JFileChooser dlg; private ConsoleTextArea consoleTextArea; public String chooseFile() { if(CWD == null) { String dir = SecurityUtilities.getSystemProperty("user.dir"); if(dir != null) { CWD = new File(dir); } } if(CWD != null) { dlg.setCurrentDirectory(CWD); } dlg.setDialogTitle("Select a file to load"); int returnVal = dlg.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { String result = dlg.getSelectedFile().getPath(); CWD = new File(dlg.getSelectedFile().getParent()); return result; } return null; } public static void main(String args[]) { new JSConsole(args); } public void createFileChooser() { dlg = new JFileChooser(); javax.swing.filechooser.FileFilter filter = new javax.swing.filechooser.FileFilter() { @Override public boolean accept(File f) { if(f.isDirectory()) { return true; } String name = f.getName(); int i = name.lastIndexOf('.'); if(i > 0 && i < name.length() -1) { String ext = name.substring(i + 1).toLowerCase(); if(ext.equals("js")) { return true; } } return false; } @Override public String getDescription() { return "JavaScript Files (*.js)"; } }; dlg.addChoosableFileFilter(filter); } public JSConsole(String[] args) { super("Rhino JavaScript Console"); JMenuBar menubar = new JMenuBar(); createFileChooser(); String[] fileItems = {"Load...", "Exit"}; String[] fileCmds = {"Load", "Exit"}; char[] fileShortCuts = {'L', 'X'}; String[] editItems = {"Cut", "Copy", "Paste"}; char[] editShortCuts = {'T', 'C', 'P'}; String[] plafItems = {"Metal", "Windows", "Motif"}; boolean [] plafState = {true, false, false}; JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('E'); JMenu plafMenu = new JMenu("Platform"); plafMenu.setMnemonic('P'); for(int i = 0; i < fileItems.length; ++i) { JMenuItem item = new JMenuItem(fileItems[i], fileShortCuts[i]); item.setActionCommand(fileCmds[i]); item.addActionListener(this); fileMenu.add(item); } for(int i = 0; i < editItems.length; ++i) { JMenuItem item = new JMenuItem(editItems[i], editShortCuts[i]); item.addActionListener(this); editMenu.add(item); } ButtonGroup group = new ButtonGroup(); for(int i = 0; i < plafItems.length; ++i) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(plafItems[i], plafState[i]); group.add(item); item.addActionListener(this); plafMenu.add(item); } menubar.add(fileMenu); menubar.add(editMenu); menubar.add(plafMenu); setJMenuBar(menubar); consoleTextArea = new ConsoleTextArea(args); JScrollPane scroller = new JScrollPane(consoleTextArea); setContentPane(scroller); consoleTextArea.setRows(24); consoleTextArea.setColumns(80); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); pack(); setVisible(true); // System.setIn(consoleTextArea.getIn()); // System.setOut(consoleTextArea.getOut()); // System.setErr(consoleTextArea.getErr()); Main.setIn(consoleTextArea.getIn()); Main.setOut(consoleTextArea.getOut()); Main.setErr(consoleTextArea.getErr()); Main.main(args); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); String plaf_name = null; if(cmd.equals("Load")) { String f = chooseFile(); if(f != null) { f = f.replace('\\', '/'); consoleTextArea.eval("load(\"" + f + "\");"); } } else if(cmd.equals("Exit")) { System.exit(0); } else if(cmd.equals("Cut")) { consoleTextArea.cut(); } else if(cmd.equals("Copy")) { consoleTextArea.copy(); } else if(cmd.equals("Paste")) { consoleTextArea.paste(); } else { if(cmd.equals("Metal")) { plaf_name = "javax.swing.plaf.metal.MetalLookAndFeel"; } else if(cmd.equals("Windows")) { plaf_name = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; } else if(cmd.equals("Motif")) { plaf_name = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; } if(plaf_name != null) { try { UIManager.setLookAndFeel(plaf_name); SwingUtilities.updateComponentTreeUI(this); consoleTextArea.postUpdateUI(); // updateComponentTreeUI seems to mess up the file // chooser dialog, so just create a new one createFileChooser(); } catch(Exception exc) { JOptionPane.showMessageDialog(this, exc.getMessage(), "Platform", JOptionPane.ERROR_MESSAGE); } } } } } ././@LongLink0000000000000000000000000000015200000000000011213 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/SecurityProxy.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/SecurityProxy0000644000175000017500000000362211314263504036047 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.shell; import org.mozilla.javascript.*; public abstract class SecurityProxy extends SecurityController { protected abstract void callProcessFileSecure(Context cx, Scriptable scope, String filename); } ././@LongLink0000000000000000000000000000014700000000000011217 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/QuitAction.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/QuitAction.ja0000644000175000017500000000352311314263504035647 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.shell; import org.mozilla.javascript.Context; /** * Defines action to perform in response to quit command. */ public interface QuitAction { public void quit(Context cx, int exitCode); } ././@LongLink0000000000000000000000000000015400000000000011215 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/ConsoleTextArea.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/ConsoleTextAr0000644000175000017500000002206011314263504035725 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino JavaScript Debugger code, released * November 21, 2000. * * The Initial Developer of the Original Code is * See Beyond Corporation. * Portions created by the Initial Developer are Copyright (C) 2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Christopher Oliver * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.shell; import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.Document; import javax.swing.text.Segment; class ConsoleWrite implements Runnable { private ConsoleTextArea textArea; private String str; public ConsoleWrite(ConsoleTextArea textArea, String str) { this.textArea = textArea; this.str = str; } public void run() { textArea.write(str); } } class ConsoleWriter extends java.io.OutputStream { private ConsoleTextArea textArea; private StringBuffer buffer; public ConsoleWriter(ConsoleTextArea textArea) { this.textArea = textArea; buffer = new StringBuffer(); } @Override public synchronized void write(int ch) { buffer.append((char)ch); if(ch == '\n') { flushBuffer(); } } public synchronized void write (char[] data, int off, int len) { for(int i = off; i < len; i++) { buffer.append(data[i]); if(data[i] == '\n') { flushBuffer(); } } } @Override public synchronized void flush() { if (buffer.length() > 0) { flushBuffer(); } } @Override public void close () { flush(); } private void flushBuffer() { String str = buffer.toString(); buffer.setLength(0); SwingUtilities.invokeLater(new ConsoleWrite(textArea, str)); } } public class ConsoleTextArea extends JTextArea implements KeyListener, DocumentListener { static final long serialVersionUID = 8557083244830872961L; private ConsoleWriter console1; private ConsoleWriter console2; private PrintStream out; private PrintStream err; private PrintWriter inPipe; private PipedInputStream in; private java.util.List history; private int historyIndex = -1; private int outputMark = 0; @Override public void select(int start, int end) { requestFocus(); super.select(start, end); } public ConsoleTextArea(String[] argv) { super(); history = new java.util.ArrayList(); console1 = new ConsoleWriter(this); console2 = new ConsoleWriter(this); out = new PrintStream(console1, true); err = new PrintStream(console2, true); PipedOutputStream outPipe = new PipedOutputStream(); inPipe = new PrintWriter(outPipe); in = new PipedInputStream(); try { outPipe.connect(in); } catch(IOException exc) { exc.printStackTrace(); } getDocument().addDocumentListener(this); addKeyListener(this); setLineWrap(true); setFont(new Font("Monospaced", 0, 12)); } synchronized void returnPressed() { Document doc = getDocument(); int len = doc.getLength(); Segment segment = new Segment(); try { doc.getText(outputMark, len - outputMark, segment); } catch(javax.swing.text.BadLocationException ignored) { ignored.printStackTrace(); } if(segment.count > 0) { history.add(segment.toString()); } historyIndex = history.size(); inPipe.write(segment.array, segment.offset, segment.count); append("\n"); outputMark = doc.getLength(); inPipe.write("\n"); inPipe.flush(); console1.flush(); } public void eval(String str) { inPipe.write(str); inPipe.write("\n"); inPipe.flush(); console1.flush(); } public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if(code == KeyEvent.VK_BACK_SPACE || code == KeyEvent.VK_LEFT) { if(outputMark == getCaretPosition()) { e.consume(); } } else if(code == KeyEvent.VK_HOME) { int caretPos = getCaretPosition(); if(caretPos == outputMark) { e.consume(); } else if(caretPos > outputMark) { if(!e.isControlDown()) { if(e.isShiftDown()) { moveCaretPosition(outputMark); } else { setCaretPosition(outputMark); } e.consume(); } } } else if(code == KeyEvent.VK_ENTER) { returnPressed(); e.consume(); } else if(code == KeyEvent.VK_UP) { historyIndex--; if(historyIndex >= 0) { if(historyIndex >= history.size()) { historyIndex = history.size() -1; } if(historyIndex >= 0) { String str = history.get(historyIndex); int len = getDocument().getLength(); replaceRange(str, outputMark, len); int caretPos = outputMark + str.length(); select(caretPos, caretPos); } else { historyIndex++; } } else { historyIndex++; } e.consume(); } else if(code == KeyEvent.VK_DOWN) { int caretPos = outputMark; if(history.size() > 0) { historyIndex++; if(historyIndex < 0) {historyIndex = 0;} int len = getDocument().getLength(); if (historyIndex < history.size()) { String str = history.get(historyIndex); replaceRange(str, outputMark, len); caretPos = outputMark + str.length(); } else { historyIndex = history.size(); replaceRange("", outputMark, len); } } select(caretPos, caretPos); e.consume(); } } public void keyTyped(KeyEvent e) { int keyChar = e.getKeyChar(); if(keyChar == 0x8 /* KeyEvent.VK_BACK_SPACE */) { if(outputMark == getCaretPosition()) { e.consume(); } } else if(getCaretPosition() < outputMark) { setCaretPosition(outputMark); } } public synchronized void keyReleased(KeyEvent e) { } public synchronized void write(String str) { insert(str, outputMark); int len = str.length(); outputMark += len; select(outputMark, outputMark); } public synchronized void insertUpdate(DocumentEvent e) { int len = e.getLength(); int off = e.getOffset(); if(outputMark > off) { outputMark += len; } } public synchronized void removeUpdate(DocumentEvent e) { int len = e.getLength(); int off = e.getOffset(); if(outputMark > off) { if(outputMark >= off + len) { outputMark -= len; } else { outputMark = off; } } } public synchronized void postUpdateUI() { // this attempts to cleanup the damage done by updateComponentTreeUI requestFocus(); setCaret(getCaret()); select(outputMark, outputMark); } public synchronized void changedUpdate(DocumentEvent e) { } public InputStream getIn() { return in; } public PrintStream getOut() { return out; } public PrintStream getErr() { return err; } } ././@LongLink0000000000000000000000000000015700000000000011220 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/JavaPolicySecurity.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/JavaPolicySec0000644000175000017500000002150111314263504035666 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.shell; import java.security.*; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import org.mozilla.javascript.*; public class JavaPolicySecurity extends SecurityProxy { @Override public Class getStaticSecurityDomainClassInternal() { return ProtectionDomain.class; } private static class Loader extends ClassLoader implements GeneratedClassLoader { private ProtectionDomain domain; Loader(ClassLoader parent, ProtectionDomain domain) { super(parent != null ? parent : getSystemClassLoader()); this.domain = domain; } public Class defineClass(String name, byte[] data) { return super.defineClass(name, data, 0, data.length, domain); } public void linkClass(Class cl) { resolveClass(cl); } } private static class ContextPermissions extends PermissionCollection { static final long serialVersionUID = -1721494496320750721L; // Construct PermissionCollection that permits an action only // if it is permitted by staticDomain and by security context of Java stack on // the moment of constructor invocation ContextPermissions(ProtectionDomain staticDomain) { _context = AccessController.getContext(); if (staticDomain != null) { _statisPermissions = staticDomain.getPermissions(); } setReadOnly(); } @Override public void add(Permission permission) { throw new RuntimeException("NOT IMPLEMENTED"); } @Override public boolean implies(Permission permission) { if (_statisPermissions != null) { if (!_statisPermissions.implies(permission)) { return false; } } try { _context.checkPermission(permission); return true; }catch (AccessControlException ex) { return false; } } @Override public Enumeration elements() { return new Enumeration() { public boolean hasMoreElements() { return false; } public Permission nextElement() { return null; } }; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getName()); sb.append('@'); sb.append(Integer.toHexString(System.identityHashCode(this))); sb.append(" (context="); sb.append(_context); sb.append(", static_permitions="); sb.append(_statisPermissions); sb.append(')'); return sb.toString(); } AccessControlContext _context; PermissionCollection _statisPermissions; } public JavaPolicySecurity() { // To trigger error on jdk-1.1 with lazy load new CodeSource(null, (java.security.cert.Certificate[])null); } @Override protected void callProcessFileSecure(final Context cx, final Scriptable scope, final String filename) { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { URL url = getUrlObj(filename); ProtectionDomain staticDomain = getUrlDomain(url); Main.processFileSecure(cx, scope, url.toExternalForm(), staticDomain); return null; } }); } private URL getUrlObj(String url) { URL urlObj; try { urlObj = new URL(url); } catch (MalformedURLException ex) { // Assume as Main.processFileSecure it is file, need to build its // URL String curDir = System.getProperty("user.dir"); curDir = curDir.replace('\\', '/'); if (!curDir.endsWith("/")) { curDir = curDir+'/'; } try { URL curDirURL = new URL("file:"+curDir); urlObj = new URL(curDirURL, url); } catch (MalformedURLException ex2) { throw new RuntimeException ("Can not construct file URL for '"+url+"':" +ex2.getMessage()); } } return urlObj; } private ProtectionDomain getUrlDomain(URL url) { CodeSource cs; cs = new CodeSource(url, (java.security.cert.Certificate[])null); PermissionCollection pc = Policy.getPolicy().getPermissions(cs); return new ProtectionDomain(cs, pc); } @Override public GeneratedClassLoader createClassLoader(ClassLoader parentLoader, Object securityDomain) { ProtectionDomain domain = (ProtectionDomain)securityDomain; return new Loader(parentLoader, domain); } @Override public Object getDynamicSecurityDomain(Object securityDomain) { ProtectionDomain staticDomain = (ProtectionDomain)securityDomain; return getDynamicDomain(staticDomain); } private ProtectionDomain getDynamicDomain(ProtectionDomain staticDomain) { ContextPermissions p = new ContextPermissions(staticDomain); ProtectionDomain contextDomain = new ProtectionDomain(null, p); return contextDomain; } @Override public Object callWithDomain(Object securityDomain, final Context cx, final Callable callable, final Scriptable scope, final Scriptable thisObj, final Object[] args) { ProtectionDomain staticDomain = (ProtectionDomain)securityDomain; // There is no direct way in Java to intersect permissions according // stack context with additional domain. // The following implementation first constructs ProtectionDomain // that allows actions only allowed by both staticDomain and current // stack context, and then constructs AccessController for this dynamic // domain. // If this is too slow, alternative solution would be to generate // class per domain with a proxy method to call to infect // java stack. // Another optimization in case of scripts coming from "world" domain, // that is having minimal default privileges is to construct // one AccessControlContext based on ProtectionDomain // with least possible privileges and simply call // AccessController.doPrivileged with this untrusted context ProtectionDomain dynamicDomain = getDynamicDomain(staticDomain); ProtectionDomain[] tmp = { dynamicDomain }; AccessControlContext restricted = new AccessControlContext(tmp); PrivilegedAction action = new PrivilegedAction() { public Object run() { return callable.call(cx, scope, thisObj, args); } }; return AccessController.doPrivileged(action, restricted); } } ././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/Environment.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/Environment.j0000644000175000017500000001043511314263504035732 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ /* Environment.java Wraps java.lang.System properties. by Patrick C. Beard */ package org.mozilla.javascript.tools.shell; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.ScriptableObject; import java.util.Map; /** * Environment, intended to be instantiated at global scope, provides * a natural way to access System properties from JavaScript. * * @author Patrick C. Beard */ public class Environment extends ScriptableObject { static final long serialVersionUID = -430727378460177065L; private Environment thePrototypeInstance = null; public static void defineClass(ScriptableObject scope) { try { ScriptableObject.defineClass(scope, Environment.class); } catch (Exception e) { throw new Error(e.getMessage()); } } @Override public String getClassName() { return "Environment"; } public Environment() { if (thePrototypeInstance == null) thePrototypeInstance = this; } public Environment(ScriptableObject scope) { setParentScope(scope); Object ctor = ScriptRuntime.getTopLevelProp(scope, "Environment"); if (ctor != null && ctor instanceof Scriptable) { Scriptable s = (Scriptable) ctor; setPrototype((Scriptable) s.get("prototype", s)); } } @Override public boolean has(String name, Scriptable start) { if (this == thePrototypeInstance) return super.has(name, start); return (System.getProperty(name) != null); } @Override public Object get(String name, Scriptable start) { if (this == thePrototypeInstance) return super.get(name, start); String result = System.getProperty(name); if (result != null) return ScriptRuntime.toObject(getParentScope(), result); else return Scriptable.NOT_FOUND; } @Override public void put(String name, Scriptable start, Object value) { if (this == thePrototypeInstance) super.put(name, start, value); else System.getProperties().put(name, ScriptRuntime.toString(value)); } private Object[] collectIds() { Map props = System.getProperties(); return props.keySet().toArray(); } @Override public Object[] getIds() { if (this == thePrototypeInstance) return super.getIds(); return collectIds(); } @Override public Object[] getAllIds() { if (this == thePrototypeInstance) return super.getAllIds(); return collectIds(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/Main.java0000644000175000017500000005242711314263504035011 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Patrick Beard * Norris Boyd * Igor Bukanov * Rob Ginda * Kurt Westerfeld * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.shell; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.UndeclaredThrowableException; import java.util.ArrayList; import java.util.List; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.EvaluatorException; import org.mozilla.javascript.Function; import org.mozilla.javascript.GeneratedClassLoader; import org.mozilla.javascript.Kit; import org.mozilla.javascript.NativeArray; import org.mozilla.javascript.RhinoException; import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.SecurityController; import org.mozilla.javascript.tools.SourceReader; import org.mozilla.javascript.tools.ToolErrorReporter; /** * The shell program. * * Can execute scripts interactively or in batch mode at the command line. * An example of controlling the JavaScript engine. * * @author Norris Boyd */ public class Main { public static ShellContextFactory shellContextFactory = new ShellContextFactory(); public static Global global = new Global(); static protected ToolErrorReporter errorReporter; static protected int exitCode = 0; static private final int EXITCODE_RUNTIME_ERROR = 3; static private final int EXITCODE_FILE_NOT_FOUND = 4; static boolean processStdin = true; static List fileList = new ArrayList(); private static SecurityProxy securityImpl; static { global.initQuitAction(new IProxy(IProxy.SYSTEM_EXIT)); } /** * Proxy class to avoid proliferation of anonymous classes. */ private static class IProxy implements ContextAction, QuitAction { private static final int PROCESS_FILES = 1; private static final int EVAL_INLINE_SCRIPT = 2; private static final int SYSTEM_EXIT = 3; private int type; String[] args; String scriptText; IProxy(int type) { this.type = type; } public Object run(Context cx) { if (type == PROCESS_FILES) { processFiles(cx, args); } else if (type == EVAL_INLINE_SCRIPT) { Script script = loadScriptFromSource(cx, scriptText, "", 1, null); if (script != null) { evaluateScript(script, cx, getGlobal()); } } else { throw Kit.codeBug(); } return null; } public void quit(Context cx, int exitCode) { if (type == SYSTEM_EXIT) { System.exit(exitCode); return; } throw Kit.codeBug(); } } /** * Main entry point. * * Process arguments as would a normal Java program. Also * create a new Context and associate it with the current thread. * Then set up the execution environment and begin to * execute scripts. */ public static void main(String args[]) { try { if (Boolean.getBoolean("rhino.use_java_policy_security")) { initJavaPolicySecuritySupport(); } } catch (SecurityException ex) { ex.printStackTrace(System.err); } int result = exec(args); if (result != 0) { System.exit(result); } } /** * Execute the given arguments, but don't System.exit at the end. */ public static int exec(String origArgs[]) { errorReporter = new ToolErrorReporter(false, global.getErr()); shellContextFactory.setErrorReporter(errorReporter); String[] args = processOptions(origArgs); if (processStdin) fileList.add(null); if (!global.initialized) { global.init(shellContextFactory); } IProxy iproxy = new IProxy(IProxy.PROCESS_FILES); iproxy.args = args; shellContextFactory.call(iproxy); return exitCode; } static void processFiles(Context cx, String[] args) { // define "arguments" array in the top-level object: // need to allocate new array since newArray requires instances // of exactly Object[], not ObjectSubclass[] Object[] array = new Object[args.length]; System.arraycopy(args, 0, array, 0, args.length); Scriptable argsObj = cx.newArray(global, array); global.defineProperty("arguments", argsObj, ScriptableObject.DONTENUM); for (String file: fileList) { processSource(cx, file); } } public static Global getGlobal() { return global; } /** * Parse arguments. */ public static String[] processOptions(String args[]) { String usageError; goodUsage: for (int i = 0; ; ++i) { if (i == args.length) { return new String[0]; } String arg = args[i]; if (!arg.startsWith("-")) { processStdin = false; fileList.add(arg); String[] result = new String[args.length - i - 1]; System.arraycopy(args, i+1, result, 0, args.length - i - 1); return result; } if (arg.equals("-version")) { if (++i == args.length) { usageError = arg; break goodUsage; } int version; try { version = Integer.parseInt(args[i]); } catch (NumberFormatException ex) { usageError = args[i]; break goodUsage; } if (!Context.isValidLanguageVersion(version)) { usageError = args[i]; break goodUsage; } shellContextFactory.setLanguageVersion(version); continue; } if (arg.equals("-opt") || arg.equals("-O")) { if (++i == args.length) { usageError = arg; break goodUsage; } int opt; try { opt = Integer.parseInt(args[i]); } catch (NumberFormatException ex) { usageError = args[i]; break goodUsage; } if (opt == -2) { // Compatibility with Cocoon Rhino fork opt = -1; } else if (!Context.isValidOptimizationLevel(opt)) { usageError = args[i]; break goodUsage; } shellContextFactory.setOptimizationLevel(opt); continue; } if (arg.equals("-encoding")) { if (++i == args.length) { usageError = arg; break goodUsage; } String enc = args[i]; shellContextFactory.setCharacterEncoding(enc); continue; } if (arg.equals("-strict")) { shellContextFactory.setStrictMode(true); errorReporter.setIsReportingWarnings(true); continue; } if (arg.equals("-fatal-warnings")) { shellContextFactory.setWarningAsError(true); continue; } if (arg.equals("-e")) { processStdin = false; if (++i == args.length) { usageError = arg; break goodUsage; } if (!global.initialized) { global.init(shellContextFactory); } IProxy iproxy = new IProxy(IProxy.EVAL_INLINE_SCRIPT); iproxy.scriptText = args[i]; shellContextFactory.call(iproxy); continue; } if (arg.equals("-w")) { errorReporter.setIsReportingWarnings(true); continue; } if (arg.equals("-f")) { processStdin = false; if (++i == args.length) { usageError = arg; break goodUsage; } fileList.add(args[i].equals("-") ? null : args[i]); continue; } if (arg.equals("-sealedlib")) { global.setSealedStdLib(true); continue; } if (arg.equals("-debug")) { shellContextFactory.setGeneratingDebug(true); continue; } if (arg.equals("-?") || arg.equals("-help")) { // print usage message global.getOut().println( ToolErrorReporter.getMessage("msg.shell.usage", Main.class.getName())); System.exit(1); } usageError = arg; break goodUsage; } // print error and usage message global.getOut().println( ToolErrorReporter.getMessage("msg.shell.invalid", usageError)); global.getOut().println( ToolErrorReporter.getMessage("msg.shell.usage", Main.class.getName())); System.exit(1); return null; } private static void initJavaPolicySecuritySupport() { Throwable exObj; try { Class cl = Class.forName ("org.mozilla.javascript.tools.shell.JavaPolicySecurity"); securityImpl = (SecurityProxy)cl.newInstance(); SecurityController.initGlobal(securityImpl); return; } catch (ClassNotFoundException ex) { exObj = ex; } catch (IllegalAccessException ex) { exObj = ex; } catch (InstantiationException ex) { exObj = ex; } catch (LinkageError ex) { exObj = ex; } throw Kit.initCause(new IllegalStateException( "Can not load security support: "+exObj), exObj); } /** * Evaluate JavaScript source. * * @param cx the current context * @param filename the name of the file to compile, or null * for interactive mode. */ public static void processSource(Context cx, String filename) { if (filename == null || filename.equals("-")) { PrintStream ps = global.getErr(); if (filename == null) { // print implementation version ps.println(cx.getImplementationVersion()); } // Use the interpreter for interactive input cx.setOptimizationLevel(-1); String charEnc = shellContextFactory.getCharacterEncoding(); if(charEnc == null) { charEnc = System.getProperty("file.encoding"); } BufferedReader in; try { in = new BufferedReader(new InputStreamReader(global.getIn(), charEnc)); } catch(UnsupportedEncodingException e) { throw new UndeclaredThrowableException(e); } int lineno = 1; boolean hitEOF = false; while (!hitEOF) { String[] prompts = global.getPrompts(cx); if (filename == null) ps.print(prompts[0]); ps.flush(); String source = ""; // Collect lines of source to compile. while (true) { String newline; try { newline = in.readLine(); } catch (IOException ioe) { ps.println(ioe.toString()); break; } if (newline == null) { hitEOF = true; break; } source = source + newline + "\n"; lineno++; if (cx.stringIsCompilableUnit(source)) break; ps.print(prompts[1]); } Script script = loadScriptFromSource(cx, source, "", lineno, null); if (script != null) { Object result = evaluateScript(script, cx, global); // Avoid printing out undefined or function definitions. if (result != Context.getUndefinedValue() && !(result instanceof Function && source.trim().startsWith("function"))) { try { ps.println(Context.toString(result)); } catch (RhinoException rex) { ToolErrorReporter.reportException( cx.getErrorReporter(), rex); } } NativeArray h = global.history; h.put((int)h.getLength(), h, source); } } ps.println(); } else { processFile(cx, global, filename); } } public static void processFile(Context cx, Scriptable scope, String filename) { if (securityImpl == null) { processFileSecure(cx, scope, filename, null); } else { securityImpl.callProcessFileSecure(cx, scope, filename); } } static void processFileSecure(Context cx, Scriptable scope, String path, Object securityDomain) { Script script; if (path.endsWith(".class")) { script = loadCompiledScript(cx, path, securityDomain); } else { String source = (String)readFileOrUrl(path, true); if (source == null) { exitCode = EXITCODE_FILE_NOT_FOUND; return; } // Support the executable script #! syntax: If // the first line begins with a '#', treat the whole // line as a comment. if (source.length() > 0 && source.charAt(0) == '#') { for (int i = 1; i != source.length(); ++i) { int c = source.charAt(i); if (c == '\n' || c == '\r') { source = source.substring(i); break; } } } script = loadScriptFromSource(cx, source, path, 1, securityDomain); } if (script != null) { evaluateScript(script, cx, scope); } } public static Script loadScriptFromSource(Context cx, String scriptSource, String path, int lineno, Object securityDomain) { try { return cx.compileString(scriptSource, path, lineno, securityDomain); } catch (EvaluatorException ee) { // Already printed message. exitCode = EXITCODE_RUNTIME_ERROR; } catch (RhinoException rex) { ToolErrorReporter.reportException( cx.getErrorReporter(), rex); exitCode = EXITCODE_RUNTIME_ERROR; } catch (VirtualMachineError ex) { // Treat StackOverflow and OutOfMemory as runtime errors ex.printStackTrace(); String msg = ToolErrorReporter.getMessage( "msg.uncaughtJSException", ex.toString()); exitCode = EXITCODE_RUNTIME_ERROR; Context.reportError(msg); } return null; } private static Script loadCompiledScript(Context cx, String path, Object securityDomain) { byte[] data = (byte[])readFileOrUrl(path, false); if (data == null) { exitCode = EXITCODE_FILE_NOT_FOUND; return null; } // XXX: For now extract class name of compiled Script from path // instead of parsing class bytes int nameStart = path.lastIndexOf('/'); if (nameStart < 0) { nameStart = 0; } else { ++nameStart; } int nameEnd = path.lastIndexOf('.'); if (nameEnd < nameStart) { // '.' does not exist in path (nameEnd < 0) // or it comes before nameStart nameEnd = path.length(); } String name = path.substring(nameStart, nameEnd); try { GeneratedClassLoader loader = SecurityController.createLoader(cx.getApplicationClassLoader(), securityDomain); Class clazz = loader.defineClass(name, data); loader.linkClass(clazz); if (!Script.class.isAssignableFrom(clazz)) { throw Context.reportRuntimeError("msg.must.implement.Script"); } return (Script) clazz.newInstance(); } catch (RhinoException rex) { ToolErrorReporter.reportException( cx.getErrorReporter(), rex); exitCode = EXITCODE_RUNTIME_ERROR; } catch (IllegalAccessException iaex) { exitCode = EXITCODE_RUNTIME_ERROR; Context.reportError(iaex.toString()); } catch (InstantiationException inex) { exitCode = EXITCODE_RUNTIME_ERROR; Context.reportError(inex.toString()); } return null; } public static Object evaluateScript(Script script, Context cx, Scriptable scope) { try { return script.exec(cx, scope); } catch (RhinoException rex) { ToolErrorReporter.reportException( cx.getErrorReporter(), rex); exitCode = EXITCODE_RUNTIME_ERROR; } catch (VirtualMachineError ex) { // Treat StackOverflow and OutOfMemory as runtime errors ex.printStackTrace(); String msg = ToolErrorReporter.getMessage( "msg.uncaughtJSException", ex.toString()); exitCode = EXITCODE_RUNTIME_ERROR; Context.reportError(msg); } return Context.getUndefinedValue(); } public static InputStream getIn() { return getGlobal().getIn(); } public static void setIn(InputStream in) { getGlobal().setIn(in); } public static PrintStream getOut() { return getGlobal().getOut(); } public static void setOut(PrintStream out) { getGlobal().setOut(out); } public static PrintStream getErr() { return getGlobal().getErr(); } public static void setErr(PrintStream err) { getGlobal().setErr(err); } /** * Read file or url specified by path. * @return file or url content as byte[] or as String if * convertToString is true. */ private static Object readFileOrUrl(String path, boolean convertToString) { try { return SourceReader.readFileOrUrl(path, convertToString, shellContextFactory.getCharacterEncoding()); } catch (IOException ex) { Context.reportError(ToolErrorReporter.getMessage( "msg.couldnt.read.source", path, ex.getMessage())); return null; } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/Global.java0000644000175000017500000012253011314263504035316 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Patrick Beard * Igor Bukanov * Norris Boyd * Rob Ginda * Kurt Westerfeld * Matthias Radestock * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.shell; import java.io.*; import java.net.*; import java.lang.reflect.*; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.Matcher; import org.mozilla.javascript.*; import org.mozilla.javascript.tools.ToolErrorReporter; import org.mozilla.javascript.serialize.*; /** * This class provides for sharing functions across multiple threads. * This is of particular interest to server applications. * * @author Norris Boyd */ public class Global extends ImporterTopLevel { static final long serialVersionUID = 4029130780977538005L; NativeArray history; boolean attemptedJLineLoad; private InputStream inStream; private PrintStream outStream; private PrintStream errStream; private boolean sealedStdLib = false; boolean initialized; private QuitAction quitAction; private String[] prompts = { "js> ", " > " }; private HashMap doctestCanonicalizations; public Global() { } public Global(Context cx) { init(cx); } public boolean isInitialized() { return initialized; } /** * Set the action to call from quit(). */ public void initQuitAction(QuitAction quitAction) { if (quitAction == null) throw new IllegalArgumentException("quitAction is null"); if (this.quitAction != null) throw new IllegalArgumentException("The method is once-call."); this.quitAction = quitAction; } public void init(ContextFactory factory) { factory.call(new ContextAction() { public Object run(Context cx) { init(cx); return null; } }); } public void init(Context cx) { // Define some global functions particular to the shell. Note // that these functions are not part of ECMA. initStandardObjects(cx, sealedStdLib); String[] names = { "defineClass", "deserialize", "doctest", "gc", "help", "load", "loadClass", "print", "quit", "readFile", "readUrl", "runCommand", "seal", "serialize", "spawn", "sync", "toint32", "version", }; defineFunctionProperties(names, Global.class, ScriptableObject.DONTENUM); // Set up "environment" in the global scope to provide access to the // System environment variables. Environment.defineClass(this); Environment environment = new Environment(this); defineProperty("environment", environment, ScriptableObject.DONTENUM); history = (NativeArray) cx.newArray(this, 0); defineProperty("history", history, ScriptableObject.DONTENUM); initialized = true; } /** * Print a help message. * * This method is defined as a JavaScript function. */ public static void help(Context cx, Scriptable thisObj, Object[] args, Function funObj) { PrintStream out = getInstance(funObj).getOut(); out.println(ToolErrorReporter.getMessage("msg.help")); } public static void gc(Context cx, Scriptable thisObj, Object[] args, Function funObj) { System.gc(); } /** * Print the string values of its arguments. * * This method is defined as a JavaScript function. * Note that its arguments are of the "varargs" form, which * allows it to handle an arbitrary number of arguments * supplied to the JavaScript function. * */ public static Object print(Context cx, Scriptable thisObj, Object[] args, Function funObj) { PrintStream out = getInstance(funObj).getOut(); for (int i=0; i < args.length; i++) { if (i > 0) out.print(" "); // Convert the arbitrary JavaScript value into a string form. String s = Context.toString(args[i]); out.print(s); } out.println(); return Context.getUndefinedValue(); } /** * Call embedding-specific quit action passing its argument as * int32 exit code. * * This method is defined as a JavaScript function. */ public static void quit(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Global global = getInstance(funObj); if (global.quitAction != null) { int exitCode = (args.length == 0 ? 0 : ScriptRuntime.toInt32(args[0])); global.quitAction.quit(cx, exitCode); } } /** * Get and set the language version. * * This method is defined as a JavaScript function. */ public static double version(Context cx, Scriptable thisObj, Object[] args, Function funObj) { double result = cx.getLanguageVersion(); if (args.length > 0) { double d = Context.toNumber(args[0]); cx.setLanguageVersion((int) d); } return result; } /** * Load and execute a set of JavaScript source files. * * This method is defined as a JavaScript function. * */ public static void load(Context cx, Scriptable thisObj, Object[] args, Function funObj) { for (int i = 0; i < args.length; i++) { Main.processFile(cx, thisObj, Context.toString(args[i])); } } /** * Load a Java class that defines a JavaScript object using the * conventions outlined in ScriptableObject.defineClass. *

* This method is defined as a JavaScript function. * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @see org.mozilla.javascript.ScriptableObject#defineClass(Scriptable,Class) */ @SuppressWarnings({"unchecked"}) public static void defineClass(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IllegalAccessException, InstantiationException, InvocationTargetException { Class clazz = getClass(args); if (!Scriptable.class.isAssignableFrom(clazz)) { throw reportRuntimeError("msg.must.implement.Scriptable"); } ScriptableObject.defineClass(thisObj, (Class)clazz); } /** * Load and execute a script compiled to a class file. *

* This method is defined as a JavaScript function. * When called as a JavaScript function, a single argument is * expected. This argument should be the name of a class that * implements the Script interface, as will any script * compiled by jsc. * * @exception IllegalAccessException if access is not available * to the class * @exception InstantiationException if unable to instantiate * the named class */ public static void loadClass(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IllegalAccessException, InstantiationException { Class clazz = getClass(args); if (!Script.class.isAssignableFrom(clazz)) { throw reportRuntimeError("msg.must.implement.Script"); } Script script = (Script) clazz.newInstance(); script.exec(cx, thisObj); } private static Class getClass(Object[] args) { if (args.length == 0) { throw reportRuntimeError("msg.expected.string.arg"); } Object arg0 = args[0]; if (arg0 instanceof Wrapper) { Object wrapped = ((Wrapper)arg0).unwrap(); if (wrapped instanceof Class) return (Class)wrapped; } String className = Context.toString(args[0]); try { return Class.forName(className); } catch (ClassNotFoundException cnfe) { throw reportRuntimeError("msg.class.not.found", className); } } public static void serialize(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { if (args.length < 2) { throw Context.reportRuntimeError( "Expected an object to serialize and a filename to write " + "the serialization to"); } Object obj = args[0]; String filename = Context.toString(args[1]); FileOutputStream fos = new FileOutputStream(filename); Scriptable scope = ScriptableObject.getTopLevelScope(thisObj); ScriptableOutputStream out = new ScriptableOutputStream(fos, scope); out.writeObject(obj); out.close(); } public static Object deserialize(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException, ClassNotFoundException { if (args.length < 1) { throw Context.reportRuntimeError( "Expected a filename to read the serialization from"); } String filename = Context.toString(args[0]); FileInputStream fis = new FileInputStream(filename); Scriptable scope = ScriptableObject.getTopLevelScope(thisObj); ObjectInputStream in = new ScriptableInputStream(fis, scope); Object deserialized = in.readObject(); in.close(); return Context.toObject(deserialized, scope); } public String[] getPrompts(Context cx) { if (ScriptableObject.hasProperty(this, "prompts")) { Object promptsJS = ScriptableObject.getProperty(this, "prompts"); if (promptsJS instanceof Scriptable) { Scriptable s = (Scriptable) promptsJS; if (ScriptableObject.hasProperty(s, 0) && ScriptableObject.hasProperty(s, 1)) { Object elem0 = ScriptableObject.getProperty(s, 0); if (elem0 instanceof Function) { elem0 = ((Function) elem0).call(cx, this, s, new Object[0]); } prompts[0] = Context.toString(elem0); Object elem1 = ScriptableObject.getProperty(s, 1); if (elem1 instanceof Function) { elem1 = ((Function) elem1).call(cx, this, s, new Object[0]); } prompts[1] = Context.toString(elem1); } } } return prompts; } /** * Example: doctest("js> function f() {\n > return 3;\n > }\njs> f();\n3\n"); returns true */ public static Object doctest(Context cx, Scriptable thisObj, Object[] args, Function funObj) { if (args.length == 0) { return Boolean.FALSE; } String session = Context.toString(args[0]); Global global = getInstance(funObj); return new Integer(global.runDoctest(cx, global, session, null, 0)); } public int runDoctest(Context cx, Scriptable scope, String session, String sourceName, int lineNumber) { doctestCanonicalizations = new HashMap(); String[] lines = session.split("[\n\r]+"); String prompt0 = this.prompts[0].trim(); String prompt1 = this.prompts[1].trim(); int testCount = 0; int i = 0; while (i < lines.length && !lines[i].trim().startsWith(prompt0)) { i++; // skip lines that don't look like shell sessions } while (i < lines.length) { String inputString = lines[i].trim().substring(prompt0.length()); inputString += "\n"; i++; while (i < lines.length && lines[i].trim().startsWith(prompt1)) { inputString += lines[i].trim().substring(prompt1.length()); inputString += "\n"; i++; } String expectedString = ""; while (i < lines.length && !lines[i].trim().startsWith(prompt0)) { expectedString += lines[i] + "\n"; i++; } PrintStream savedOut = this.getOut(); PrintStream savedErr = this.getErr(); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); this.setOut(new PrintStream(out)); this.setErr(new PrintStream(err)); String resultString = ""; ErrorReporter savedErrorReporter = cx.getErrorReporter(); cx.setErrorReporter(new ToolErrorReporter(false, this.getErr())); try { testCount++; Object result = cx.evaluateString(scope, inputString, "doctest input", 1, null); if (result != Context.getUndefinedValue() && !(result instanceof Function && inputString.trim().startsWith("function"))) { resultString = Context.toString(result); } } catch (RhinoException e) { ToolErrorReporter.reportException(cx.getErrorReporter(), e); } finally { this.setOut(savedOut); this.setErr(savedErr); cx.setErrorReporter(savedErrorReporter); resultString += err.toString() + out.toString(); } if (!doctestOutputMatches(expectedString, resultString)) { String message = "doctest failure running:\n" + inputString + "expected: " + expectedString + "actual: " + resultString + "\n"; if (sourceName != null) throw Context.reportRuntimeError(message, sourceName, lineNumber+i-1, null, 0); else throw Context.reportRuntimeError(message); } } return testCount; } /** * Compare actual result of doctest to expected, modulo some * acceptable differences. Currently just trims the strings * before comparing, but should ignore differences in line numbers * for error messages for example. * * @param expected the expected string * @param actual the actual string * @return true iff actual matches expected modulo some acceptable * differences */ private boolean doctestOutputMatches(String expected, String actual) { expected = expected.trim(); actual = actual.trim().replace("\r\n", "\n"); if (expected.equals(actual)) return true; for (Map.Entry entry: doctestCanonicalizations.entrySet()) { expected = expected.replace(entry.getKey(), entry.getValue()); } if (expected.equals(actual)) return true; // java.lang.Object.toString() prints out a unique hex number associated // with each object. This number changes from run to run, so we want to // ignore differences between these numbers in the output. We search for a // regexp that matches the hex number preceded by '@', then enter mappings into // "doctestCanonicalizations" so that we ensure that the mappings are // consistent within a session. Pattern p = Pattern.compile("@[0-9a-fA-F]+"); Matcher expectedMatcher = p.matcher(expected); Matcher actualMatcher = p.matcher(actual); for (;;) { if (!expectedMatcher.find()) return false; if (!actualMatcher.find()) return false; if (actualMatcher.start() != expectedMatcher.start()) return false; int start = expectedMatcher.start(); if (!expected.substring(0, start).equals(actual.substring(0, start))) return false; String expectedGroup = expectedMatcher.group(); String actualGroup = actualMatcher.group(); String mapping = doctestCanonicalizations.get(expectedGroup); if (mapping == null) { doctestCanonicalizations.put(expectedGroup, actualGroup); expected = expected.replace(expectedGroup, actualGroup); } else if (!actualGroup.equals(mapping)) { return false; // wrong object! } if (expected.equals(actual)) return true; } } /** * The spawn function runs a given function or script in a different * thread. * * js> function g() { a = 7; } * js> a = 3; * 3 * js> spawn(g) * Thread[Thread-1,5,main] * js> a * 3 */ public static Object spawn(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Scriptable scope = funObj.getParentScope(); Runner runner; if (args.length != 0 && args[0] instanceof Function) { Object[] newArgs = null; if (args.length > 1 && args[1] instanceof Scriptable) { newArgs = cx.getElements((Scriptable) args[1]); } if (newArgs == null) { newArgs = ScriptRuntime.emptyArgs; } runner = new Runner(scope, (Function) args[0], newArgs); } else if (args.length != 0 && args[0] instanceof Script) { runner = new Runner(scope, (Script) args[0]); } else { throw reportRuntimeError("msg.spawn.args"); } runner.factory = cx.getFactory(); Thread thread = new Thread(runner); thread.start(); return thread; } /** * The sync function creates a synchronized function (in the sense * of a Java synchronized method) from an existing function. The * new function synchronizes on the this object of * its invocation. * js> var o = { f : sync(function(x) { * print("entry"); * Packages.java.lang.Thread.sleep(x*1000); * print("exit"); * })}; * js> spawn(function() {o.f(5);}); * Thread[Thread-0,5,main] * entry * js> spawn(function() {o.f(5);}); * Thread[Thread-1,5,main] * js> * exit * entry * exit */ public static Object sync(Context cx, Scriptable thisObj, Object[] args, Function funObj) { if (args.length == 1 && args[0] instanceof Function) { return new Synchronizer((Function)args[0]); } else { throw reportRuntimeError("msg.sync.args"); } } /** * Execute the specified command with the given argument and options * as a separate process and return the exit status of the process. *

* Usage: *

     * runCommand(command)
     * runCommand(command, arg1, ..., argN)
     * runCommand(command, arg1, ..., argN, options)
     * 
* All except the last arguments to runCommand are converted to strings * and denote command name and its arguments. If the last argument is a * JavaScript object, it is an option object. Otherwise it is converted to * string denoting the last argument and options objects assumed to be * empty. * The following properties of the option object are processed: *
    *
  • args - provides an array of additional command arguments *
  • env - explicit environment object. All its enumerable * properties define the corresponding environment variable names. *
  • input - the process input. If it is not * java.io.InputStream, it is converted to string and sent to the process * as its input. If not specified, no input is provided to the process. *
  • output - the process output instead of * java.lang.System.out. If it is not instance of java.io.OutputStream, * the process output is read, converted to a string, appended to the * output property value converted to string and put as the new value of * the output property. *
  • err - the process error output instead of * java.lang.System.err. If it is not instance of java.io.OutputStream, * the process error output is read, converted to a string, appended to * the err property value converted to string and put as the new * value of the err property. *
*/ public static Object runCommand(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { int L = args.length; if (L == 0 || (L == 1 && args[0] instanceof Scriptable)) { throw reportRuntimeError("msg.runCommand.bad.args"); } InputStream in = null; OutputStream out = null, err = null; ByteArrayOutputStream outBytes = null, errBytes = null; Object outObj = null, errObj = null; String[] environment = null; Scriptable params = null; Object[] addArgs = null; if (args[L - 1] instanceof Scriptable) { params = (Scriptable)args[L - 1]; --L; Object envObj = ScriptableObject.getProperty(params, "env"); if (envObj != Scriptable.NOT_FOUND) { if (envObj == null) { environment = new String[0]; } else { if (!(envObj instanceof Scriptable)) { throw reportRuntimeError("msg.runCommand.bad.env"); } Scriptable envHash = (Scriptable)envObj; Object[] ids = ScriptableObject.getPropertyIds(envHash); environment = new String[ids.length]; for (int i = 0; i != ids.length; ++i) { Object keyObj = ids[i], val; String key; if (keyObj instanceof String) { key = (String)keyObj; val = ScriptableObject.getProperty(envHash, key); } else { int ikey = ((Number)keyObj).intValue(); key = Integer.toString(ikey); val = ScriptableObject.getProperty(envHash, ikey); } if (val == ScriptableObject.NOT_FOUND) { val = Undefined.instance; } environment[i] = key+'='+ScriptRuntime.toString(val); } } } Object inObj = ScriptableObject.getProperty(params, "input"); if (inObj != Scriptable.NOT_FOUND) { in = toInputStream(inObj); } outObj = ScriptableObject.getProperty(params, "output"); if (outObj != Scriptable.NOT_FOUND) { out = toOutputStream(outObj); if (out == null) { outBytes = new ByteArrayOutputStream(); out = outBytes; } } errObj = ScriptableObject.getProperty(params, "err"); if (errObj != Scriptable.NOT_FOUND) { err = toOutputStream(errObj); if (err == null) { errBytes = new ByteArrayOutputStream(); err = errBytes; } } Object addArgsObj = ScriptableObject.getProperty(params, "args"); if (addArgsObj != Scriptable.NOT_FOUND) { Scriptable s = Context.toObject(addArgsObj, getTopLevelScope(thisObj)); addArgs = cx.getElements(s); } } Global global = getInstance(funObj); if (out == null) { out = (global != null) ? global.getOut() : System.out; } if (err == null) { err = (global != null) ? global.getErr() : System.err; } // If no explicit input stream, do not send any input to process, // in particular, do not use System.in to avoid deadlocks // when waiting for user input to send to process which is already // terminated as it is not always possible to interrupt read method. String[] cmd = new String[(addArgs == null) ? L : L + addArgs.length]; for (int i = 0; i != L; ++i) { cmd[i] = ScriptRuntime.toString(args[i]); } if (addArgs != null) { for (int i = 0; i != addArgs.length; ++i) { cmd[L + i] = ScriptRuntime.toString(addArgs[i]); } } int exitCode = runProcess(cmd, environment, in, out, err); if (outBytes != null) { String s = ScriptRuntime.toString(outObj) + outBytes.toString(); ScriptableObject.putProperty(params, "output", s); } if (errBytes != null) { String s = ScriptRuntime.toString(errObj) + errBytes.toString(); ScriptableObject.putProperty(params, "err", s); } return new Integer(exitCode); } /** * The seal function seals all supplied arguments. */ public static void seal(Context cx, Scriptable thisObj, Object[] args, Function funObj) { for (int i = 0; i != args.length; ++i) { Object arg = args[i]; if (!(arg instanceof ScriptableObject) || arg == Undefined.instance) { if (!(arg instanceof Scriptable) || arg == Undefined.instance) { throw reportRuntimeError("msg.shell.seal.not.object"); } else { throw reportRuntimeError("msg.shell.seal.not.scriptable"); } } } for (int i = 0; i != args.length; ++i) { Object arg = args[i]; ((ScriptableObject)arg).sealObject(); } } /** * The readFile reads the given file content and convert it to a string * using the specified character coding or default character coding if * explicit coding argument is not given. *

* Usage: *

     * readFile(filePath)
     * readFile(filePath, charCoding)
     * 
* The first form converts file's context to string using the default * character coding. */ public static Object readFile(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { if (args.length == 0) { throw reportRuntimeError("msg.shell.readFile.bad.args"); } String path = ScriptRuntime.toString(args[0]); String charCoding = null; if (args.length >= 2) { charCoding = ScriptRuntime.toString(args[1]); } return readUrl(path, charCoding, true); } /** * The readUrl opens connection to the given URL, read all its data * and converts them to a string * using the specified character coding or default character coding if * explicit coding argument is not given. *

* Usage: *

     * readUrl(url)
     * readUrl(url, charCoding)
     * 
* The first form converts file's context to string using the default * charCoding. */ public static Object readUrl(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { if (args.length == 0) { throw reportRuntimeError("msg.shell.readUrl.bad.args"); } String url = ScriptRuntime.toString(args[0]); String charCoding = null; if (args.length >= 2) { charCoding = ScriptRuntime.toString(args[1]); } return readUrl(url, charCoding, false); } /** * Convert the argument to int32 number. */ public static Object toint32(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Object arg = (args.length != 0 ? args[0] : Undefined.instance); if (arg instanceof Integer) return arg; return ScriptRuntime.wrapInt(ScriptRuntime.toInt32(arg)); } public InputStream getIn() { if (inStream == null && !attemptedJLineLoad) { // Check if we can use JLine for better command line handling InputStream jlineStream = ShellLine.getStream(this); if (jlineStream != null) inStream = jlineStream; attemptedJLineLoad = true; } return inStream == null ? System.in : inStream; } public void setIn(InputStream in) { inStream = in; } public PrintStream getOut() { return outStream == null ? System.out : outStream; } public void setOut(PrintStream out) { outStream = out; } public PrintStream getErr() { return errStream == null ? System.err : errStream; } public void setErr(PrintStream err) { errStream = err; } public void setSealedStdLib(boolean value) { sealedStdLib = value; } private static Global getInstance(Function function) { Scriptable scope = function.getParentScope(); if (!(scope instanceof Global)) throw reportRuntimeError("msg.bad.shell.function.scope", String.valueOf(scope)); return (Global)scope; } /** * Runs the given process using Runtime.exec(). * If any of in, out, err is null, the corresponding process stream will * be closed immediately, otherwise it will be closed as soon as * all data will be read from/written to process * * @return Exit value of process. * @throws IOException If there was an error executing the process. */ private static int runProcess(String[] cmd, String[] environment, InputStream in, OutputStream out, OutputStream err) throws IOException { Process p; if (environment == null) { p = Runtime.getRuntime().exec(cmd); } else { p = Runtime.getRuntime().exec(cmd, environment); } try { PipeThread inThread = null; if (in != null) { inThread = new PipeThread(false, in, p.getOutputStream()); inThread.start(); } else { p.getOutputStream().close(); } PipeThread outThread = null; if (out != null) { outThread = new PipeThread(true, p.getInputStream(), out); outThread.start(); } else { p.getInputStream().close(); } PipeThread errThread = null; if (err != null) { errThread = new PipeThread(true, p.getErrorStream(), err); errThread.start(); } else { p.getErrorStream().close(); } // wait for process completion for (;;) { try { p.waitFor(); if (outThread != null) { outThread.join(); } if (inThread != null) { inThread.join(); } if (errThread != null) { errThread.join(); } break; } catch (InterruptedException ignore) { } } return p.exitValue(); } finally { p.destroy(); } } static void pipe(boolean fromProcess, InputStream from, OutputStream to) throws IOException { try { final int SIZE = 4096; byte[] buffer = new byte[SIZE]; for (;;) { int n; if (!fromProcess) { n = from.read(buffer, 0, SIZE); } else { try { n = from.read(buffer, 0, SIZE); } catch (IOException ex) { // Ignore exception as it can be cause by closed pipe break; } } if (n < 0) { break; } if (fromProcess) { to.write(buffer, 0, n); to.flush(); } else { try { to.write(buffer, 0, n); to.flush(); } catch (IOException ex) { // Ignore exception as it can be cause by closed pipe break; } } } } finally { try { if (fromProcess) { from.close(); } else { to.close(); } } catch (IOException ex) { // Ignore errors on close. On Windows JVM may throw invalid // refrence exception if process terminates too fast. } } } private static InputStream toInputStream(Object value) throws IOException { InputStream is = null; String s = null; if (value instanceof Wrapper) { Object unwrapped = ((Wrapper)value).unwrap(); if (unwrapped instanceof InputStream) { is = (InputStream)unwrapped; } else if (unwrapped instanceof byte[]) { is = new ByteArrayInputStream((byte[])unwrapped); } else if (unwrapped instanceof Reader) { s = readReader((Reader)unwrapped); } else if (unwrapped instanceof char[]) { s = new String((char[])unwrapped); } } if (is == null) { if (s == null) { s = ScriptRuntime.toString(value); } is = new ByteArrayInputStream(s.getBytes()); } return is; } private static OutputStream toOutputStream(Object value) { OutputStream os = null; if (value instanceof Wrapper) { Object unwrapped = ((Wrapper)value).unwrap(); if (unwrapped instanceof OutputStream) { os = (OutputStream)unwrapped; } } return os; } private static String readUrl(String filePath, String charCoding, boolean urlIsFile) throws IOException { int chunkLength; InputStream is = null; try { if (!urlIsFile) { URL urlObj = new URL(filePath); URLConnection uc = urlObj.openConnection(); is = uc.getInputStream(); chunkLength = uc.getContentLength(); if (chunkLength <= 0) chunkLength = 1024; if (charCoding == null) { String type = uc.getContentType(); if (type != null) { charCoding = getCharCodingFromType(type); } } } else { File f = new File(filePath); if (!f.exists()) { throw new FileNotFoundException("File not found: " + filePath); } else if (!f.canRead()) { throw new IOException("Cannot read file: " + filePath); } long length = f.length(); chunkLength = (int)length; if (chunkLength != length) throw new IOException("Too big file size: "+length); if (chunkLength == 0) { return ""; } is = new FileInputStream(f); } Reader r; if (charCoding == null) { r = new InputStreamReader(is); } else { r = new InputStreamReader(is, charCoding); } return readReader(r, chunkLength); } finally { if (is != null) is.close(); } } private static String getCharCodingFromType(String type) { int i = type.indexOf(';'); if (i >= 0) { int end = type.length(); ++i; while (i != end && type.charAt(i) <= ' ') { ++i; } String charset = "charset"; if (charset.regionMatches(true, 0, type, i, charset.length())) { i += charset.length(); while (i != end && type.charAt(i) <= ' ') { ++i; } if (i != end && type.charAt(i) == '=') { ++i; while (i != end && type.charAt(i) <= ' ') { ++i; } if (i != end) { // i is at the start of non-empty // charCoding spec while (type.charAt(end -1) <= ' ') { --end; } return type.substring(i, end); } } } } return null; } private static String readReader(Reader reader) throws IOException { return readReader(reader, 4096); } private static String readReader(Reader reader, int initialBufferSize) throws IOException { char[] buffer = new char[initialBufferSize]; int offset = 0; for (;;) { int n = reader.read(buffer, offset, buffer.length - offset); if (n < 0) { break; } offset += n; if (offset == buffer.length) { char[] tmp = new char[buffer.length * 2]; System.arraycopy(buffer, 0, tmp, 0, offset); buffer = tmp; } } return new String(buffer, 0, offset); } static RuntimeException reportRuntimeError(String msgId) { String message = ToolErrorReporter.getMessage(msgId); return Context.reportRuntimeError(message); } static RuntimeException reportRuntimeError(String msgId, String msgArg) { String message = ToolErrorReporter.getMessage(msgId, msgArg); return Context.reportRuntimeError(message); } } class Runner implements Runnable, ContextAction { Runner(Scriptable scope, Function func, Object[] args) { this.scope = scope; f = func; this.args = args; } Runner(Scriptable scope, Script script) { this.scope = scope; s = script; } public void run() { factory.call(this); } public Object run(Context cx) { if (f != null) return f.call(cx, scope, scope, args); else return s.exec(cx, scope); } ContextFactory factory; private Scriptable scope; private Function f; private Script s; private Object[] args; } class PipeThread extends Thread { PipeThread(boolean fromProcess, InputStream from, OutputStream to) { setDaemon(true); this.fromProcess = fromProcess; this.from = from; this.to = to; } @Override public void run() { try { Global.pipe(fromProcess, from, to); } catch (IOException ex) { throw Context.throwAsScriptRuntimeEx(ex); } } private boolean fromProcess; private InputStream from; private OutputStream to; } ././@LongLink0000000000000000000000000000015600000000000011217 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/ParsedContentType.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/ParsedContent0000644000175000017500000000345611314263504035754 0ustar jamespagejamespage00000000000000package org.mozilla.javascript.tools.shell; import java.util.StringTokenizer; /** * Breaks a "contentType; charset=encoding" MIME type into content type and * encoding parts. * @author Attila Szegedi * @version $Id: ParsedContentType.java 3786 2008-11-19 18:23:18Z mguillem $ */ public final class ParsedContentType { private final String contentType; private final String encoding; public ParsedContentType(String mimeType) { String contentType = null; String encoding = null; if(mimeType != null) { StringTokenizer tok = new StringTokenizer(mimeType, ";"); if(tok.hasMoreTokens()) { contentType = tok.nextToken().trim(); while(tok.hasMoreTokens()) { String param = tok.nextToken().trim(); if(param.startsWith("charset=")) { encoding = param.substring(8).trim(); int l = encoding.length(); if(l > 0) { if(encoding.charAt(0) == '"') { encoding = encoding.substring(1); } if(encoding.charAt(l - 1) == '"') { encoding = encoding.substring(0, l - 1); } } break; } } } } this.contentType = contentType; this.encoding = encoding; } public String getContentType() { return contentType; } public String getEncoding() { return encoding; } }././@LongLink0000000000000000000000000000014600000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/ShellLine.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/toolsrc/org/mozilla/javascript/tools/shell/ShellLine.jav0000755000175000017500000001620711314263504035642 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Matthieu Riou * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.tools.shell; import java.io.InputStream; import java.util.List; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.InvocationTargetException; import org.mozilla.javascript.Kit; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.Function; /** * Provides a specialized input stream for consoles to handle line * editing, history and completion. Relies on the JLine library (see * ). */ public class ShellLine { public static InputStream getStream(Scriptable scope) { // We don't want a compile-time dependency on the JLine jar, so use // reflection to load and reference the JLine classes. ClassLoader classLoader = ShellLine.class.getClassLoader(); if (classLoader == null) { // If the attempt to get a class specific class loader above failed // then fallback to the system class loader. classLoader = ClassLoader.getSystemClassLoader(); } if (classLoader == null) { // If for some reason we still don't have a handle to a class // loader then give up (avoid a NullPointerException). return null; } Class readerClass = Kit.classOrNull(classLoader, "jline.ConsoleReader"); if (readerClass == null) return null; try { // ConsoleReader reader = new ConsoleReader(); Constructor c = readerClass.getConstructor(); Object reader = c.newInstance(); // reader.setBellEnabled(false); Method m = readerClass.getMethod("setBellEnabled", Boolean.TYPE); m.invoke(reader, Boolean.FALSE); // reader.addCompletor(new FlexibleCompletor(prefixes)); Class completorClass = Kit.classOrNull(classLoader, "jline.Completor"); m = readerClass.getMethod("addCompletor", completorClass); Object completor = Proxy.newProxyInstance(classLoader, new Class[] { completorClass }, new FlexibleCompletor(completorClass, scope)); m.invoke(reader, completor); // return new ConsoleReaderInputStream(reader); Class inputStreamClass = Kit.classOrNull(classLoader, "jline.ConsoleReaderInputStream"); c = inputStreamClass.getConstructor(readerClass); return (InputStream) c.newInstance(reader); } catch (NoSuchMethodException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return null; } } /** * The completors provided with JLine are pretty uptight, they only * complete on a line that it can fully recognize (only composed of * completed strings). This one completes whatever came before. */ class FlexibleCompletor implements java.lang.reflect.InvocationHandler { private Method completeMethod; private Scriptable global; FlexibleCompletor(Class completorClass, Scriptable global) throws NoSuchMethodException { this.global = global; this.completeMethod = completorClass.getMethod("complete", String.class, Integer.TYPE, List.class); } @SuppressWarnings({"unchecked"}) public Object invoke(Object proxy, Method method, Object[] args) { if (method.equals(this.completeMethod)) { int result = complete((String)args[0], ((Integer) args[1]).intValue(), (List) args[2]); return Integer.valueOf(result); } throw new NoSuchMethodError(method.toString()); } public int complete(String buffer, int cursor, List candidates) { // Starting from "cursor" at the end of the buffer, look backward // and collect a list of identifiers separated by (possibly zero) // dots. Then look up each identifier in turn until getting to the // last, presumably incomplete fragment. Then enumerate all the // properties of the last object and find any that have the // fragment as a prefix and return those for autocompletion. int m = cursor - 1; while (m >= 0) { char c = buffer.charAt(m); if (!Character.isJavaIdentifierPart(c) && c != '.') break; m--; } String namesAndDots = buffer.substring(m+1, cursor); String[] names = namesAndDots.split("\\.", -1); Scriptable obj = this.global; for (int i=0; i < names.length - 1; i++) { Object val = obj.get(names[i], global); if (val instanceof Scriptable) obj = (Scriptable) val; else { return buffer.length(); // no matches } } Object[] ids = (obj instanceof ScriptableObject) ? ((ScriptableObject)obj).getAllIds() : obj.getIds(); String lastPart = names[names.length-1]; for (int i=0; i < ids.length; i++) { if (!(ids[i] instanceof String)) continue; String id = (String)ids[i]; if (id.startsWith(lastPart)) { if (obj.get(id, obj) instanceof Function) id += "("; candidates.add(id); } } return buffer.length() - lastPart.length(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/0000755000175000017500000000000011537630013025102 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/build.xml0000644000175000017500000001232111314263504026722 0ustar jamespagejamespage00000000000000 Skipping DOM E4X implementation; JDK 1.5+ currently required for compilation. Compiling XMLBeans E4X implementation using ${xbean.jar} and ${jsr173.jar} Skipping compilation of XMLBeans E4X implementation due to missing XMLBeans files jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/0000755000175000017500000000000011537630013025671 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/0000755000175000017500000000000011537630013027340 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/0000755000175000017500000000000011537630013031506 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/0000755000175000017500000000000011537630013033170 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/Namespace.java0000644000175000017500000002641211314263504035734 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ethan Hugg * Terry Lucas * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import org.mozilla.javascript.*; /** * Class Namespace * */ class Namespace extends IdScriptableObject { static final long serialVersionUID = -5765755238131301744L; private static final Object NAMESPACE_TAG = "Namespace"; private Namespace prototype; private XmlNode.Namespace ns; private Namespace() { } static Namespace create(Scriptable scope, Namespace prototype, XmlNode.Namespace namespace) { Namespace rv = new Namespace(); rv.setParentScope(scope); rv.prototype = prototype; rv.setPrototype(prototype); rv.ns = namespace; return rv; } final XmlNode.Namespace getDelegate() { return ns; } public void exportAsJSClass(boolean sealed) { exportAsJSClass(MAX_PROTOTYPE_ID, this.getParentScope(), sealed); } public String uri() { return ns.getUri(); } public String prefix() { return ns.getPrefix(); } @Override public String toString() { return uri(); } public String toLocaleString() { return toString(); } private boolean equals(Namespace n) { return uri().equals(n.uri()); } @Override public boolean equals(Object obj) { if (!(obj instanceof Namespace)) return false; return equals((Namespace)obj); } @Override public int hashCode() { return uri().hashCode(); } @Override protected Object equivalentValues(Object value) { if (!(value instanceof Namespace)) return Scriptable.NOT_FOUND; boolean result = equals((Namespace)value); return result ? Boolean.TRUE : Boolean.FALSE; } @Override public String getClassName() { return "Namespace"; } @Override public Object getDefaultValue(Class hint) { return uri(); } // #string_id_map# private static final int Id_prefix = 1, Id_uri = 2, MAX_INSTANCE_ID = 2; @Override protected int getMaxInstanceId() { return super.getMaxInstanceId() + MAX_INSTANCE_ID; } @Override protected int findInstanceIdInfo(String s) { int id; // #generated# Last update: 2007-08-20 08:23:22 EDT L0: { id = 0; String X = null; int s_length = s.length(); if (s_length==3) { X="uri";id=Id_uri; } else if (s_length==6) { X="prefix";id=Id_prefix; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# if (id == 0) return super.findInstanceIdInfo(s); int attr; switch (id) { case Id_prefix: case Id_uri: attr = PERMANENT | READONLY; break; default: throw new IllegalStateException(); } return instanceIdInfo(attr, super.getMaxInstanceId() + id); } // #/string_id_map# @Override protected String getInstanceIdName(int id) { switch (id - super.getMaxInstanceId()) { case Id_prefix: return "prefix"; case Id_uri: return "uri"; } return super.getInstanceIdName(id); } @Override protected Object getInstanceIdValue(int id) { switch (id - super.getMaxInstanceId()) { case Id_prefix: if (ns.getPrefix() == null) return Undefined.instance; return ns.getPrefix(); case Id_uri: return ns.getUri(); } return super.getInstanceIdValue(id); } // #string_id_map# private static final int Id_constructor = 1, Id_toString = 2, Id_toSource = 3, MAX_PROTOTYPE_ID = 3; @Override protected int findPrototypeId(String s) { int id; // #generated# Last update: 2007-08-20 08:23:22 EDT L0: { id = 0; String X = null; int c; int s_length = s.length(); if (s_length==8) { c=s.charAt(3); if (c=='o') { X="toSource";id=Id_toSource; } else if (c=='t') { X="toString";id=Id_toString; } } else if (s_length==11) { X="constructor";id=Id_constructor; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# return id; } // #/string_id_map# @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=2; s="constructor"; break; case Id_toString: arity=0; s="toString"; break; case Id_toSource: arity=0; s="toSource"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(NAMESPACE_TAG, id, s, arity); } @Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(NAMESPACE_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); switch (id) { case Id_constructor: return jsConstructor(cx, (thisObj == null), args); case Id_toString: return realThis(thisObj, f).toString(); case Id_toSource: return realThis(thisObj, f).js_toSource(); } throw new IllegalArgumentException(String.valueOf(id)); } private Namespace realThis(Scriptable thisObj, IdFunctionObject f) { if(!(thisObj instanceof Namespace)) throw incompatibleCallError(f); return (Namespace)thisObj; } Namespace newNamespace(String uri) { Namespace prototype = (this.prototype == null) ? this : this.prototype; return create( this.getParentScope(), prototype, XmlNode.Namespace.create(uri) ); } Namespace newNamespace(String prefix, String uri) { if (prefix == null) return newNamespace(uri); Namespace prototype = (this.prototype == null) ? this : this.prototype; return create( this.getParentScope(), prototype, XmlNode.Namespace.create(prefix, uri) ); } Namespace constructNamespace(Object uriValue) { String prefix; String uri; if (uriValue instanceof Namespace) { Namespace ns = (Namespace)uriValue; prefix = ns.prefix(); uri = ns.uri(); } else if (uriValue instanceof QName) { QName qname = (QName)uriValue; uri = qname.uri(); if (uri != null) { // TODO Is there a way to push this back into QName so that we can make prefix() private? prefix = qname.prefix(); } else { uri = qname.toString(); prefix = null; } } else { uri = ScriptRuntime.toString(uriValue); prefix = (uri.length() == 0) ? "" : null; } return newNamespace(prefix, uri); } Namespace castToNamespace(Object namespaceObj) { if (namespaceObj instanceof Namespace) { return (Namespace)namespaceObj; } return constructNamespace(namespaceObj); } private Namespace constructNamespace(Object prefixValue, Object uriValue) { String prefix; String uri; if (uriValue instanceof QName) { QName qname = (QName)uriValue; uri = qname.uri(); if (uri == null) { uri = qname.toString(); } } else { uri = ScriptRuntime.toString(uriValue); } if (uri.length() == 0) { if (prefixValue == Undefined.instance) { prefix = ""; } else { prefix = ScriptRuntime.toString(prefixValue); if (prefix.length() != 0) { throw ScriptRuntime.typeError( "Illegal prefix '"+prefix+"' for 'no namespace'."); } } } else if (prefixValue == Undefined.instance) { prefix = ""; } else if (!XMLName.accept(prefixValue)) { prefix = ""; } else { prefix = ScriptRuntime.toString(prefixValue); } return newNamespace(prefix, uri); } private Namespace constructNamespace() { return newNamespace("", ""); } private Object jsConstructor(Context cx, boolean inNewExpr, Object[] args) { if (!inNewExpr && args.length == 1) { return castToNamespace(args[0]); } if (args.length == 0) { return constructNamespace(); } else if (args.length == 1) { return constructNamespace(args[0]); } else { return constructNamespace(args[0], args[1]); } } private String js_toSource() { StringBuffer sb = new StringBuffer(); sb.append('('); toSourceImpl(ns.getPrefix(), ns.getUri(), sb); sb.append(')'); return sb.toString(); } static void toSourceImpl(String prefix, String uri, StringBuffer sb) { sb.append("new Namespace("); if (uri.length() == 0) { if (!"".equals(prefix)) throw new IllegalArgumentException(prefix); } else { sb.append('\''); if (prefix != null) { sb.append(ScriptRuntime.escapeString(prefix, '\'')); sb.append("', '"); } sb.append(ScriptRuntime.escapeString(uri, '\'')); sb.append('\''); } sb.append(')'); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XmlNode.java0000644000175000017500000007573111314263504035416 0ustar jamespagejamespage00000000000000/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino DOM-only E4X implementation. * * The Initial Developer of the Original Code is * David P. Caldwell. * Portions created by David P. Caldwell are Copyright (C) * 2007 David P. Caldwell. All Rights Reserved. * * * Contributor(s): * David P. Caldwell * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.mozilla.javascript.Undefined; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.UserDataHandler; class XmlNode implements Serializable { private static final String XML_NAMESPACES_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/"; private static final String USER_DATA_XMLNODE_KEY = XmlNode.class.getName(); private static final boolean DOM_LEVEL_3 = true; private static XmlNode getUserData(Node node) { if (DOM_LEVEL_3) { return (XmlNode)node.getUserData(USER_DATA_XMLNODE_KEY); } return null; } private static void setUserData(Node node, XmlNode wrap) { if (DOM_LEVEL_3) { node.setUserData(USER_DATA_XMLNODE_KEY, wrap, wrap.events); } } private static XmlNode createImpl(Node node) { if (node instanceof Document) throw new IllegalArgumentException(); XmlNode rv = null; if (getUserData(node) == null) { rv = new XmlNode(); rv.dom = node; setUserData(node, rv); } else { rv = getUserData(node); } return rv; } static XmlNode newElementWithText(XmlProcessor processor, XmlNode reference, XmlNode.QName qname, String value) { if (reference instanceof org.w3c.dom.Document) throw new IllegalArgumentException("Cannot use Document node as reference"); Document document = null; if (reference != null) { document = reference.dom.getOwnerDocument(); } else { document = processor.newDocument(); } Node referenceDom = (reference != null) ? reference.dom : null; Namespace ns = qname.getNamespace(); Element e = (ns == null || ns.getUri().length() == 0) ? document.createElementNS(null, qname.getLocalName()) : document.createElementNS(ns.getUri(), qname.qualify(referenceDom)); if (value != null) { e.appendChild(document.createTextNode(value)); } return XmlNode.createImpl(e); } static XmlNode createText(XmlProcessor processor, String value) { return createImpl( processor.newDocument().createTextNode(value) ); } static XmlNode createElementFromNode(Node node) { if (node instanceof Document) node = ((Document) node).getDocumentElement(); return createImpl(node); } static XmlNode createElement(XmlProcessor processor, String namespaceUri, String xml) throws org.xml.sax.SAXException { return createImpl( processor.toXml(namespaceUri, xml) ); } static XmlNode createEmpty(XmlProcessor processor) { return createText(processor, ""); } private static XmlNode copy(XmlNode other) { return createImpl( other.dom.cloneNode(true) ); } private static final long serialVersionUID = 1L; private UserDataHandler events = new XmlNodeUserDataHandler(); private Node dom; private XML xml; private XmlNode() { } String debug() { XmlProcessor raw = new XmlProcessor(); raw.setIgnoreComments(false); raw.setIgnoreProcessingInstructions(false); raw.setIgnoreWhitespace(false); raw.setPrettyPrinting(false); return raw.ecmaToXmlString(this.dom); } @Override public String toString() { return "XmlNode: type=" + dom.getNodeType() + " dom=" + dom.toString(); } XML getXml() { return xml; } void setXml(XML xml) { this.xml = xml; } int getChildCount() { return this.dom.getChildNodes().getLength(); } XmlNode parent() { Node domParent = dom.getParentNode(); if (domParent instanceof Document) return null; if (domParent == null) return null; return createImpl(domParent); } int getChildIndex() { if (this.isAttributeType()) return -1; if (parent() == null) return -1; org.w3c.dom.NodeList siblings = this.dom.getParentNode().getChildNodes(); for (int i=0; i map = new HashMap(); private Map uriToPrefix = new HashMap(); Namespaces() { } void declare(Namespace n) { if (map.get(n.prefix) == null) { map.put(n.prefix, n.uri); } // TODO I think this is analogous to the other way, but have not really thought it through ... should local scope // matter more than outer scope? if (uriToPrefix.get(n.uri) == null) { uriToPrefix.put(n.uri, n.prefix); } } Namespace getNamespaceByUri(String uri) { if (uriToPrefix.get(uri) == null) return null; return Namespace.create(uri, uriToPrefix.get(uri)); } Namespace getNamespace(String prefix) { if (map.get(prefix) == null) return null; return Namespace.create(prefix, map.get(prefix)); } Namespace[] getNamespaces() { ArrayList rv = new ArrayList(); for (String prefix: map.keySet()) { String uri = map.get(prefix); Namespace n = Namespace.create(prefix, uri); if (!n.isEmpty()) { rv.add(n); } } return rv.toArray(new Namespace[rv.size()]); } } final XmlNode copy() { return copy( this ); } // Returns whether this node is capable of being a parent final boolean isParentType() { return isElementType(); } final boolean isTextType() { return dom.getNodeType() == Node.TEXT_NODE || dom.getNodeType() == Node.CDATA_SECTION_NODE; } final boolean isAttributeType() { return dom.getNodeType() == Node.ATTRIBUTE_NODE; } final boolean isProcessingInstructionType() { return dom.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE; } final boolean isCommentType() { return dom.getNodeType() == Node.COMMENT_NODE; } final boolean isElementType() { return dom.getNodeType() == Node.ELEMENT_NODE; } final void renameNode(QName qname) { this.dom = dom.getOwnerDocument().renameNode(dom, qname.getNamespace().getUri(), qname.qualify(dom)); } void invalidateNamespacePrefix() { if (!(dom instanceof Element)) throw new IllegalStateException(); String prefix = this.dom.getPrefix(); QName after = QName.create(this.dom.getNamespaceURI(), this.dom.getLocalName(), null); renameNode(after); NamedNodeMap attrs = this.dom.getAttributes(); for (int i=0; i 0) { e.setAttributeNS(XML_NAMESPACES_NAMESPACE_URI, "xmlns:" + prefix, uri); } else { e.setAttribute("xmlns", uri); } } void declareNamespace(String prefix, String uri) { if (!(dom instanceof Element)) throw new IllegalStateException(); if (dom.lookupNamespaceURI(uri) != null && dom.lookupNamespaceURI(uri).equals(prefix)) { // do nothing } else { Element e = (Element)dom; declareNamespace(e, prefix, uri); } } private Namespace getDefaultNamespace() { String prefix = ""; String uri = (dom.lookupNamespaceURI(null) == null) ? "" : dom.lookupNamespaceURI(null); return Namespace.create(prefix, uri); } private String getExistingPrefixFor(Namespace namespace) { if (getDefaultNamespace().getUri().equals(namespace.getUri())) { return ""; } return dom.lookupPrefix(namespace.getUri()); } private Namespace getNodeNamespace() { String uri = dom.getNamespaceURI(); String prefix = dom.getPrefix(); if (uri == null) uri = ""; if (prefix == null) prefix = ""; return Namespace.create(prefix, uri); } Namespace getNamespace() { return getNodeNamespace(); } void removeNamespace(Namespace namespace) { Namespace current = getNodeNamespace(); // Do not remove in-use namespace if (namespace.is(current)) return; NamedNodeMap attrs = this.dom.getAttributes(); for (int i=0; i rv = new ArrayList(); NodeList nodes = this.dom.getChildNodes(); for (int i=0; i 0) return prefix + ":" + localName; return localName; } private Namespace namespace; private String localName; private QName() { } @Override public String toString() { return "XmlNode.QName [" + localName + "," + namespace + "]"; } private boolean equals(String one, String two) { if (one == null && two == null) return true; if (one == null || two == null) return false; return one.equals(two); } private boolean namespacesEqual(Namespace one, Namespace two) { if (one == null && two == null) return true; if (one == null || two == null) return false; return equals(one.getUri(), two.getUri()); } final boolean equals(QName other) { if (!namespacesEqual(this.namespace, other.namespace)) return false; if (!equals(this.localName, other.localName)) return false; return true; } @Override public boolean equals(Object obj) { if(!(obj instanceof QName)) { return false; } return equals((QName)obj); } @Override public int hashCode() { return localName == null ? 0 : localName.hashCode(); } void lookupPrefix(org.w3c.dom.Node node) { if (node == null) throw new IllegalArgumentException("node must not be null"); String prefix = node.lookupPrefix(namespace.getUri()); if (prefix == null) { // check to see if we match the default namespace String defaultNamespace = node.lookupNamespaceURI(null); if (defaultNamespace == null) defaultNamespace = ""; String nodeNamespace = namespace.getUri(); if (nodeNamespace.equals(defaultNamespace)) { prefix = ""; } } int i = 0; while(prefix == null) { String generatedPrefix = "e4x_" + i++; String generatedUri = node.lookupNamespaceURI(generatedPrefix); if (generatedUri == null) { prefix = generatedPrefix; org.w3c.dom.Node top = node; while(top.getParentNode() != null && top.getParentNode() instanceof org.w3c.dom.Element) { top = top.getParentNode(); } ((org.w3c.dom.Element)top).setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + prefix, namespace.getUri()); } } namespace.setPrefix(prefix); } String qualify(org.w3c.dom.Node node) { if (namespace.getPrefix() == null) { if (node != null) { lookupPrefix(node); } else { if (namespace.getUri().equals("")) { namespace.setPrefix(""); } else { // TODO I am not sure this is right, but if we are creating a standalone node, I think we can set the // default namespace on the node itself and not worry about setting a prefix for that namespace. namespace.setPrefix(""); } } } return qualify(namespace.getPrefix(), localName); } void setAttribute(org.w3c.dom.Element element, String value) { if (namespace.getPrefix() == null) lookupPrefix(element); element.setAttributeNS(namespace.getUri(), qualify(namespace.getPrefix(), localName), value); } Namespace getNamespace() { return namespace; } String getLocalName() { return localName; } } static class InternalList implements Serializable { private static final long serialVersionUID = -3633151157292048978L; private List list; InternalList() { list = new ArrayList(); } private void _add(XmlNode n) { list.add(n); } XmlNode item(int index) { return list.get(index); } void remove(int index) { list.remove(index); } void add(InternalList other) { for (int i=0; i * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.List; import java.util.ArrayList; import org.mozilla.javascript.*; // Disambiguate from org.mozilla.javascript.Node import org.w3c.dom.Node; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; class XmlProcessor implements Serializable { private static final long serialVersionUID = 6903514433204808713L; private boolean ignoreComments; private boolean ignoreProcessingInstructions; private boolean ignoreWhitespace; private boolean prettyPrint; private int prettyIndent; private transient javax.xml.parsers.DocumentBuilderFactory dom; private transient javax.xml.transform.TransformerFactory xform; private transient DocumentBuilder documentBuilder; private RhinoSAXErrorHandler errorHandler = new RhinoSAXErrorHandler(); private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.dom = javax.xml.parsers.DocumentBuilderFactory.newInstance(); this.dom.setNamespaceAware(true); this.dom.setIgnoringComments(false); this.xform = javax.xml.transform.TransformerFactory.newInstance(); } private static class RhinoSAXErrorHandler implements ErrorHandler, Serializable { private static final long serialVersionUID = 6918417235413084055L; private void throwError(SAXParseException e) { throw ScriptRuntime.constructError("TypeError", e.getMessage(), e.getLineNumber() - 1); } public void error(SAXParseException e) { throwError(e); } public void fatalError(SAXParseException e) { throwError(e); } public void warning(SAXParseException e) { Context.reportWarning(e.getMessage()); } } XmlProcessor() { setDefault(); this.dom = javax.xml.parsers.DocumentBuilderFactory.newInstance(); this.dom.setNamespaceAware(true); this.dom.setIgnoringComments(false); this.xform = javax.xml.transform.TransformerFactory.newInstance(); } final void setDefault() { this.setIgnoreComments(true); this.setIgnoreProcessingInstructions(true); this.setIgnoreWhitespace(true); this.setPrettyPrinting(true); this.setPrettyIndent(2); } final void setIgnoreComments(boolean b) { this.ignoreComments = b; } final void setIgnoreWhitespace(boolean b) { this.ignoreWhitespace = b; } final void setIgnoreProcessingInstructions(boolean b) { this.ignoreProcessingInstructions = b; } final void setPrettyPrinting(boolean b) { this.prettyPrint = b; } final void setPrettyIndent(int i) { this.prettyIndent = i; } final boolean isIgnoreComments() { return ignoreComments; } final boolean isIgnoreProcessingInstructions() { return ignoreProcessingInstructions; } final boolean isIgnoreWhitespace() { return ignoreWhitespace; } final boolean isPrettyPrinting() { return prettyPrint; } final int getPrettyIndent() { return prettyIndent; } private String toXmlNewlines(String rv) { StringBuffer nl = new StringBuffer(); for (int i=0; i list, Node node) { if (node instanceof ProcessingInstruction) { list.add(node); } if (node.getChildNodes() != null) { for (int i=0; i list, Node node) { if (node instanceof Comment) { list.add(node); } if (node.getChildNodes() != null) { for (int i=0; i toRemove, Node node) { if (node instanceof Text) { Text text = (Text)node; boolean BUG_369394_IS_VALID = false; if (!BUG_369394_IS_VALID) { text.setData(text.getData().trim()); } else { if (text.getData().trim().length() == 0) { text.setData(""); } } if (text.getData().length() == 0) { toRemove.add(node); } } if (node.getChildNodes() != null) { for (int i=0; i" + xml + ""; builder = getDocumentBuilderFromPool(); Document document = builder.parse( new org.xml.sax.InputSource(new java.io.StringReader(syntheticXml)) ); if (ignoreProcessingInstructions) { List list = new java.util.ArrayList(); addProcessingInstructionsTo(list, document); for (Node node: list) { node.getParentNode().removeChild(node); } } if (ignoreComments) { List list = new java.util.ArrayList(); addCommentsTo(list, document); for (Node node: list) { node.getParentNode().removeChild(node); } } if (ignoreWhitespace) { // Apparently JAXP setIgnoringElementContentWhitespace() has a different meaning, it appears from the Javadoc // Refers to element-only content models, which means we would need to have a validating parser and DTD or schema // so that it would know which whitespace to ignore. // Instead we will try to delete it ourselves. List list = new java.util.ArrayList(); addTextNodesToRemoveAndTrim(list, document); for (Node node: list) { node.getParentNode().removeChild(node); } } NodeList rv = document.getDocumentElement().getChildNodes(); if (rv.getLength() > 1) { throw ScriptRuntime.constructError("SyntaxError", "XML objects may contain at most one node."); } else if (rv.getLength() == 0) { Node node = document.createTextNode(""); return node; } else { Node node = rv.item(0); document.getDocumentElement().removeChild(node); return node; } } catch (java.io.IOException e) { throw new RuntimeException("Unreachable."); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new RuntimeException(e); } finally { if (builder != null) returnDocumentBuilderToPool(builder); } } Document newDocument() { DocumentBuilder builder = null; try { // TODO Should this use XML settings? builder = getDocumentBuilderFromPool(); return builder.newDocument(); } catch (javax.xml.parsers.ParserConfigurationException ex) { // TODO How to handle these runtime errors? throw new RuntimeException(ex); } finally { if (builder != null) returnDocumentBuilderToPool(builder); } } // TODO Cannot remember what this is for, so whether it should use settings or not private String toString(Node node) { javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(node); java.io.StringWriter writer = new java.io.StringWriter(); javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(writer); try { javax.xml.transform.Transformer transformer = xform.newTransformer(); transformer.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "no"); transformer.setOutputProperty(javax.xml.transform.OutputKeys.METHOD, "xml"); transformer.transform(source, result); } catch (javax.xml.transform.TransformerConfigurationException ex) { // TODO How to handle these runtime errors? throw new RuntimeException(ex); } catch (javax.xml.transform.TransformerException ex) { // TODO How to handle these runtime errors? throw new RuntimeException(ex); } return toXmlNewlines(writer.toString()); } String escapeAttributeValue(Object value) { String text = ScriptRuntime.toString(value); if (text.length() == 0) return ""; Document dom = newDocument(); Element e = dom.createElement("a"); e.setAttribute("b", text); String elementText = toString(e); int begin = elementText.indexOf('"'); int end = elementText.lastIndexOf('"'); return elementText.substring(begin+1,end); } String escapeTextValue(Object value) { if (value instanceof XMLObjectImpl) { return ((XMLObjectImpl)value).toXMLString(); } String text = ScriptRuntime.toString(value); if (text.length() == 0) return text; Document dom = newDocument(); Element e = dom.createElement("a"); e.setTextContent(text); String elementText = toString(e); int begin = elementText.indexOf('>') + 1; int end = elementText.lastIndexOf('<'); return (begin < end) ? elementText.substring(begin, end) : ""; } private String escapeElementValue(String s) { // TODO Check this return escapeTextValue(s); } private String elementToXmlString(Element element) { // TODO My goodness ECMA is complicated (see 10.2.1). We'll try this first. Element copy = (Element)element.cloneNode(true); if (prettyPrint) { beautifyElement(copy, 0); } return toString(copy); } final String ecmaToXmlString(Node node) { // See ECMA 357 Section 10.2.1 StringBuffer s = new StringBuffer(); int indentLevel = 0; if (prettyPrint) { for (int i=0; i"); return s.toString(); } if (node instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction)node; s.append(""); return s.toString(); } s.append(elementToXmlString((Element)node)); return s.toString(); } private void beautifyElement(Element e, int indent) { StringBuffer s = new StringBuffer(); s.append('\n'); for (int i=0; i toIndent = new ArrayList(); boolean indentChildren = false; for (int i=0; i list = new ArrayList(); for (int i=0; i < nodes.getLength(); i++) { if (nodes.item(i) instanceof Element) { list.add((Element)nodes.item(i)); } } for (Element elem: list) { beautifyElement(elem, indent + prettyIndent); } if (indentChildren) { e.appendChild(e.getOwnerDocument().createTextNode(afterContent)); } } } ././@LongLink0000000000000000000000000000014600000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLLibImpl.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLLibImpl.jav0000644000175000017500000005411511314263504035611 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * David P. Caldwell * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import java.io.Serializable; import org.mozilla.javascript.*; import org.mozilla.javascript.xml.*; public final class XMLLibImpl extends XMLLib implements Serializable { private static final long serialVersionUID = 1L; // // EXPERIMENTAL Java interface // /** This experimental interface is undocumented. */ public static org.w3c.dom.Node toDomNode(Object xmlObject) { // Could return DocumentFragment for XMLList // Probably a single node for XMLList with one element if (xmlObject instanceof XML) { return ((XML)xmlObject).toDomNode(); } else { throw new IllegalArgumentException( "xmlObject is not an XML object in JavaScript."); } } public static void init(Context cx, Scriptable scope, boolean sealed) { XMLLibImpl lib = new XMLLibImpl(scope); XMLLib bound = lib.bindToScope(scope); if (bound == lib) { lib.exportToScope(sealed); } } public void setIgnoreComments(boolean b) { options.setIgnoreComments(b); } public void setIgnoreWhitespace(boolean b) { options.setIgnoreWhitespace(b); } public void setIgnoreProcessingInstructions(boolean b) { options.setIgnoreProcessingInstructions(b); } public void setPrettyPrinting(boolean b) { options.setPrettyPrinting(b); } public void setPrettyIndent(int i) { options.setPrettyIndent(i); } public boolean isIgnoreComments() { return options.isIgnoreComments(); } public boolean isIgnoreProcessingInstructions() { return options.isIgnoreProcessingInstructions(); } public boolean isIgnoreWhitespace() { return options.isIgnoreWhitespace(); } public boolean isPrettyPrinting() { return options.isPrettyPrinting(); } public int getPrettyIndent() { return options.getPrettyIndent(); } private Scriptable globalScope; private XML xmlPrototype; private XMLList xmlListPrototype; private Namespace namespacePrototype; private QName qnamePrototype; private XmlProcessor options = new XmlProcessor(); private XMLLibImpl(Scriptable globalScope) { this.globalScope = globalScope; } /** @deprecated */ QName qnamePrototype() { return qnamePrototype; } /** @deprecated */ Scriptable globalScope() { return globalScope; } XmlProcessor getProcessor() { return options; } private void exportToScope(boolean sealed) { xmlPrototype = newXML(XmlNode.createText(options, "")); xmlListPrototype = newXMLList(); namespacePrototype = Namespace.create(this.globalScope, null, XmlNode.Namespace.GLOBAL); qnamePrototype = QName.create(this, this.globalScope, null, XmlNode.QName.create(XmlNode.Namespace.create(""), "")); xmlPrototype.exportAsJSClass(sealed); xmlListPrototype.exportAsJSClass(sealed); namespacePrototype.exportAsJSClass(sealed); qnamePrototype.exportAsJSClass(sealed); } /** @deprecated */ XMLName toAttributeName(Context cx, Object nameValue) { if (nameValue instanceof XMLName) { // TODO Will this always be an XMLName of type attribute name? return (XMLName)nameValue; } else if (nameValue instanceof QName) { return XMLName.create( ((QName)nameValue).getDelegate(), true, false ); } else if (nameValue instanceof Boolean || nameValue instanceof Number || nameValue == Undefined.instance || nameValue == null) { throw badXMLName(nameValue); } else { // TODO Not 100% sure that putting these in global namespace is the right thing to do String localName = null; if (nameValue instanceof String) { localName = (String)nameValue; } else { localName = ScriptRuntime.toString(nameValue); } if (localName != null && localName.equals("*")) localName = null; return XMLName.create(XmlNode.QName.create(XmlNode.Namespace.create(""), localName), true, false); } } private static RuntimeException badXMLName(Object value) { String msg; if (value instanceof Number) { msg = "Can not construct XML name from number: "; } else if (value instanceof Boolean) { msg = "Can not construct XML name from boolean: "; } else if (value == Undefined.instance || value == null) { msg = "Can not construct XML name from "; } else { throw new IllegalArgumentException(value.toString()); } return ScriptRuntime.typeError(msg+ScriptRuntime.toString(value)); } XMLName toXMLNameFromString(Context cx, String name) { return XMLName.create(getDefaultNamespaceURI(cx), name); } /* TODO: Marked deprecated by original author */ XMLName toXMLName(Context cx, Object nameValue) { XMLName result; if (nameValue instanceof XMLName) { result = (XMLName)nameValue; } else if (nameValue instanceof QName) { QName qname = (QName)nameValue; result = XMLName.formProperty(qname.uri(), qname.localName()); } else if (nameValue instanceof String) { result = toXMLNameFromString(cx, (String)nameValue); } else if (nameValue instanceof Boolean || nameValue instanceof Number || nameValue == Undefined.instance || nameValue == null) { throw badXMLName(nameValue); } else { String name = ScriptRuntime.toString(nameValue); result = toXMLNameFromString(cx, name); } return result; } /** * If value represents Uint32 index, make it available through * ScriptRuntime.lastUint32Result(cx) and return null. * Otherwise return the same value as toXMLName(cx, value). */ XMLName toXMLNameOrIndex(Context cx, Object value) { XMLName result; if (value instanceof XMLName) { result = (XMLName)value; } else if (value instanceof String) { String str = (String)value; long test = ScriptRuntime.testUint32String(str); if (test >= 0) { ScriptRuntime.storeUint32Result(cx, test); result = null; } else { result = toXMLNameFromString(cx, str); } } else if (value instanceof Number) { double d = ((Number)value).doubleValue(); long l = (long)d; if (l == d && 0 <= l && l <= 0xFFFFFFFFL) { ScriptRuntime.storeUint32Result(cx, l); result = null; } else { throw badXMLName(value); } } else if (value instanceof QName) { QName qname = (QName)value; String uri = qname.uri(); boolean number = false; result = null; if (uri != null && uri.length() == 0) { // Only in this case qname.toString() can resemble uint32 long test = ScriptRuntime.testUint32String(uri); if (test >= 0) { ScriptRuntime.storeUint32Result(cx, test); number = true; } } if (!number) { result = XMLName.formProperty(uri, qname.localName()); } } else if (value instanceof Boolean || value == Undefined.instance || value == null) { throw badXMLName(value); } else { String str = ScriptRuntime.toString(value); long test = ScriptRuntime.testUint32String(str); if (test >= 0) { ScriptRuntime.storeUint32Result(cx, test); result = null; } else { result = toXMLNameFromString(cx, str); } } return result; } Object addXMLObjects(Context cx, XMLObject obj1, XMLObject obj2) { XMLList listToAdd = newXMLList(); if (obj1 instanceof XMLList) { XMLList list1 = (XMLList)obj1; if (list1.length() == 1) { listToAdd.addToList(list1.item(0)); } else { // Might be xmlFragment + xmlFragment + xmlFragment + ...; // then the result will be an XMLList which we want to be an // rValue and allow it to be assigned to an lvalue. listToAdd = newXMLListFrom(obj1); } } else { listToAdd.addToList(obj1); } if (obj2 instanceof XMLList) { XMLList list2 = (XMLList)obj2; for (int i = 0; i < list2.length(); i++) { listToAdd.addToList(list2.item(i)); } } else if (obj2 instanceof XML) { listToAdd.addToList(obj2); } return listToAdd; } private Ref xmlPrimaryReference(Context cx, XMLName xmlName, Scriptable scope) { XMLObjectImpl xmlObj; XMLObjectImpl firstXml = null; for (;;) { // XML object can only present on scope chain as a wrapper // of XMLWithScope if (scope instanceof XMLWithScope) { xmlObj = (XMLObjectImpl)scope.getPrototype(); if (xmlObj.hasXMLProperty(xmlName)) { break; } if (firstXml == null) { firstXml = xmlObj; } } scope = scope.getParentScope(); if (scope == null) { xmlObj = firstXml; break; } } // xmlObj == null corresponds to undefined as the target of // the reference if (xmlObj != null) { xmlName.initXMLObject(xmlObj); } return xmlName; } Namespace castToNamespace(Context cx, Object namespaceObj) { return this.namespacePrototype.castToNamespace(namespaceObj); } private String getDefaultNamespaceURI(Context cx) { return getDefaultNamespace(cx).uri(); } Namespace newNamespace(String uri) { return this.namespacePrototype.newNamespace(uri); } Namespace getDefaultNamespace(Context cx) { if (cx == null) { cx = Context.getCurrentContext(); if (cx == null) { return namespacePrototype; } } Object ns = ScriptRuntime.searchDefaultNamespace(cx); if (ns == null) { return namespacePrototype; } else { if (ns instanceof Namespace) { return (Namespace)ns; } else { // TODO Clarify or remove the following comment // Should not happen but for now it could // due to bad searchDefaultNamespace implementation. return namespacePrototype; } } } Namespace[] createNamespaces(XmlNode.Namespace[] declarations) { Namespace[] rv = new Namespace[declarations.length]; for (int i=0; i")) { throw ScriptRuntime.typeError("Invalid use of XML object anonymous tags <>."); } if (frag.indexOf("<") == -1) { // Solo text node return newXML(XmlNode.createText(options, frag)); } return parse(frag); } private XML parse(String frag) { try { return newXML(XmlNode.createElement(options, getDefaultNamespaceURI(Context.getCurrentContext()), frag)); } catch (org.xml.sax.SAXException e) { throw ScriptRuntime.typeError("Cannot parse XML: " + e.getMessage()); } } final XML ecmaToXml(Object object) { // See ECMA357 10.3 if (object == null || object == Undefined.instance) throw ScriptRuntime.typeError("Cannot convert " + object + " to XML"); if (object instanceof XML) return (XML)object; if (object instanceof XMLList) { XMLList list = (XMLList)object; if (list.getXML() != null) { return list.getXML(); } else { throw ScriptRuntime.typeError("Cannot convert list of >1 element to XML"); } } // TODO Technically we should fail on anything except a String, Number or Boolean // See ECMA357 10.3 // Extension: if object is a DOM node, use that to construct the XML // object. if (object instanceof Wrapper) { object = ((Wrapper) object).unwrap(); } if (object instanceof org.w3c.dom.Node) { org.w3c.dom.Node node = (org.w3c.dom.Node) object; return newXML(XmlNode.createElementFromNode(node)); } // Instead we just blindly cast to a String and let them convert anything. String s = ScriptRuntime.toString(object); // TODO Could this get any uglier? if (s.length() > 0 && s.charAt(0) == '<') { return parse(s); } else { return newXML(XmlNode.createText(options, s)); } } final XML newTextElementXML(XmlNode reference, XmlNode.QName qname, String value) { return newXML(XmlNode.newElementWithText(options, reference, qname, value)); } XMLList newXMLList() { return new XMLList(this, this.globalScope, this.xmlListPrototype); } final XMLList newXMLListFrom(Object inputObject) { XMLList rv = newXMLList(); if (inputObject == null || inputObject instanceof Undefined) { return rv; } else if (inputObject instanceof XML) { XML xml = (XML) inputObject; rv.getNodeList().add(xml); return rv; } else if (inputObject instanceof XMLList) { XMLList xmll = (XMLList) inputObject; rv.getNodeList().add(xmll.getNodeList()); return rv; } else { String frag = ScriptRuntime.toString(inputObject).trim(); if (!frag.startsWith("<>")) { frag = "<>" + frag + ""; } frag = "" + frag.substring(2); if (!frag.endsWith("")) { throw ScriptRuntime.typeError("XML with anonymous tag missing end anonymous tag"); } frag = frag.substring(0, frag.length() - 3) + ""; XML orgXML = newXMLFromJs(frag); // Now orphan the children and add them to our XMLList. XMLList children = orgXML.children(); for (int i = 0; i < children.getNodeList().length(); i++) { // Copy here is so that they'll be orphaned (parent() will be undefined) rv.getNodeList().add(((XML) children.item(i).copy())); } return rv; } } XmlNode.QName toNodeQName(Context cx, Object namespaceValue, Object nameValue) { // This is duplication of constructQName(cx, namespaceValue, nameValue) // but for XMLName String localName; if (nameValue instanceof QName) { QName qname = (QName)nameValue; localName = qname.localName(); } else { localName = ScriptRuntime.toString(nameValue); } XmlNode.Namespace ns; if (namespaceValue == Undefined.instance) { if ("*".equals(localName)) { ns = null; } else { ns = getDefaultNamespace(cx).getDelegate(); } } else if (namespaceValue == null) { ns = null; } else if (namespaceValue instanceof Namespace) { ns = ((Namespace)namespaceValue).getDelegate(); } else { ns = this.namespacePrototype.constructNamespace(namespaceValue).getDelegate(); } if (localName != null && localName.equals("*")) localName = null; return XmlNode.QName.create(ns, localName); } XmlNode.QName toNodeQName(Context cx, String name, boolean attribute) { XmlNode.Namespace defaultNamespace = getDefaultNamespace(cx).getDelegate(); if (name != null && name.equals("*")) { return XmlNode.QName.create(null, null); } else { if (attribute) { return XmlNode.QName.create(XmlNode.Namespace.GLOBAL, name); } else { return XmlNode.QName.create(defaultNamespace, name); } } } /* TODO: Too general; this should be split into overloaded methods. Is that possible? */ XmlNode.QName toNodeQName(Context cx, Object nameValue, boolean attribute) { if (nameValue instanceof XMLName) { return ((XMLName)nameValue).toQname(); } else if (nameValue instanceof QName) { QName qname = (QName)nameValue; return qname.getDelegate(); } else if ( nameValue instanceof Boolean || nameValue instanceof Number || nameValue == Undefined.instance || nameValue == null ) { throw badXMLName(nameValue); } else { String local = null; if (nameValue instanceof String) { local = (String)nameValue; } else { local = ScriptRuntime.toString(nameValue); } return toNodeQName(cx, local, attribute); } } // // Override methods from XMLLib // @Override public boolean isXMLName(Context _cx, Object nameObj) { return XMLName.accept(nameObj); } @Override public Object toDefaultXmlNamespace(Context cx, Object uriValue) { return this.namespacePrototype.constructNamespace(uriValue); } @Override public String escapeTextValue(Object o) { return options.escapeTextValue(o); } @Override public String escapeAttributeValue(Object o) { return options.escapeAttributeValue(o); } @Override public Ref nameRef(Context cx, Object name, Scriptable scope, int memberTypeFlags) { if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) == 0) { // should only be called for cases like @name or @[expr] throw Kit.codeBug(); } XMLName xmlName = toAttributeName(cx, name); return xmlPrimaryReference(cx, xmlName, scope); } @Override public Ref nameRef(Context cx, Object namespace, Object name, Scriptable scope, int memberTypeFlags) { XMLName xmlName = XMLName.create(toNodeQName(cx, namespace, name), false, false); // No idea what is coming in from the parser in this case; is it detecting the "@"? if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) != 0) { if (!xmlName.isAttributeName()) { xmlName.setAttributeName(); } } return xmlPrimaryReference(cx, xmlName, scope); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XML.java0000644000175000017500000005515011314263504034501 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ethan Hugg * Terry Lucas * Milen Nankov * David P. Caldwell * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import org.mozilla.javascript.*; import org.mozilla.javascript.xml.XMLObject; class XML extends XMLObjectImpl { static final long serialVersionUID = -630969919086449092L; private XmlNode node; XML(XMLLibImpl lib, Scriptable scope, XMLObject prototype, XmlNode node) { super(lib, scope, prototype); initialize(node); } void initialize(XmlNode node) { this.node = node; this.node.setXml(this); } @Override final XML getXML() { return this; } void replaceWith(XML value) { // We use the underlying document structure if the node is not // "standalone," but we need to just replace the XmlNode instance // otherwise if (this.node.parent() != null || false) { this.node.replaceWith(value.node); } else { this.initialize(value.node); } } /* TODO: needs encapsulation. */ XML makeXmlFromString(XMLName name, String value) { try { return newTextElementXML(this.node, name.toQname(), value); } catch(Exception e) { throw ScriptRuntime.typeError(e.getMessage()); } } /* TODO: Rename this, at the very least. But it's not clear it's even necessary */ XmlNode getAnnotation() { return node; } // // Methods from ScriptableObject // // TODO Either cross-reference this next comment with the specification or delete it and change the behavior // The comment: XML[0] should return this, all other indexes are Undefined @Override public Object get(int index, Scriptable start) { if (index == 0) { return this; } else { return Scriptable.NOT_FOUND; } } @Override public boolean has(int index, Scriptable start) { return (index == 0); } @Override public void put(int index, Scriptable start, Object value) { // TODO Clarify the following comment and add a reference to the spec // The comment: Spec says assignment to indexed XML object should return type error throw ScriptRuntime.typeError("Assignment to indexed XML is not allowed"); } @Override public Object[] getIds() { if (isPrototype()) { return new Object[0]; } else { return new Object[] { Integer.valueOf(0) }; } } // TODO This is how I found it but I am not sure it makes sense @Override public void delete(int index) { if (index == 0) { this.remove(); } } // // Methods from XMLObjectImpl // @Override boolean hasXMLProperty(XMLName xmlName) { if (isPrototype()) { return getMethod(xmlName.localName()) != NOT_FOUND; } else { return (getPropertyList(xmlName).length() > 0) || (getMethod(xmlName.localName()) != NOT_FOUND); } } @Override Object getXMLProperty(XMLName xmlName) { if (isPrototype()) { return getMethod(xmlName.localName()); } else { return getPropertyList(xmlName); } } // // // Methods that merit further review // // XmlNode.QName getNodeQname() { return this.node.getQname(); } XML[] getChildren() { if (!isElement()) return null; XmlNode[] children = this.node.getMatchingChildren(XmlNode.Filter.TRUE); XML[] rv = new XML[children.length]; for (int i=0; i 0); } return hasProperty; } @Override protected Object jsConstructor(Context cx, boolean inNewExpr, Object[] args) { if (args.length == 0 || args[0] == null || args[0] == Undefined.instance) { args = new Object[] { "" }; } // ECMA 13.4.2 does not appear to specify what to do if multiple arguments are sent. XML toXml = ecmaToXml(args[0]); if (inNewExpr) { return toXml.copy(); } else { return toXml; } } // See ECMA 357, 11_2_2_1, Semantics, 3_f. @Override public Scriptable getExtraMethodSource(Context cx) { if (hasSimpleContent()) { String src = toString(); return ScriptRuntime.toObjectOrNull(cx, src); } return null; } // // TODO Miscellaneous methods not yet grouped // void removeChild(int index) { this.node.removeChild(index); } @Override void normalize() { this.node.normalize(); } private XML toXML(XmlNode node) { if (node.getXml() == null) { node.setXml(newXML(node)); } return node.getXml(); } void setAttribute(XMLName xmlName, Object value) { if (!isElement()) throw new IllegalStateException("Can only set attributes on elements."); // TODO Is this legal, but just not "supported"? If so, support it. if (xmlName.uri() == null && xmlName.localName().equals("*")) { throw ScriptRuntime.typeError("@* assignment not supported."); } this.node.setAttribute(xmlName.toQname(), ScriptRuntime.toString(value)); } void remove() { this.node.deleteMe(); } @Override void addMatches(XMLList rv, XMLName name) { name.addMatches(rv, this); } @Override XMLList elements(XMLName name) { XMLList rv = newXMLList(); rv.setTargets(this, name.toQname()); // TODO Should have an XMLNode.Filter implementation based on XMLName XmlNode[] elements = this.node.getMatchingChildren(XmlNode.Filter.ELEMENT); for (int i=0; i= 0 && index < this.node.getChildCount()) { result.addToList(getXmlChild(index)); } return result; } XML getXmlChild(int index) { XmlNode child = this.node.getChild(index); if (child.getXml() == null) { child.setXml(newXML(child)); } return child.getXml(); } int childIndex() { return this.node.getChildIndex(); } @Override boolean contains(Object xml) { if (xml instanceof XML) { return equivalentXml(xml); } else { return false; } } // Method overriding XMLObjectImpl @Override boolean equivalentXml(Object target) { boolean result = false; if (target instanceof XML) { // TODO This is a horrifyingly inefficient way to do this so we should make it better. It may also not work. return this.node.toXmlString(getProcessor()).equals( ((XML)target).node.toXmlString(getProcessor()) ); } else if (target instanceof XMLList) { // TODO Is this right? Check the spec ... XMLList otherList = (XMLList) target; if (otherList.length() == 1) { result = equivalentXml(otherList.getXML()); } } else if (hasSimpleContent()) { String otherStr = ScriptRuntime.toString(target); result = toString().equals(otherStr); } return result; } @Override XMLObjectImpl copy() { return newXML( this.node.copy() ); } @Override boolean hasSimpleContent() { if (isComment() || isProcessingInstruction()) return false; if (isText() || this.node.isAttributeType()) return true; return !this.node.hasChildElement(); } @Override boolean hasComplexContent() { return !hasSimpleContent(); } // TODO Cross-reference comment below with spec // Comment is: Length of an XML object is always 1, it's a list of XML objects of size 1. @Override int length() { return 1; } // TODO it is not clear what this method was for ... boolean is(XML other) { return this.node.isSameNode(other.node); } Object nodeKind() { return ecmaClass(); } @Override Object parent() { XmlNode parent = this.node.parent(); if (parent == null) return null; return newXML(this.node.parent()); } @Override boolean propertyIsEnumerable(Object name) { boolean result; if (name instanceof Integer) { result = (((Integer)name).intValue() == 0); } else if (name instanceof Number) { double x = ((Number)name).doubleValue(); // Check that number is positive 0 result = (x == 0.0 && 1.0 / x > 0); } else { result = ScriptRuntime.toString(name).equals("0"); } return result; } @Override Object valueOf() { return this; } // // Selection of children // @Override XMLList comments() { XMLList rv = newXMLList(); this.node.addMatchingChildren(rv, XmlNode.Filter.COMMENT); return rv; } @Override XMLList text() { XMLList rv = newXMLList(); this.node.addMatchingChildren(rv, XmlNode.Filter.TEXT); return rv; } @Override XMLList processingInstructions(XMLName xmlName) { XMLList rv = newXMLList(); this.node.addMatchingChildren(rv, XmlNode.Filter.PROCESSING_INSTRUCTION(xmlName)); return rv; } // // Methods relating to modification of child nodes // // We create all the nodes we are inserting before doing the insert to // avoid nasty cycles caused by mutability of these objects. For example, // what if the toString() method of value modifies the XML object we were // going to insert into? insertAfter might get confused about where to // insert. This actually came up with SpiderMonkey, leading to a (very) // long discussion. See bug #354145. private XmlNode[] getNodesForInsert(Object value) { if (value instanceof XML) { return new XmlNode[] { ((XML)value).node }; } else if (value instanceof XMLList) { XMLList list = (XMLList)value; XmlNode[] rv = new XmlNode[list.length()]; for (int i=0; i 0) { // One exists an that index XML childToReplace = xlChildToReplace.item(0); insertChildAfter(childToReplace, xml); removeChild(index); } return this; } XML prependChild(Object xml) { if (this.node.isParentType()) { this.node.insertChildrenAt(0, getNodesForInsert(xml)); } return this; } XML appendChild(Object xml) { if (this.node.isParentType()) { XmlNode[] nodes = getNodesForInsert(xml); this.node.insertChildrenAt(this.node.getChildCount(), nodes); } return this; } private int getChildIndexOf(XML child) { for (int i=0; i 0) { this.node.removeChild(0); } XmlNode[] toInsert = getNodesForInsert(xml); // append new children this.node.insertChildrenAt(0, toInsert); return this; } // // Name and namespace-related methods // private void addInScopeNamespace(Namespace ns) { if (!isElement()) { return; } // See ECMA357 9.1.1.13 // in this implementation null prefix means ECMA undefined if (ns.prefix() != null) { if (ns.prefix().length() == 0 && ns.uri().length() == 0) { return; } if (node.getQname().getNamespace().getPrefix().equals(ns.prefix())) { node.invalidateNamespacePrefix(); } node.declareNamespace(ns.prefix(), ns.uri()); } else { return; } } Namespace[] inScopeNamespaces() { XmlNode.Namespace[] inScope = this.node.getInScopeNamespaces(); return createNamespaces(inScope); } private XmlNode.Namespace adapt(Namespace ns) { if (ns.prefix() == null) { return XmlNode.Namespace.create(ns.uri()); } else { return XmlNode.Namespace.create(ns.prefix(), ns.uri()); } } XML removeNamespace(Namespace ns) { if (!isElement()) return this; this.node.removeNamespace(adapt(ns)); return this; } XML addNamespace(Namespace ns) { addInScopeNamespace(ns); return this; } QName name() { if (isText() || isComment()) return null; if (isProcessingInstruction()) return newQName("", this.node.getQname().getLocalName(), null); return newQName(node.getQname()); } Namespace[] namespaceDeclarations() { XmlNode.Namespace[] declarations = node.getNamespaceDeclarations(); return createNamespaces(declarations); } Namespace namespace(String prefix) { if (prefix == null) { return createNamespace( this.node.getNamespaceDeclaration() ); } else { return createNamespace( this.node.getNamespaceDeclaration(prefix) ); } } String localName() { if (name() == null) return null; return name().localName(); } void setLocalName(String localName) { // ECMA357 13.4.4.34 if (isText() || isComment()) return; this.node.setLocalName(localName); } void setName(QName name) { // See ECMA357 13.4.4.35 if (isText() || isComment()) return; if (isProcessingInstruction()) { // Spec says set the name URI to empty string and then set the [[Name]] property, but I understand this to do the same // thing, unless we allow colons in processing instruction targets, which I think we do not. this.node.setLocalName(name.localName()); return; } node.renameNode(name.getDelegate()); } void setNamespace(Namespace ns) { // See ECMA357 13.4.4.36 if (isText() || isComment() || isProcessingInstruction()) return; setName(newQName(ns.uri(), localName(), ns.prefix())); } final String ecmaClass() { // See ECMA357 9.1 // TODO See ECMA357 9.1.1 last paragraph for what defaults should be if (node.isTextType()) { return "text"; } else if (node.isAttributeType()) { return "attribute"; } else if (node.isCommentType()) { return "comment"; } else if (node.isProcessingInstructionType()) { return "processing-instruction"; } else if (node.isElementType()) { return "element"; } else { throw new RuntimeException("Unrecognized type: " + node); } } @Override public String getClassName() { // TODO: This appears to confuse the interpreter if we use the "real" class property from ECMA. Otherwise this code // would be: // return ecmaClass(); return "XML"; } private String ecmaValue() { return node.ecmaValue(); } private String ecmaToString() { // See ECMA357 10.1.1 if (isAttribute() || isText()) { return ecmaValue(); } if (this.hasSimpleContent()) { StringBuffer rv = new StringBuffer(); for (int i=0; i < this.node.getChildCount(); i++) { XmlNode child = this.node.getChild(i); if (!child.isProcessingInstructionType() && !child.isCommentType()) { // TODO: Probably inefficient; taking clean non-optimized // solution for now XML x = new XML(getLib(), getParentScope(), (XMLObject)getPrototype(), child); rv.append(x.toString()); } } return rv.toString(); } return toXMLString(); } @Override public String toString() { return ecmaToString(); } @Override String toSource(int indent) { return toXMLString(); } @Override String toXMLString() { return this.node.ecmaToXMLString(getProcessor()); } final boolean isAttribute() { return node.isAttributeType(); } final boolean isComment() { return node.isCommentType(); } final boolean isText() { return node.isTextType(); } final boolean isElement() { return node.isElementType(); } final boolean isProcessingInstruction() { return node.isProcessingInstructionType(); } // Support experimental Java interface org.w3c.dom.Node toDomNode() { return node.toDomNode(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLCtor.java0000644000175000017500000002363611314263504035335 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * David P. Caldwell * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import org.mozilla.javascript.*; class XMLCtor extends IdFunctionObject { static final long serialVersionUID = -8708195078359817341L; private static final Object XMLCTOR_TAG = "XMLCtor"; private XmlProcessor options; // private XMLLibImpl lib; XMLCtor(XML xml, Object tag, int id, int arity) { super(xml, tag, id, arity); // this.lib = xml.lib; this.options = xml.getProcessor(); activatePrototypeMap(MAX_FUNCTION_ID); } private void writeSetting(Scriptable target) { for (int i = 1; i <= MAX_INSTANCE_ID; ++i) { int id = super.getMaxInstanceId() + i; String name = getInstanceIdName(id); Object value = getInstanceIdValue(id); ScriptableObject.putProperty(target, name, value); } } private void readSettings(Scriptable source) { for (int i = 1; i <= MAX_INSTANCE_ID; ++i) { int id = super.getMaxInstanceId() + i; String name = getInstanceIdName(id); Object value = ScriptableObject.getProperty(source, name); if (value == Scriptable.NOT_FOUND) { continue; } switch (i) { case Id_ignoreComments: case Id_ignoreProcessingInstructions: case Id_ignoreWhitespace: case Id_prettyPrinting: if (!(value instanceof Boolean)) { continue; } break; case Id_prettyIndent: if (!(value instanceof Number)) { continue; } break; default: throw new IllegalStateException(); } setInstanceIdValue(id, value); } } // #string_id_map# private static final int Id_ignoreComments = 1, Id_ignoreProcessingInstructions = 2, Id_ignoreWhitespace = 3, Id_prettyIndent = 4, Id_prettyPrinting = 5, MAX_INSTANCE_ID = 5; @Override protected int getMaxInstanceId() { return super.getMaxInstanceId() + MAX_INSTANCE_ID; } @Override protected int findInstanceIdInfo(String s) { int id; // #generated# Last update: 2007-08-20 09:01:10 EDT L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 12: X="prettyIndent";id=Id_prettyIndent; break L; case 14: c=s.charAt(0); if (c=='i') { X="ignoreComments";id=Id_ignoreComments; } else if (c=='p') { X="prettyPrinting";id=Id_prettyPrinting; } break L; case 16: X="ignoreWhitespace";id=Id_ignoreWhitespace; break L; case 28: X="ignoreProcessingInstructions";id=Id_ignoreProcessingInstructions; break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# if (id == 0) return super.findInstanceIdInfo(s); int attr; switch (id) { case Id_ignoreComments: case Id_ignoreProcessingInstructions: case Id_ignoreWhitespace: case Id_prettyIndent: case Id_prettyPrinting: attr = PERMANENT | DONTENUM; break; default: throw new IllegalStateException(); } return instanceIdInfo(attr, super.getMaxInstanceId() + id); } // #/string_id_map# @Override protected String getInstanceIdName(int id) { switch (id - super.getMaxInstanceId()) { case Id_ignoreComments: return "ignoreComments"; case Id_ignoreProcessingInstructions: return "ignoreProcessingInstructions"; case Id_ignoreWhitespace: return "ignoreWhitespace"; case Id_prettyIndent: return "prettyIndent"; case Id_prettyPrinting: return "prettyPrinting"; } return super.getInstanceIdName(id); } @Override protected Object getInstanceIdValue(int id) { switch (id - super.getMaxInstanceId()) { case Id_ignoreComments: return ScriptRuntime.wrapBoolean(options.isIgnoreComments()); case Id_ignoreProcessingInstructions: return ScriptRuntime.wrapBoolean(options.isIgnoreProcessingInstructions()); case Id_ignoreWhitespace: return ScriptRuntime.wrapBoolean(options.isIgnoreWhitespace()); case Id_prettyIndent: return ScriptRuntime.wrapInt(options.getPrettyIndent()); case Id_prettyPrinting: return ScriptRuntime.wrapBoolean(options.isPrettyPrinting()); } return super.getInstanceIdValue(id); } @Override protected void setInstanceIdValue(int id, Object value) { switch (id - super.getMaxInstanceId()) { case Id_ignoreComments: options.setIgnoreComments(ScriptRuntime.toBoolean(value)); return; case Id_ignoreProcessingInstructions: options.setIgnoreProcessingInstructions(ScriptRuntime.toBoolean(value)); return; case Id_ignoreWhitespace: options.setIgnoreWhitespace(ScriptRuntime.toBoolean(value)); return; case Id_prettyIndent: options.setPrettyIndent(ScriptRuntime.toInt32(value)); return; case Id_prettyPrinting: options.setPrettyPrinting(ScriptRuntime.toBoolean(value)); return; } super.setInstanceIdValue(id, value); } // #string_id_map# private static final int Id_defaultSettings = 1, Id_settings = 2, Id_setSettings = 3, MAX_FUNCTION_ID = 3; @Override protected int findPrototypeId(String s) { int id; // #generated# Last update: 2007-08-20 09:01:10 EDT L0: { id = 0; String X = null; int s_length = s.length(); if (s_length==8) { X="settings";id=Id_settings; } else if (s_length==11) { X="setSettings";id=Id_setSettings; } else if (s_length==15) { X="defaultSettings";id=Id_defaultSettings; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# return id; } // #/string_id_map# @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_defaultSettings: arity=0; s="defaultSettings"; break; case Id_settings: arity=0; s="settings"; break; case Id_setSettings: arity=1; s="setSettings"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(XMLCTOR_TAG, id, s, arity); } @Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(XMLCTOR_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); switch (id) { case Id_defaultSettings: { options.setDefault(); Scriptable obj = cx.newObject(scope); writeSetting(obj); return obj; } case Id_settings: { Scriptable obj = cx.newObject(scope); writeSetting(obj); return obj; } case Id_setSettings: { if (args.length == 0 || args[0] == null || args[0] == Undefined.instance) { options.setDefault(); } else if (args[0] instanceof Scriptable) { readSettings((Scriptable)args[0]); } return Undefined.instance; } } throw new IllegalArgumentException(String.valueOf(id)); } /** hasInstance for XML objects works differently than other objects; see ECMA357 13.4.3.10. */ @Override public boolean hasInstance(Scriptable instance) { return (instance instanceof XML || instance instanceof XMLList); } } ././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLWithScope.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLWithScope.j0000644000175000017500000001046511314263504035637 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Ethan Hugg * Terry Lucas * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import org.mozilla.javascript.*; import org.mozilla.javascript.xml.*; final class XMLWithScope extends NativeWith { private static final long serialVersionUID = -696429282095170887L; private XMLLibImpl lib; private int _currIndex; private XMLList _xmlList; private XMLObject _dqPrototype; XMLWithScope(XMLLibImpl lib, Scriptable parent, XMLObject prototype) { super(parent, prototype); this.lib = lib; } void initAsDotQuery() { XMLObject prototype = (XMLObject)getPrototype(); // XMLWithScope also handles the .(xxx) DotQuery for XML // basically DotQuery is a for/in/with statement and in // the following 3 statements we setup to signal it's // DotQuery, // the index and the object being looped over. The // xws.setPrototype is the scope of the object which is // is a element of the lhs (XMLList). _currIndex = 0; _dqPrototype = prototype; if (prototype instanceof XMLList) { XMLList xl = (XMLList)prototype; if (xl.length() > 0) { setPrototype((Scriptable)(xl.get(0, null))); } } // Always return the outer-most type of XML lValue of // XML to left of dotQuery. _xmlList = lib.newXMLList(); } @Override protected Object updateDotQuery(boolean value) { // Return null to continue looping XMLObject seed = _dqPrototype; XMLList xmlL = _xmlList; if (seed instanceof XMLList) { // We're a list so keep testing each element of the list if the // result on the top of stack is true then that element is added // to our result list. If false, we try the next element. XMLList orgXmlL = (XMLList)seed; int idx = _currIndex; if (value) { xmlL.addToList(orgXmlL.get(idx, null)); } // More elements to test? if (++idx < orgXmlL.length()) { // Yes, set our new index, get the next element and // reset the expression to run with this object as // the WITH selector. _currIndex = idx; setPrototype((Scriptable)(orgXmlL.get(idx, null))); // continue looping return null; } } else { // If we're not a XMLList then there's no looping // just return DQPrototype if the result is true. if (value) { xmlL.addToList(seed); } } return xmlL; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLName.java0000644000175000017500000003645611314263504035312 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Milen Nankov * David P. Caldwell * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import org.mozilla.javascript.*; class XMLName extends Ref { static final long serialVersionUID = 3832176310755686977L; private static boolean isNCNameStartChar(int c) { if ((c & ~0x7F) == 0) { // Optimize for ASCII and use A..Z < _ < a..z if (c >= 'a') { return c <= 'z'; } else if (c >= 'A') { if (c <= 'Z') { return true; } return c == '_'; } } else if ((c & ~0x1FFF) == 0) { return (0xC0 <= c && c <= 0xD6) || (0xD8 <= c && c <= 0xF6) || (0xF8 <= c && c <= 0x2FF) || (0x370 <= c && c <= 0x37D) || 0x37F <= c; } return (0x200C <= c && c <= 0x200D) || (0x2070 <= c && c <= 0x218F) || (0x2C00 <= c && c <= 0x2FEF) || (0x3001 <= c && c <= 0xD7FF) || (0xF900 <= c && c <= 0xFDCF) || (0xFDF0 <= c && c <= 0xFFFD) || (0x10000 <= c && c <= 0xEFFFF); } private static boolean isNCNameChar(int c) { if ((c & ~0x7F) == 0) { // Optimize for ASCII and use - < . < 0..9 < A..Z < _ < a..z if (c >= 'a') { return c <= 'z'; } else if (c >= 'A') { if (c <= 'Z') { return true; } return c == '_'; } else if (c >= '0') { return c <= '9'; } else { return c == '-' || c == '.'; } } else if ((c & ~0x1FFF) == 0) { return isNCNameStartChar(c) || c == 0xB7 || (0x300 <= c && c <= 0x36F); } return isNCNameStartChar(c) || (0x203F <= c && c <= 0x2040); } // This means "accept" in the parsing sense // See ECMA357 13.1.2.1 static boolean accept(Object nameObj) { String name; try { name = ScriptRuntime.toString(nameObj); } catch (EcmaError ee) { if ("TypeError".equals(ee.getName())) { return false; } throw ee; } // See http://w3.org/TR/xml-names11/#NT-NCName int length = name.length(); if (length != 0) { if (isNCNameStartChar(name.charAt(0))) { for (int i = 1; i != length; ++i) { if (!isNCNameChar(name.charAt(i))) { return false; } } return true; } } return false; } private XmlNode.QName qname; private boolean isAttributeName; private boolean isDescendants; private XMLObjectImpl xmlObject; private XMLName() { } static XMLName formStar() { XMLName rv = new XMLName(); rv.qname = XmlNode.QName.create(null, null); return rv; } /** @deprecated */ static XMLName formProperty(XmlNode.Namespace namespace, String localName) { if (localName != null && localName.equals("*")) localName = null; XMLName rv = new XMLName(); rv.qname = XmlNode.QName.create(namespace, localName); return rv; } /** TODO: marked deprecated by original author */ static XMLName formProperty(String uri, String localName) { return formProperty(XmlNode.Namespace.create(uri), localName); } /** TODO: marked deprecated by original implementor */ static XMLName create(String defaultNamespaceUri, String name) { if (name == null) throw new IllegalArgumentException(); int l = name.length(); if (l != 0) { char firstChar = name.charAt(0); if (firstChar == '*') { if (l == 1) { return XMLName.formStar(); } } else if (firstChar == '@') { XMLName xmlName = XMLName.formProperty("", name.substring(1)); xmlName.setAttributeName(); return xmlName; } } return XMLName.formProperty(defaultNamespaceUri, name); } static XMLName create(XmlNode.QName qname, boolean attribute, boolean descendants) { XMLName rv = new XMLName(); rv.qname = qname; rv.isAttributeName = attribute; rv.isDescendants = descendants; return rv; } /** @deprecated */ static XMLName create(XmlNode.QName qname) { return create(qname, false, false); } void initXMLObject(XMLObjectImpl xmlObject) { if (xmlObject == null) throw new IllegalArgumentException(); if (this.xmlObject != null) throw new IllegalStateException(); this.xmlObject = xmlObject; } String uri() { if (qname.getNamespace() == null) return null; return qname.getNamespace().getUri(); } String localName() { if (qname.getLocalName() == null) return "*"; return qname.getLocalName(); } private void addDescendantChildren(XMLList list, XML target) { XMLName xmlName = this; if (target.isElement()) { XML[] children = target.getChildren(); for (int i=0; i * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import org.mozilla.javascript.*; import org.mozilla.javascript.xml.*; /** * This abstract class describes what all XML objects (XML, XMLList) should * have in common. * * @see XML */ abstract class XMLObjectImpl extends XMLObject { private static final Object XMLOBJECT_TAG = "XMLObject"; private XMLLibImpl lib; private boolean prototypeFlag; protected XMLObjectImpl(XMLLibImpl lib, Scriptable scope, XMLObject prototype) { initialize(lib, scope, prototype); } final void initialize(XMLLibImpl lib, Scriptable scope, XMLObject prototype) { setParentScope(scope); setPrototype(prototype); prototypeFlag = (prototype == null); this.lib = lib; } final boolean isPrototype() { return prototypeFlag; } XMLLibImpl getLib() { return lib; } final XML newXML(XmlNode node) { return lib.newXML(node); } XML xmlFromNode(XmlNode node) { if (node.getXml() == null) { node.setXml( newXML(node) ); } return node.getXml(); } final XMLList newXMLList() { return lib.newXMLList(); } final XMLList newXMLListFrom(Object o) { return lib.newXMLListFrom(o); } final XmlProcessor getProcessor() { return lib.getProcessor(); } final QName newQName(String uri, String localName, String prefix) { return lib.newQName(uri, localName, prefix); } final QName newQName(XmlNode.QName name) { return lib.newQName(name); } final Namespace createNamespace(XmlNode.Namespace declaration) { if (declaration == null) return null; return lib.createNamespaces( new XmlNode.Namespace[] { declaration } )[0]; } final Namespace[] createNamespaces(XmlNode.Namespace[] declarations) { return lib.createNamespaces(declarations); } // // Scriptable // @Override public final Object get(String name, Scriptable start) { return super.get(name, start); } @Override public final boolean has(String name, Scriptable start) { return super.has(name, start); } @Override public final void put(String name, Scriptable start, Object value) { super.put(name, start, value); } @Override public final void delete(String name) { // TODO I am not sure about this, but this is how I found it. DPC throw new IllegalArgumentException("String: [" + name + "]"); } @Override public final Scriptable getPrototype() { return super.getPrototype(); } @Override public final void setPrototype(Scriptable prototype) { super.setPrototype(prototype); } @Override public final Scriptable getParentScope() { return super.getParentScope(); } @Override public final void setParentScope(Scriptable parent) { super.setParentScope(parent); } @Override public final Object getDefaultValue(Class hint) { return this.toString(); } @Override public final boolean hasInstance(Scriptable scriptable) { return super.hasInstance(scriptable); } /** * ecmaHas(cx, id) calls this after resolving when id to XMLName * and checking it is not Uint32 index. */ abstract boolean hasXMLProperty(XMLName name); /** * ecmaGet(cx, id) calls this after resolving when id to XMLName * and checking it is not Uint32 index. */ abstract Object getXMLProperty(XMLName name); /** * ecmaPut(cx, id, value) calls this after resolving when id to XMLName * and checking it is not Uint32 index. */ abstract void putXMLProperty(XMLName name, Object value); /** * ecmaDelete(cx, id) calls this after resolving when id to XMLName * and checking it is not Uint32 index. */ abstract void deleteXMLProperty(XMLName name); /** * Test XML equality with target the target. */ abstract boolean equivalentXml(Object target); abstract void addMatches(XMLList rv, XMLName name); private XMLList getMatches(XMLName name) { XMLList rv = newXMLList(); addMatches(rv, name); return rv; } abstract XML getXML(); // Methods from section 12.4.4 in the spec abstract XMLList child(int index); abstract XMLList child(XMLName xmlName); abstract XMLList children(); abstract XMLList comments(); abstract boolean contains(Object xml); abstract XMLObjectImpl copy(); abstract XMLList elements(XMLName xmlName); abstract boolean hasOwnProperty(XMLName xmlName); abstract boolean hasComplexContent(); abstract boolean hasSimpleContent(); abstract int length(); abstract void normalize(); abstract Object parent(); abstract XMLList processingInstructions(XMLName xmlName); abstract boolean propertyIsEnumerable(Object member); abstract XMLList text(); @Override public abstract String toString(); abstract String toSource(int indent); abstract String toXMLString(); abstract Object valueOf(); protected abstract Object jsConstructor(Context cx, boolean inNewExpr, Object[] args); final Object getMethod(String id) { return super.get(id, this); } // // // Methods overriding ScriptableObject // // /** * XMLObject always compare with any value and equivalentValues * never returns {@link Scriptable#NOT_FOUND} for them but rather * calls equivalentXml(value) and wrap the result as Boolean. */ @Override protected final Object equivalentValues(Object value) { boolean result = equivalentXml(value); return result ? Boolean.TRUE : Boolean.FALSE; } // // // Methods overriding XMLObject // // /** * Implementation of ECMAScript [[Has]] */ @Override public final boolean ecmaHas(Context cx, Object id) { if (cx == null) cx = Context.getCurrentContext(); XMLName xmlName = lib.toXMLNameOrIndex(cx, id); if (xmlName == null) { long index = ScriptRuntime.lastUint32Result(cx); // XXX Fix this cast return has((int)index, this); } return hasXMLProperty(xmlName); } /** * Implementation of ECMAScript [[Get]] */ @Override public final Object ecmaGet(Context cx, Object id) { if (cx == null) cx = Context.getCurrentContext(); XMLName xmlName = lib.toXMLNameOrIndex(cx, id); if (xmlName == null) { long index = ScriptRuntime.lastUint32Result(cx); // XXX Fix this cast Object result = get((int)index, this); if (result == Scriptable.NOT_FOUND) { result = Undefined.instance; } return result; } return getXMLProperty(xmlName); } /** * Implementation of ECMAScript [[Put]] */ @Override public final void ecmaPut(Context cx, Object id, Object value) { if (cx == null) cx = Context.getCurrentContext(); XMLName xmlName = lib.toXMLNameOrIndex(cx, id); if (xmlName == null) { long index = ScriptRuntime.lastUint32Result(cx); // XXX Fix this cast put((int)index, this, value); return; } putXMLProperty(xmlName, value); } /** * Implementation of ECMAScript [[Delete]]. */ @Override public final boolean ecmaDelete(Context cx, Object id) { if (cx == null) cx = Context.getCurrentContext(); XMLName xmlName = lib.toXMLNameOrIndex(cx, id); if (xmlName == null) { long index = ScriptRuntime.lastUint32Result(cx); // XXX Fix this delete((int)index); return true; } deleteXMLProperty(xmlName); return true; } // TODO Can this be made more strongly typed? @Override public Ref memberRef(Context cx, Object elem, int memberTypeFlags) { boolean attribute = (memberTypeFlags & Node.ATTRIBUTE_FLAG) != 0; boolean descendants = (memberTypeFlags & Node.DESCENDANTS_FLAG) != 0; if (!attribute && !descendants) { // Code generation would use ecma(Get|Has|Delete|Set) for // normal name identifiers so one ATTRIBUTE_FLAG // or DESCENDANTS_FLAG has to be set throw Kit.codeBug(); } XmlNode.QName qname = lib.toNodeQName(cx, elem, attribute); XMLName rv = XMLName.create(qname, attribute, descendants); rv.initXMLObject(this); return rv; } /** * Generic reference to implement x::ns, x.@ns::y, x..@ns::y etc. */ @Override public Ref memberRef(Context cx, Object namespace, Object elem, int memberTypeFlags) { boolean attribute = (memberTypeFlags & Node.ATTRIBUTE_FLAG) != 0; boolean descendants = (memberTypeFlags & Node.DESCENDANTS_FLAG) != 0; XMLName rv = XMLName.create(lib.toNodeQName(cx, namespace, elem), attribute, descendants); rv.initXMLObject(this); return rv; } @Override public NativeWith enterWith(Scriptable scope) { return new XMLWithScope(lib, scope, this); } @Override public NativeWith enterDotQuery(Scriptable scope) { XMLWithScope xws = new XMLWithScope(lib, scope, this); xws.initAsDotQuery(); return xws; } @Override public final Object addValues(Context cx, boolean thisIsLeft, Object value) { if (value instanceof XMLObject) { XMLObject v1, v2; if (thisIsLeft) { v1 = this; v2 = (XMLObject)value; } else { v1 = (XMLObject)value; v2 = this; } return lib.addXMLObjects(cx, v1, v2); } if (value == Undefined.instance) { // both "xml + undefined" and "undefined + xml" gives String(xml) return ScriptRuntime.toString(this); } return super.addValues(cx, thisIsLeft, value); } // // // IdScriptableObject machinery // // final void exportAsJSClass(boolean sealed) { prototypeFlag = true; exportAsJSClass(MAX_PROTOTYPE_ID, getParentScope(), sealed); } // #string_id_map# private final static int Id_constructor = 1, Id_addNamespace = 2, Id_appendChild = 3, Id_attribute = 4, Id_attributes = 5, Id_child = 6, Id_childIndex = 7, Id_children = 8, Id_comments = 9, Id_contains = 10, Id_copy = 11, Id_descendants = 12, Id_elements = 13, Id_inScopeNamespaces = 14, Id_insertChildAfter = 15, Id_insertChildBefore = 16, Id_hasOwnProperty = 17, Id_hasComplexContent = 18, Id_hasSimpleContent = 19, Id_length = 20, Id_localName = 21, Id_name = 22, Id_namespace = 23, Id_namespaceDeclarations = 24, Id_nodeKind = 25, Id_normalize = 26, Id_parent = 27, Id_prependChild = 28, Id_processingInstructions = 29, Id_propertyIsEnumerable = 30, Id_removeNamespace = 31, Id_replace = 32, Id_setChildren = 33, Id_setLocalName = 34, Id_setName = 35, Id_setNamespace = 36, Id_text = 37, Id_toString = 38, Id_toSource = 39, Id_toXMLString = 40, Id_valueOf = 41, MAX_PROTOTYPE_ID = 41; @Override protected int findPrototypeId(String s) { int id; // #generated# Last update: 2008-10-21 12:32:31 MESZ L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 4: c=s.charAt(0); if (c=='c') { X="copy";id=Id_copy; } else if (c=='n') { X="name";id=Id_name; } else if (c=='t') { X="text";id=Id_text; } break L; case 5: X="child";id=Id_child; break L; case 6: c=s.charAt(0); if (c=='l') { X="length";id=Id_length; } else if (c=='p') { X="parent";id=Id_parent; } break L; case 7: c=s.charAt(0); if (c=='r') { X="replace";id=Id_replace; } else if (c=='s') { X="setName";id=Id_setName; } else if (c=='v') { X="valueOf";id=Id_valueOf; } break L; case 8: switch (s.charAt(2)) { case 'S': c=s.charAt(7); if (c=='e') { X="toSource";id=Id_toSource; } else if (c=='g') { X="toString";id=Id_toString; } break L; case 'd': X="nodeKind";id=Id_nodeKind; break L; case 'e': X="elements";id=Id_elements; break L; case 'i': X="children";id=Id_children; break L; case 'm': X="comments";id=Id_comments; break L; case 'n': X="contains";id=Id_contains; break L; } break L; case 9: switch (s.charAt(2)) { case 'c': X="localName";id=Id_localName; break L; case 'm': X="namespace";id=Id_namespace; break L; case 'r': X="normalize";id=Id_normalize; break L; case 't': X="attribute";id=Id_attribute; break L; } break L; case 10: c=s.charAt(0); if (c=='a') { X="attributes";id=Id_attributes; } else if (c=='c') { X="childIndex";id=Id_childIndex; } break L; case 11: switch (s.charAt(0)) { case 'a': X="appendChild";id=Id_appendChild; break L; case 'c': X="constructor";id=Id_constructor; break L; case 'd': X="descendants";id=Id_descendants; break L; case 's': X="setChildren";id=Id_setChildren; break L; case 't': X="toXMLString";id=Id_toXMLString; break L; } break L; case 12: c=s.charAt(0); if (c=='a') { X="addNamespace";id=Id_addNamespace; } else if (c=='p') { X="prependChild";id=Id_prependChild; } else if (c=='s') { c=s.charAt(3); if (c=='L') { X="setLocalName";id=Id_setLocalName; } else if (c=='N') { X="setNamespace";id=Id_setNamespace; } } break L; case 14: X="hasOwnProperty";id=Id_hasOwnProperty; break L; case 15: X="removeNamespace";id=Id_removeNamespace; break L; case 16: c=s.charAt(0); if (c=='h') { X="hasSimpleContent";id=Id_hasSimpleContent; } else if (c=='i') { X="insertChildAfter";id=Id_insertChildAfter; } break L; case 17: c=s.charAt(3); if (c=='C') { X="hasComplexContent";id=Id_hasComplexContent; } else if (c=='c') { X="inScopeNamespaces";id=Id_inScopeNamespaces; } else if (c=='e') { X="insertChildBefore";id=Id_insertChildBefore; } break L; case 20: X="propertyIsEnumerable";id=Id_propertyIsEnumerable; break L; case 21: X="namespaceDeclarations";id=Id_namespaceDeclarations; break L; case 22: X="processingInstructions";id=Id_processingInstructions; break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# return id; } // #/string_id_map# @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: { IdFunctionObject ctor; if (this instanceof XML) { ctor = new XMLCtor((XML)this, XMLOBJECT_TAG, id, 1); } else { ctor = new IdFunctionObject(this, XMLOBJECT_TAG, id, 1); } initPrototypeConstructor(ctor); return; } case Id_addNamespace: arity=1; s="addNamespace"; break; case Id_appendChild: arity=1; s="appendChild"; break; case Id_attribute: arity=1; s="attribute"; break; case Id_attributes: arity=0; s="attributes"; break; case Id_child: arity=1; s="child"; break; case Id_childIndex: arity=0; s="childIndex"; break; case Id_children: arity=0; s="children"; break; case Id_comments: arity=0; s="comments"; break; case Id_contains: arity=1; s="contains"; break; case Id_copy: arity=0; s="copy"; break; case Id_descendants: arity=1; s="descendants"; break; case Id_elements: arity=1; s="elements"; break; case Id_hasComplexContent: arity=0; s="hasComplexContent"; break; case Id_hasOwnProperty: arity=1; s="hasOwnProperty"; break; case Id_hasSimpleContent: arity=0; s="hasSimpleContent"; break; case Id_inScopeNamespaces: arity=0; s="inScopeNamespaces"; break; case Id_insertChildAfter: arity=2; s="insertChildAfter"; break; case Id_insertChildBefore: arity=2; s="insertChildBefore"; break; case Id_length: arity=0; s="length"; break; case Id_localName: arity=0; s="localName"; break; case Id_name: arity=0; s="name"; break; case Id_namespace: arity=1; s="namespace"; break; case Id_namespaceDeclarations: arity=0; s="namespaceDeclarations"; break; case Id_nodeKind: arity=0; s="nodeKind"; break; case Id_normalize: arity=0; s="normalize"; break; case Id_parent: arity=0; s="parent"; break; case Id_prependChild: arity=1; s="prependChild"; break; case Id_processingInstructions: arity=1; s="processingInstructions"; break; case Id_propertyIsEnumerable: arity=1; s="propertyIsEnumerable"; break; case Id_removeNamespace: arity=1; s="removeNamespace"; break; case Id_replace: arity=2; s="replace"; break; case Id_setChildren: arity=1; s="setChildren"; break; case Id_setLocalName: arity=1; s="setLocalName"; break; case Id_setName: arity=1; s="setName"; break; case Id_setNamespace: arity=1; s="setNamespace"; break; case Id_text: arity=0; s="text"; break; case Id_toString: arity=0; s="toString"; break; case Id_toSource: arity=1; s="toSource"; break; case Id_toXMLString: arity=1; s="toXMLString"; break; case Id_valueOf: arity=0; s="valueOf"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(XMLOBJECT_TAG, id, s, arity); } private Object[] toObjectArray(Object[] typed) { Object[] rv = new Object[typed.length]; for (int i=0; i 0) ? ScriptRuntime.toString(args[0]) : null; Namespace rv = xml.namespace(prefix); if (rv == null) { return Undefined.instance; } else { return rv; } } case Id_namespaceDeclarations: { if (xml == null) xmlMethodNotFound(realThis, "namespaceDeclarations"); Namespace[] array = xml.namespaceDeclarations(); return cx.newArray(scope, toObjectArray(array)); } case Id_nodeKind: { if (xml == null) xmlMethodNotFound(realThis, "nodeKind"); return xml.nodeKind(); } case Id_prependChild: { if (xml == null) xmlMethodNotFound(realThis, "prependChild"); return xml.prependChild(arg(args, 0)); } case Id_removeNamespace: { if (xml == null) xmlMethodNotFound(realThis, "removeNamespace"); Namespace ns = lib.castToNamespace(cx, arg(args, 0)); return xml.removeNamespace(ns); } case Id_replace: { if (xml == null) xmlMethodNotFound(realThis, "replace"); XMLName xmlName = lib.toXMLNameOrIndex(cx, arg(args, 0)); Object arg1 = arg(args, 1); if (xmlName == null) { // I refuse to believe that this number will exceed 2^31 int index = (int)ScriptRuntime.lastUint32Result(cx); return xml.replace(index, arg1); } else { return xml.replace(xmlName, arg1); } } case Id_setChildren: { if (xml == null) xmlMethodNotFound(realThis, "setChildren"); return xml.setChildren(arg(args, 0)); } case Id_setLocalName: { if (xml == null) xmlMethodNotFound(realThis, "setLocalName"); String localName; Object arg = arg(args, 0); if (arg instanceof QName) { localName = ((QName)arg).localName(); } else { localName = ScriptRuntime.toString(arg); } xml.setLocalName(localName); return Undefined.instance; } case Id_setName: { if (xml == null) xmlMethodNotFound(realThis, "setName"); Object arg = (args.length != 0) ? args[0] : Undefined.instance; QName qname = lib.constructQName(cx, arg); xml.setName(qname); return Undefined.instance; } case Id_setNamespace: { if (xml == null) xmlMethodNotFound(realThis, "setNamespace"); Namespace ns = lib.castToNamespace(cx, arg(args, 0)); xml.setNamespace(ns); return Undefined.instance; } case Id_attribute: { XMLName xmlName = XMLName.create( lib.toNodeQName(cx, arg(args, 0), true), true, false ); return realThis.getMatches(xmlName); } case Id_attributes: return realThis.getMatches(XMLName.create(XmlNode.QName.create(null, null), true, false)); case Id_child: { XMLName xmlName = lib.toXMLNameOrIndex(cx, arg(args, 0)); if (xmlName == null) { // Two billion or so is a fine upper limit, so we cast to int int index = (int)ScriptRuntime.lastUint32Result(cx); return realThis.child(index); } else { return realThis.child(xmlName); } } case Id_children: return realThis.children(); case Id_comments: return realThis.comments(); case Id_contains: return ScriptRuntime.wrapBoolean( realThis.contains(arg(args, 0))); case Id_copy: return realThis.copy(); case Id_descendants: { XmlNode.QName qname = (args.length == 0) ? XmlNode.QName.create(null, null) : lib.toNodeQName(cx, args[0], false); return realThis.getMatches( XMLName.create(qname, false, true) ); } case Id_elements: { XMLName xmlName = (args.length == 0) ? XMLName.formStar() : lib.toXMLName(cx, args[0]); return realThis.elements(xmlName); } case Id_hasOwnProperty: { XMLName xmlName = lib.toXMLName(cx, arg(args, 0)); return ScriptRuntime.wrapBoolean( realThis.hasOwnProperty(xmlName)); } case Id_hasComplexContent: return ScriptRuntime.wrapBoolean(realThis.hasComplexContent()); case Id_hasSimpleContent: return ScriptRuntime.wrapBoolean(realThis.hasSimpleContent()); case Id_length: return ScriptRuntime.wrapInt(realThis.length()); case Id_normalize: realThis.normalize(); return Undefined.instance; case Id_parent: return realThis.parent(); case Id_processingInstructions: { XMLName xmlName = (args.length > 0) ? lib.toXMLName(cx, args[0]) : XMLName.formStar(); return realThis.processingInstructions(xmlName); } case Id_propertyIsEnumerable: { return ScriptRuntime.wrapBoolean( realThis.propertyIsEnumerable(arg(args, 0))); } case Id_text: return realThis.text(); case Id_toString: return realThis.toString(); case Id_toSource: int indent = ScriptRuntime.toInt32(args, 0); return realThis.toSource(indent); case Id_toXMLString: { return realThis.toXMLString(); } case Id_valueOf: return realThis.valueOf(); } throw new IllegalArgumentException(String.valueOf(id)); } private static Object arg(Object[] args, int i) { return (i < args.length) ? args[i] : Undefined.instance; } final XML newTextElementXML(XmlNode reference, XmlNode.QName qname, String value) { return lib.newTextElementXML(reference, qname, value); } /* TODO: Hopefully this can be replaced with ecmaToXml below. */ final XML newXMLFromJs(Object inputObject) { return lib.newXMLFromJs(inputObject); } final XML ecmaToXml(Object object) { return lib.ecmaToXml(object); } final String ecmaEscapeAttributeValue(String s) { // TODO Check this String quoted = lib.escapeAttributeValue(s); return quoted.substring(1, quoted.length() - 1); } final XML createEmptyXML() { return newXML(XmlNode.createEmpty(getProcessor())); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java0000644000175000017500000005713411314263504035341 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ethan Hugg * Terry Lucas * Milen Nankov * David P. Caldwell * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import org.mozilla.javascript.*; import org.mozilla.javascript.xml.*; import java.util.ArrayList; class XMLList extends XMLObjectImpl implements Function { static final long serialVersionUID = -4543618751670781135L; private XmlNode.InternalList _annos; private XMLObjectImpl targetObject = null; private XmlNode.QName targetProperty = null; XMLList(XMLLibImpl lib, Scriptable scope, XMLObject prototype) { super(lib, scope, prototype); _annos = new XmlNode.InternalList(); } /* TODO Will probably end up unnecessary as we move things around */ XmlNode.InternalList getNodeList() { return _annos; } // TODO Should be XMLObjectImpl, XMLName? void setTargets(XMLObjectImpl object, XmlNode.QName property) { targetObject = object; targetProperty = property; } /* TODO: original author marked this as deprecated */ private XML getXmlFromAnnotation(int index) { return getXML(_annos, index); } @Override XML getXML() { if (length() == 1) return getXmlFromAnnotation(0); return null; } private void internalRemoveFromList(int index) { _annos.remove(index); } void replace(int index, XML xml) { if (index < length()) { XmlNode.InternalList newAnnoList = new XmlNode.InternalList(); newAnnoList.add(_annos, 0, index); newAnnoList.add(xml); newAnnoList.add(_annos, index+1, length()); _annos = newAnnoList; } } private void insert(int index, XML xml) { if (index < length()) { XmlNode.InternalList newAnnoList = new XmlNode.InternalList(); newAnnoList.add(_annos, 0, index); newAnnoList.add(xml); newAnnoList.add(_annos, index, length()); _annos = newAnnoList; } } // // // methods overriding ScriptableObject // // @Override public String getClassName() { return "XMLList"; } // // // methods overriding IdScriptableObject // // @Override public Object get(int index, Scriptable start) { //Log("get index: " + index); if (index >= 0 && index < length()) { return getXmlFromAnnotation(index); } else { return Scriptable.NOT_FOUND; } } @Override boolean hasXMLProperty(XMLName xmlName) { boolean result = false; // Has now should return true if the property would have results > 0 or // if it's a method name String name = xmlName.localName(); if ((getPropertyList(xmlName).length() > 0) || (getMethod(name) != NOT_FOUND)) { result = true; } return result; } @Override public boolean has(int index, Scriptable start) { return 0 <= index && index < length(); } @Override void putXMLProperty(XMLName xmlName, Object value) { //Log("put property: " + name); // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (length() > 1) { throw ScriptRuntime.typeError( "Assignment to lists with more than one item is not supported"); } else if (length() == 0) { // Secret sauce for super-expandos. // We set an element here, and then add ourselves to our target. if (targetObject != null && targetProperty != null && targetProperty.getLocalName() != null) { // Add an empty element with our targetProperty name and // then set it. XML xmlValue = newTextElementXML(null, targetProperty, null); addToList(xmlValue); if(xmlName.isAttributeName()) { setAttribute(xmlName, value); } else { XML xml = item(0); xml.putXMLProperty(xmlName, value); // Update the list with the new item at location 0. replace(0, item(0)); } // Now add us to our parent XMLName name2 = XMLName.formProperty( targetProperty.getNamespace().getUri(), targetProperty.getLocalName()); targetObject.putXMLProperty(name2, this); } else { throw ScriptRuntime.typeError( "Assignment to empty XMLList without targets not supported"); } } else if(xmlName.isAttributeName()) { setAttribute(xmlName, value); } else { XML xml = item(0); xml.putXMLProperty(xmlName, value); // Update the list with the new item at location 0. replace(0, item(0)); if (targetObject != null && targetProperty != null && targetProperty.getLocalName() != null) { // Now add us to our parent XMLName name2 = XMLName.formProperty( targetProperty.getNamespace().getUri(), targetProperty.getLocalName()); targetObject.putXMLProperty(name2, this); } } } @Override Object getXMLProperty(XMLName name) { return getPropertyList(name); } private void replaceNode(XML xml, XML with) { xml.replaceWith(with); } @Override public void put(int index, Scriptable start, Object value) { Object parent = Undefined.instance; // Convert text into XML if needed. XMLObject xmlValue; // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (value instanceof XMLObject) { xmlValue = (XMLObject) value; } else { if (targetProperty == null) { xmlValue = newXMLFromJs(value.toString()); } else { // Note that later in the code, we will use this as an argument to replace(int,value) // So we will be "replacing" this element with itself // There may well be a better way to do this // TODO Find a way to refactor this whole method and simplify it xmlValue = item(index); ((XML)xmlValue).setChildren(value); } } // Find the parent if (index < length()) { parent = item(index).parent(); } else { // Appending parent = parent(); } if (parent instanceof XML) { // found parent, alter doc XML xmlParent = (XML) parent; if (index < length()) { // We're replacing the the node. XML xmlNode = getXmlFromAnnotation(index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { int lastIndexAdded = xmlNode.childIndex(); replaceNode(xmlNode, list.item(0)); replace(index, list.item(0)); for (int i = 1; i < list.length(); i++) { xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i)); lastIndexAdded++; insert(index + i, list.item(i)); } } } } else { // Appending xmlParent.appendChild(xmlValue); addToList(xmlParent.getXmlChild(index)); } } else { // Don't all have same parent, no underlying doc to alter if (index < length()) { XML xmlNode = getXML(_annos, index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { replaceNode(xmlNode, list.item(0)); replace(index, list.item(0)); for (int i = 1; i < list.length(); i++) { insert(index + i, list.item(i)); } } } } else { addToList(xmlValue); } } } private XML getXML(XmlNode.InternalList _annos, int index) { if (index >= 0 && index < length()) { return xmlFromNode(_annos.item(index)); } else { return null; } } @Override void deleteXMLProperty(XMLName name) { for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); if (xml.isElement()) { xml.deleteXMLProperty(name); } } } @Override public void delete(int index) { if (index >= 0 && index < length()) { XML xml = getXmlFromAnnotation(index); xml.remove(); internalRemoveFromList(index); } } @Override public Object[] getIds() { Object enumObjs[]; if (isPrototype()) { enumObjs = new Object[0]; } else { enumObjs = new Object[length()]; for (int i = 0; i < enumObjs.length; i++) { enumObjs[i] = Integer.valueOf(i); } } return enumObjs; } public Object[] getIdsForDebug() { return getIds(); } // XMLList will remove will delete all items in the list (a set delete) this differs from the XMLList delete operator. void remove() { int nLen = length(); for (int i = nLen - 1; i >= 0; i--) { XML xml = getXmlFromAnnotation(i); if (xml != null) { xml.remove(); internalRemoveFromList(i); } } } XML item(int index) { return _annos != null ? getXmlFromAnnotation(index) : createEmptyXML(); } private void setAttribute(XMLName xmlName, Object value) { for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); xml.setAttribute(xmlName, value); } } void addToList(Object toAdd) { _annos.addToList(toAdd); } // // // Methods from section 12.4.4 in the spec // // @Override XMLList child(int index) { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { result.addToList(getXmlFromAnnotation(i).child(index)); } return result; } @Override XMLList child(XMLName xmlName) { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { result.addToList(getXmlFromAnnotation(i).child(xmlName)); } return result; } @Override void addMatches(XMLList rv, XMLName name) { for (int i=0; i list = new ArrayList(); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); if (xml != null) { XMLList childList = xml.children(); int cChildren = childList.length(); for (int j = 0; j < cChildren; j++) { list.add(childList.item(j)); } } } XMLList allChildren = newXMLList(); int sz = list.size(); for (int i = 0; i < sz; i++) { allChildren.addToList(list.get(i)); } return allChildren; } @Override XMLList comments() { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.comments()); } return result; } @Override XMLList elements(XMLName name) { XMLList rv = newXMLList(); for (int i=0; i 0); } } @Override boolean hasComplexContent() { boolean complexContent; int length = length(); if (length == 0) { complexContent = false; } else if (length == 1) { complexContent = getXmlFromAnnotation(0).hasComplexContent(); } else { complexContent = false; for (int i = 0; i < length; i++) { XML nextElement = getXmlFromAnnotation(i); if (nextElement.isElement()) { complexContent = true; break; } } } return complexContent; } @Override boolean hasSimpleContent() { if (length() == 0) { return true; } else if (length() == 1) { return getXmlFromAnnotation(0).hasSimpleContent(); } else { for (int i=0; i hint) { return toString(); } // #string_id_map# private static final int Id_localName = 1, Id_uri = 2, MAX_INSTANCE_ID = 2; @Override protected int getMaxInstanceId() { return super.getMaxInstanceId() + MAX_INSTANCE_ID; } @Override protected int findInstanceIdInfo(String s) { int id; // #generated# Last update: 2007-08-20 08:21:41 EDT L0: { id = 0; String X = null; int s_length = s.length(); if (s_length==3) { X="uri";id=Id_uri; } else if (s_length==9) { X="localName";id=Id_localName; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# if (id == 0) return super.findInstanceIdInfo(s); int attr; switch (id) { case Id_localName: case Id_uri: attr = PERMANENT | READONLY; break; default: throw new IllegalStateException(); } return instanceIdInfo(attr, super.getMaxInstanceId() + id); } // #/string_id_map# @Override protected String getInstanceIdName(int id) { switch (id - super.getMaxInstanceId()) { case Id_localName: return "localName"; case Id_uri: return "uri"; } return super.getInstanceIdName(id); } @Override protected Object getInstanceIdValue(int id) { switch (id - super.getMaxInstanceId()) { case Id_localName: return localName(); case Id_uri: return uri(); } return super.getInstanceIdValue(id); } // #string_id_map# private static final int Id_constructor = 1, Id_toString = 2, Id_toSource = 3, MAX_PROTOTYPE_ID = 3; @Override protected int findPrototypeId(String s) { int id; // #generated# Last update: 2007-08-20 08:21:41 EDT L0: { id = 0; String X = null; int c; int s_length = s.length(); if (s_length==8) { c=s.charAt(3); if (c=='o') { X="toSource";id=Id_toSource; } else if (c=='t') { X="toString";id=Id_toString; } } else if (s_length==11) { X="constructor";id=Id_constructor; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# return id; } // #/string_id_map# @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=2; s="constructor"; break; case Id_toString: arity=0; s="toString"; break; case Id_toSource: arity=0; s="toSource"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(QNAME_TAG, id, s, arity); } @Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(QNAME_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); switch (id) { case Id_constructor: return jsConstructor(cx, (thisObj == null), args); case Id_toString: return realThis(thisObj, f).toString(); case Id_toSource: return realThis(thisObj, f).js_toSource(); } throw new IllegalArgumentException(String.valueOf(id)); } private QName realThis(Scriptable thisObj, IdFunctionObject f) { if(!(thisObj instanceof QName)) throw incompatibleCallError(f); return (QName)thisObj; } QName newQName(XMLLibImpl lib, String q_uri, String q_localName, String q_prefix) { QName prototype = this.prototype; if (prototype == null) { prototype = this; } XmlNode.Namespace ns = null; if (q_prefix != null) { ns = XmlNode.Namespace.create(q_uri, q_prefix); } else if (q_uri != null) { ns = XmlNode.Namespace.create(q_uri); } else { ns = null; } if (q_localName != null && q_localName.equals("*")) q_localName = null; return create(lib, this.getParentScope(), prototype, XmlNode.QName.create(ns, q_localName)); } // See ECMA357 13.3.2 QName constructQName(XMLLibImpl lib, Context cx, Object namespace, Object name) { String nameString = null; if (name instanceof QName) { if (namespace == Undefined.instance) { return (QName)name; } else { nameString = ((QName)name).localName(); } } if (name == Undefined.instance) { nameString = ""; } else { nameString = ScriptRuntime.toString(name); } if (namespace == Undefined.instance) { if ("*".equals(nameString)) { namespace = null; } else { namespace = lib.getDefaultNamespace(cx); } } Namespace namespaceNamespace = null; if (namespace == null) { // leave as null } else if (namespace instanceof Namespace) { namespaceNamespace = (Namespace)namespace; } else { namespaceNamespace = lib.newNamespace(ScriptRuntime.toString(namespace)); } String q_localName = nameString; String q_uri; String q_prefix; if (namespace == null) { q_uri = null; q_prefix = null; // corresponds to undefined; see QName class } else { q_uri = namespaceNamespace.uri(); q_prefix = namespaceNamespace.prefix(); } return newQName(lib, q_uri, q_localName, q_prefix); } QName constructQName(XMLLibImpl lib, Context cx, Object nameValue) { return constructQName(lib, cx, Undefined.instance, nameValue); } QName castToQName(XMLLibImpl lib, Context cx, Object qnameValue) { if (qnameValue instanceof QName) { return (QName)qnameValue; } return constructQName(lib, cx, qnameValue); } private Object jsConstructor(Context cx, boolean inNewExpr, Object[] args) { // See ECMA357 13.3.2 if (!inNewExpr && args.length == 1) { return castToQName(lib, cx, args[0]); } if (args.length == 0) { return constructQName(lib, cx, Undefined.instance); } else if (args.length == 1) { return constructQName(lib, cx, args[0]); } else { return constructQName(lib, cx, args[0], args[1]); } } private String js_toSource() { StringBuffer sb = new StringBuffer(); sb.append('('); toSourceImpl(uri(), localName(), prefix(), sb); sb.append(')'); return sb.toString(); } private static void toSourceImpl(String uri, String localName, String prefix, StringBuffer sb) { sb.append("new QName("); if (uri == null && prefix == null) { if (!"*".equals(localName)) { sb.append("null, "); } } else { Namespace.toSourceImpl(prefix, uri, sb); sb.append(", "); } sb.append('\''); sb.append(ScriptRuntime.escapeString(localName, '\'')); sb.append("')"); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/LICENSE.txt0000644000175000017500000013334111314263504024540 0ustar jamespagejamespage00000000000000The majority of Rhino is MPL 1.1 / GPL 2.0 dual licensed: The Mozilla Public License (http://www.mozilla.org/MPL/MPL-1.1.txt): ============================================================================ MOZILLA PUBLIC LICENSE Version 1.1 --------------- 1. Definitions. 1.0.1. "Commercial Use" means distribution or otherwise making the Covered Code available to a third party. 1.1. "Contributor" means each entity that creates or contributes to the creation of Modifications. 1.2. "Contributor Version" means the combination of the Original Code, prior Modifications used by a Contributor, and the Modifications made by that particular Contributor. 1.3. "Covered Code" means the Original Code or Modifications or the combination of the Original Code and Modifications, in each case including portions thereof. 1.4. "Electronic Distribution Mechanism" means a mechanism generally accepted in the software development community for the electronic transfer of data. 1.5. "Executable" means Covered Code in any form other than Source Code. 1.6. "Initial Developer" means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A. 1.7. "Larger Work" means a work which combines Covered Code or portions thereof with code not governed by the terms of this License. 1.8. "License" means this document. 1.8.1. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein. 1.9. "Modifications" means any addition to or deletion from the substance or structure of either the Original Code or any previous Modifications. When Covered Code is released as a series of files, a Modification is: A. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications. B. Any new file that contains any part of the Original Code or previous Modifications. 1.10. "Original Code" means Source Code of computer software code which is described in the Source Code notice required by Exhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License. 1.10.1. "Patent Claims" means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor. 1.11. "Source Code" means the preferred form of the Covered Code for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an Executable, or source code differential comparisons against either the Original Code or another well known, available Covered Code of the Contributor's choice. The Source Code can be in a compressed or archival form, provided the appropriate decompression or de-archiving software is widely available for no charge. 1.12. "You" (or "Your") means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License or a future version of this License issued under Section 6.1. For legal entities, "You" includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. Source Code License. 2.1. The Initial Developer Grant. The Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims: (a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, and/or as part of a Larger Work; and (b) under Patents Claims infringed by the making, using or selling of Original Code, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Code (or portions thereof). (c) the licenses granted in this Section 2.1(a) and (b) are effective on the date Initial Developer first distributes Original Code under the terms of this License. (d) Notwithstanding Section 2.1(b) above, no patent license is granted: 1) for code that You delete from the Original Code; 2) separate from the Original Code; or 3) for infringements caused by: i) the modification of the Original Code or ii) the combination of the Original Code with other software or devices. 2.2. Contributor Grant. Subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license (a) under intellectual property rights (other than patent or trademark) Licensable by Contributor, to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof) either on an unmodified basis, with other Modifications, as Covered Code and/or as part of a Larger Work; and (b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: 1) Modifications made by that Contributor (or portions thereof); and 2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination). (c) the licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first makes Commercial Use of the Covered Code. (d) Notwithstanding Section 2.2(b) above, no patent license is granted: 1) for any code that Contributor has deleted from the Contributor Version; 2) separate from the Contributor Version; 3) for infringements caused by: i) third party modifications of Contributor Version or ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or 4) under Patent Claims infringed by Covered Code in the absence of Modifications made by that Contributor. 3. Distribution Obligations. 3.1. Application of License. The Modifications which You create or to which You contribute are governed by the terms of this License, including without limitation Section 2.2. The Source Code version of Covered Code may be distributed only under the terms of this License or a future version of this License released under Section 6.1, and You must include a copy of this License with every copy of the Source Code You distribute. You may not offer or impose any terms on any Source Code version that alters or restricts the applicable version of this License or the recipients' rights hereunder. However, You may include an additional document offering the additional rights described in Section 3.5. 3.2. Availability of Source Code. Any Modification which You create or to which You contribute must be made available in Source Code form under the terms of this License either on the same media as an Executable version or via an accepted Electronic Distribution Mechanism to anyone to whom you made an Executable version available; and if made available via Electronic Distribution Mechanism, must remain available for at least twelve (12) months after the date it initially became available, or at least six (6) months after a subsequent version of that particular Modification has been made available to such recipients. You are responsible for ensuring that the Source Code version remains available even if the Electronic Distribution Mechanism is maintained by a third party. 3.3. Description of Modifications. You must cause all Covered Code to which You contribute to contain a file documenting the changes You made to create that Covered Code and the date of any change. You must include a prominent statement that the Modification is derived, directly or indirectly, from Original Code provided by the Initial Developer and including the name of the Initial Developer in (a) the Source Code, and (b) in any notice in an Executable version or related documentation in which You describe the origin or ownership of the Covered Code. 3.4. Intellectual Property Matters (a) Third Party Claims. If Contributor has knowledge that a license under a third party's intellectual property rights is required to exercise the rights granted by such Contributor under Sections 2.1 or 2.2, Contributor must include a text file with the Source Code distribution titled "LEGAL" which describes the claim and the party making the claim in sufficient detail that a recipient will know whom to contact. If Contributor obtains such knowledge after the Modification is made available as described in Section 3.2, Contributor shall promptly modify the LEGAL file in all copies Contributor makes available thereafter and shall take other steps (such as notifying appropriate mailing lists or newsgroups) reasonably calculated to inform those who received the Covered Code that new knowledge has been obtained. (b) Contributor APIs. If Contributor's Modifications include an application programming interface and Contributor has knowledge of patent licenses which are reasonably necessary to implement that API, Contributor must also include this information in the LEGAL file. (c) Representations. Contributor represents that, except as disclosed pursuant to Section 3.4(a) above, Contributor believes that Contributor's Modifications are Contributor's original creation(s) and/or Contributor has sufficient rights to grant the rights conveyed by this License. 3.5. Required Notices. You must duplicate the notice in Exhibit A in each file of the Source Code. If it is not possible to put such notice in a particular Source Code file due to its structure, then You must include such notice in a location (such as a relevant directory) where a user would be likely to look for such a notice. If You created one or more Modification(s) You may add your name as a Contributor to the notice described in Exhibit A. You must also duplicate this License in any documentation for the Source Code where You describe recipients' rights or ownership rights relating to Covered Code. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear than any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer. 3.6. Distribution of Executable Versions. You may distribute Covered Code in Executable form only if the requirements of Section 3.1-3.5 have been met for that Covered Code, and if You include a notice stating that the Source Code version of the Covered Code is available under the terms of this License, including a description of how and where You have fulfilled the obligations of Section 3.2. The notice must be conspicuously included in any notice in an Executable version, related documentation or collateral in which You describe recipients' rights relating to the Covered Code. You may distribute the Executable version of Covered Code or ownership rights under a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable version does not attempt to limit or alter the recipient's rights in the Source Code version from the rights set forth in this License. If You distribute the Executable version under a different license You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or any Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer. 3.7. Larger Works. You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Code. 4. Inability to Comply Due to Statute or Regulation. If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Code due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be included in the LEGAL file described in Section 3.4 and must be included with all distributions of the Source Code. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Application of this License. This License applies to code to which the Initial Developer has attached the notice in Exhibit A and to related Covered Code. 6. Versions of the License. 6.1. New Versions. Netscape Communications Corporation ("Netscape") may publish revised and/or new versions of the License from time to time. Each version will be given a distinguishing version number. 6.2. Effect of New Versions. Once Covered Code has been published under a particular version of the License, You may always continue to use it under the terms of that version. You may also choose to use such Covered Code under the terms of any subsequent version of the License published by Netscape. No one other than Netscape has the right to modify the terms applicable to Covered Code created under this License. 6.3. Derivative Works. If You create or use a modified version of this License (which you may only do in order to apply it to code which is not already Covered Code governed by this License), You must (a) rename Your license so that the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape", "MPL", "NPL" or any confusingly similar phrase do not appear in your license (except to note that your license differs from this License) and (b) otherwise make it clear that Your version of the license contains terms which differ from the Mozilla Public License and Netscape Public License. (Filling in the name of the Initial Developer, Original Code or Contributor in the notice described in Exhibit A shall not of themselves be deemed to be modifications of this License.) 7. DISCLAIMER OF WARRANTY. COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. 8. TERMINATION. 8.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. All sublicenses to the Covered Code which are properly granted shall survive any termination of this License. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive. 8.2. If You initiate litigation by asserting a patent infringement claim (excluding declatory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You file such action is referred to as "Participant") alleging that: (a) such Participant's Contributor Version directly or indirectly infringes any patent, then any and all rights granted by such Participant to You under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively, unless if within 60 days after receipt of notice You either: (i) agree in writing to pay Participant a mutually agreeable reasonable royalty for Your past and future use of Modifications made by such Participant, or (ii) withdraw Your litigation claim with respect to the Contributor Version against such Participant. If within 60 days of notice, a reasonable royalty and payment arrangement are not mutually agreed upon in writing by the parties or the litigation claim is not withdrawn, the rights granted by Participant to You under Sections 2.1 and/or 2.2 automatically terminate at the expiration of the 60 day notice period specified above. (b) any software, hardware, or device, other than such Participant's Contributor Version, directly or indirectly infringes any patent, then any rights granted to You by such Participant under Sections 2.1(b) and 2.2(b) are revoked effective as of the date You first made, used, sold, distributed, or had made, Modifications made by that Participant. 8.3. If You assert a patent infringement claim against Participant alleging that such Participant's Contributor Version directly or indirectly infringes any patent where such claim is resolved (such as by license or settlement) prior to the initiation of patent infringement litigation, then the reasonable value of the licenses granted by such Participant under Sections 2.1 or 2.2 shall be taken into account in determining the amount or value of any payment or license. 8.4. In the event of termination under Sections 8.1 or 8.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or any distributor hereunder prior to termination shall survive termination. 9. LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. 10. U.S. GOVERNMENT END USERS. The Covered Code is a "commercial item," as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer software" and "commercial computer software documentation," as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Code with only those rights set forth herein. 11. MISCELLANEOUS. This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by California law provisions (except to the extent applicable law, if any, provides otherwise), excluding its conflict-of-law provisions. With respect to disputes in which at least one party is a citizen of, or an entity chartered or registered to do business in the United States of America, any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California, with venue lying in Santa Clara County, California, with the losing party responsible for costs, including without limitation, court costs and reasonable attorneys' fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. 12. RESPONSIBILITY FOR CLAIMS. As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability. 13. MULTIPLE-LICENSED CODE. Initial Developer may designate portions of the Covered Code as "Multiple-Licensed". "Multiple-Licensed" means that the Initial Developer permits you to utilize portions of the Covered Code under Your choice of the NPL or the alternative licenses, if any, specified by the Initial Developer in the file described in Exhibit A. EXHIBIT A -Mozilla Public License. ``The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is ______________________________________. The Initial Developer of the Original Code is ________________________. Portions created by ______________________ are Copyright (C) ______ _______________________. All Rights Reserved. Contributor(s): ______________________________________. Alternatively, the contents of this file may be used under the terms of the _____ license (the "[___] License"), in which case the provisions of [______] License are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the [____] License and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the [___] License. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the [___] License." [NOTE: The text of this Exhibit A may differ slightly from the text of the notices in the Source Code files of the Original Code. You should use the text of this Exhibit A rather than the text found in the Original Code Source Code for Your Modifications.] ============================================================================ ============================================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ============================================================================ Additionally, some files (currently the contents of toolsrc/org/mozilla/javascript/tools/debugger/treetable/) are available only under the following license: ============================================================================ * Copyright 1997, 1998 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================ jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/0000755000175000017500000000000011537630013023477 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/manifest0000644000175000017500000000011211314263504025222 0ustar jamespagejamespage00000000000000Manifest-Version: 1.0 Main-Class: org.mozilla.javascript.tools.shell.Main jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/build.xml0000644000175000017500000000665311314263504025332 0ustar jamespagejamespage00000000000000 jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/0000755000175000017500000000000011537630012024265 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/0000755000175000017500000000000011537630012025734 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/0000755000175000017500000000000011537630013030103 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ScriptableObject.java0000644000175000017500000033270311314263504034175 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Daniel Gredler * Bob Jervis * Roger Lawrence * Cameron McCormack * Steve Weiss * Hannes Wallnoefer * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; import java.lang.reflect.*; import java.util.*; import java.io.*; import org.mozilla.javascript.debug.DebuggableObject; /** * This is the default implementation of the Scriptable interface. This * class provides convenient default behavior that makes it easier to * define host objects. *

* Various properties and methods of JavaScript objects can be conveniently * defined using methods of ScriptableObject. *

* Classes extending ScriptableObject must define the getClassName method. * * @see org.mozilla.javascript.Scriptable * @author Norris Boyd */ public abstract class ScriptableObject implements Scriptable, Serializable, DebuggableObject, ConstProperties, Map { /** * The empty property attribute. * * Used by getAttributes() and setAttributes(). * * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int EMPTY = 0x00; /** * Property attribute indicating assignment to this property is ignored. * * @see org.mozilla.javascript.ScriptableObject * #put(String, Scriptable, Object) * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int READONLY = 0x01; /** * Property attribute indicating property is not enumerated. * * Only enumerated properties will be returned by getIds(). * * @see org.mozilla.javascript.ScriptableObject#getIds() * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int DONTENUM = 0x02; /** * Property attribute indicating property cannot be deleted. * * @see org.mozilla.javascript.ScriptableObject#delete(String) * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int PERMANENT = 0x04; /** * Property attribute indicating that this is a const property that has not * been assigned yet. The first 'const' assignment to the property will * clear this bit. */ public static final int UNINITIALIZED_CONST = 0x08; public static final int CONST = PERMANENT|READONLY|UNINITIALIZED_CONST; /** * The prototype of this object. */ private Scriptable prototypeObject; /** * The parent scope of this object. */ private Scriptable parentScopeObject; private static final Slot REMOVED = new Slot(null, 0, READONLY); static { REMOVED.wasDeleted = true; } private transient Slot[] slots; // If count >= 0, it gives number of keys or if count < 0, // it indicates sealed object where ~count gives number of keys private int count; // gateways into the definition-order linked list of slots private transient Slot firstAdded; private transient Slot lastAdded; // cache; may be removed for smaller memory footprint private transient Slot lastAccess = REMOVED; private volatile Map associatedValues; private static final int SLOT_QUERY = 1; private static final int SLOT_MODIFY = 2; private static final int SLOT_REMOVE = 3; private static final int SLOT_MODIFY_GETTER_SETTER = 4; private static final int SLOT_MODIFY_CONST = 5; private static final int SLOT_CONVERT_ACCESSOR_TO_DATA = 6; private boolean isExtensible = true; private static class Slot implements Serializable { private static final long serialVersionUID = -6090581677123995491L; String name; // This can change due to caching int indexOrHash; private volatile short attributes; transient volatile boolean wasDeleted; volatile Object value; transient volatile Slot next; // next in hash table bucket transient volatile Slot orderedNext; // next in linked list Slot(String name, int indexOrHash, int attributes) { this.name = name; this.indexOrHash = indexOrHash; this.attributes = (short)attributes; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (name != null) { indexOrHash = name.hashCode(); } } final int getAttributes() { return attributes; } final synchronized void setAttributes(int value) { checkValidAttributes(value); attributes = (short)value; } final void checkNotReadonly() { if ((attributes & READONLY) != 0) { String str = (name != null ? name : Integer.toString(indexOrHash)); throw Context.reportRuntimeError1("msg.modify.readonly", str); } } ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) { ScriptableObject desc = new NativeObject(); ScriptRuntime.setObjectProtoAndParent(desc, scope); if (value != null) desc.defineProperty("value", value, EMPTY); desc.defineProperty("writable", (attributes & READONLY) == 0, EMPTY); desc.defineProperty("enumerable", (attributes & DONTENUM) == 0, EMPTY); desc.defineProperty("configurable", (attributes & PERMANENT) == 0, EMPTY); return desc; } } private static final class GetterSlot extends Slot { static final long serialVersionUID = -4900574849788797588L; Object getter; Object setter; GetterSlot(String name, int indexOrHash, int attributes) { super(name, indexOrHash, attributes); } @Override ScriptableObject getPropertyDescriptor(Context cx, Scriptable parent) { ScriptableObject desc = super.getPropertyDescriptor(cx, parent); desc.delete("value"); desc.delete("writable"); if (getter != null) desc.defineProperty("get", getter, EMPTY); if (setter != null) desc.defineProperty("set", setter, EMPTY); return desc; } } static void checkValidAttributes(int attributes) { final int mask = READONLY | DONTENUM | PERMANENT | UNINITIALIZED_CONST; if ((attributes & ~mask) != 0) { throw new IllegalArgumentException(String.valueOf(attributes)); } } public ScriptableObject() { } public ScriptableObject(Scriptable scope, Scriptable prototype) { if (scope == null) throw new IllegalArgumentException(); parentScopeObject = scope; prototypeObject = prototype; } /** * Gets the value that will be returned by calling the typeof operator on this object. * @return default is "object" unless {@link #avoidObjectDetection()} is true in which * case it returns "undefined" */ public String getTypeOf() { return avoidObjectDetection() ? "undefined" : "object"; } /** * Return the name of the class. * * This is typically the same name as the constructor. * Classes extending ScriptableObject must implement this abstract * method. */ public abstract String getClassName(); /** * Returns true if the named property is defined. * * @param name the name of the property * @param start the object in which the lookup began * @return true if and only if the property was found in the object */ public boolean has(String name, Scriptable start) { return null != getSlot(name, 0, SLOT_QUERY); } /** * Returns true if the property index is defined. * * @param index the numeric index for the property * @param start the object in which the lookup began * @return true if and only if the property was found in the object */ public boolean has(int index, Scriptable start) { return null != getSlot(null, index, SLOT_QUERY); } /** * Returns the value of the named property or NOT_FOUND. * * If the property was created using defineProperty, the * appropriate getter method is called. * * @param name the name of the property * @param start the object in which the lookup began * @return the value of the property (may be null), or NOT_FOUND */ public Object get(String name, Scriptable start) { return getImpl(name, 0, start); } /** * Returns the value of the indexed property or NOT_FOUND. * * @param index the numeric index for the property * @param start the object in which the lookup began * @return the value of the property (may be null), or NOT_FOUND */ public Object get(int index, Scriptable start) { return getImpl(null, index, start); } /** * Sets the value of the named property, creating it if need be. * * If the property was created using defineProperty, the * appropriate setter method is called.

* * If the property's attributes include READONLY, no action is * taken. * This method will actually set the property in the start * object. * * @param name the name of the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(String name, Scriptable start, Object value) { if (putImpl(name, 0, start, value, EMPTY)) return; if (start == this) throw Kit.codeBug(); start.put(name, start, value); } /** * Sets the value of the indexed property, creating it if need be. * * @param index the numeric index for the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(int index, Scriptable start, Object value) { if (putImpl(null, index, start, value, EMPTY)) return; if (start == this) throw Kit.codeBug(); start.put(index, start, value); } /** * Removes a named property from the object. * * If the property is not found, or it has the PERMANENT attribute, * no action is taken. * * @param name the name of the property */ public void delete(String name) { checkNotSealed(name, 0); accessSlot(name, 0, SLOT_REMOVE); } /** * Removes the indexed property from the object. * * If the property is not found, or it has the PERMANENT attribute, * no action is taken. * * @param index the numeric index for the property */ public void delete(int index) { checkNotSealed(null, index); accessSlot(null, index, SLOT_REMOVE); } /** * Sets the value of the named const property, creating it if need be. * * If the property was created using defineProperty, the * appropriate setter method is called.

* * If the property's attributes include READONLY, no action is * taken. * This method will actually set the property in the start * object. * * @param name the name of the property * @param start the object whose property is being set * @param value value to set the property to */ public void putConst(String name, Scriptable start, Object value) { if (putImpl(name, 0, start, value, READONLY)) return; if (start == this) throw Kit.codeBug(); if (start instanceof ConstProperties) ((ConstProperties)start).putConst(name, start, value); else start.put(name, start, value); } public void defineConst(String name, Scriptable start) { if (putImpl(name, 0, start, Undefined.instance, UNINITIALIZED_CONST)) return; if (start == this) throw Kit.codeBug(); if (start instanceof ConstProperties) ((ConstProperties)start).defineConst(name, start); } /** * Returns true if the named property is defined as a const on this object. * @param name * @return true if the named property is defined as a const, false * otherwise. */ public boolean isConst(String name) { Slot slot = getSlot(name, 0, SLOT_QUERY); if (slot == null) { return false; } return (slot.getAttributes() & (PERMANENT|READONLY)) == (PERMANENT|READONLY); } /** * @deprecated Use {@link #getAttributes(String name)}. The engine always * ignored the start argument. */ public final int getAttributes(String name, Scriptable start) { return getAttributes(name); } /** * @deprecated Use {@link #getAttributes(int index)}. The engine always * ignored the start argument. */ public final int getAttributes(int index, Scriptable start) { return getAttributes(index); } /** * @deprecated Use {@link #setAttributes(String name, int attributes)}. * The engine always ignored the start argument. */ public final void setAttributes(String name, Scriptable start, int attributes) { setAttributes(name, attributes); } /** * @deprecated Use {@link #setAttributes(int index, int attributes)}. * The engine always ignored the start argument. */ public void setAttributes(int index, Scriptable start, int attributes) { setAttributes(index, attributes); } /** * Get the attributes of a named property. * * The property is specified by name * as defined for has.

* * @param name the identifier for the property * @return the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public int getAttributes(String name) { return findAttributeSlot(name, 0, SLOT_QUERY).getAttributes(); } /** * Get the attributes of an indexed property. * * @param index the numeric index for the property * @exception EvaluatorException if the named property is not found * is not found * @return the bitset of attributes * @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public int getAttributes(int index) { return findAttributeSlot(null, index, SLOT_QUERY).getAttributes(); } /** * Set the attributes of a named property. * * The property is specified by name * as defined for has.

* * The possible attributes are READONLY, DONTENUM, * and PERMANENT. Combinations of attributes * are expressed by the bitwise OR of attributes. * EMPTY is the state of no attributes set. Any unused * bits are reserved for future use. * * @param name the name of the property * @param attributes the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.Scriptable#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public void setAttributes(String name, int attributes) { checkNotSealed(name, 0); findAttributeSlot(name, 0, SLOT_MODIFY).setAttributes(attributes); } /** * Set the attributes of an indexed property. * * @param index the numeric index for the property * @param attributes the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.Scriptable#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public void setAttributes(int index, int attributes) { checkNotSealed(null, index); findAttributeSlot(null, index, SLOT_MODIFY).setAttributes(attributes); } /** * XXX: write docs. */ public void setGetterOrSetter(String name, int index, Callable getterOrSetter, boolean isSetter) { setGetterOrSetter(name, index, getterOrSetter, isSetter, false); } private void setGetterOrSetter(String name, int index, Callable getterOrSetter, boolean isSetter, boolean force) { if (name != null && index != 0) throw new IllegalArgumentException(name); if (!force) { checkNotSealed(name, index); } final GetterSlot gslot; if (isExtensible()) { gslot = (GetterSlot)getSlot(name, index, SLOT_MODIFY_GETTER_SETTER); } else { gslot = (GetterSlot)getSlot(name, index, SLOT_QUERY); if (gslot == null) return; } if (!force) { gslot.checkNotReadonly(); } if (isSetter) { gslot.setter = getterOrSetter; } else { gslot.getter = getterOrSetter; } gslot.value = Undefined.instance; } /** * Get the getter or setter for a given property. Used by __lookupGetter__ * and __lookupSetter__. * * @param name Name of the object. If nonnull, index must be 0. * @param index Index of the object. If nonzero, name must be null. * @param isSetter If true, return the setter, otherwise return the getter. * @exception IllegalArgumentException if both name and index are nonnull * and nonzero respectively. * @return Null if the property does not exist. Otherwise returns either * the getter or the setter for the property, depending on * the value of isSetter (may be undefined if unset). */ public Object getGetterOrSetter(String name, int index, boolean isSetter) { if (name != null && index != 0) throw new IllegalArgumentException(name); Slot slot = getSlot(name, index, SLOT_QUERY); if (slot == null) return null; if (slot instanceof GetterSlot) { GetterSlot gslot = (GetterSlot)slot; Object result = isSetter ? gslot.setter : gslot.getter; return result != null ? result : Undefined.instance; } else return Undefined.instance; } /** * Returns whether a property is a getter or a setter * @param name property name * @param index property index * @param setter true to check for a setter, false for a getter * @return whether the property is a getter or a setter */ protected boolean isGetterOrSetter(String name, int index, boolean setter) { Slot slot = getSlot(name, index, SLOT_QUERY); if (slot instanceof GetterSlot) { if (setter && ((GetterSlot)slot).setter != null) return true; if (!setter && ((GetterSlot)slot).getter != null) return true; } return false; } void addLazilyInitializedValue(String name, int index, LazilyLoadedCtor init, int attributes) { if (name != null && index != 0) throw new IllegalArgumentException(name); checkNotSealed(name, index); GetterSlot gslot = (GetterSlot)getSlot(name, index, SLOT_MODIFY_GETTER_SETTER); gslot.setAttributes(attributes); gslot.getter = null; gslot.setter = null; gslot.value = init; } /** * Returns the prototype of the object. */ public Scriptable getPrototype() { return prototypeObject; } /** * Sets the prototype of the object. */ public void setPrototype(Scriptable m) { prototypeObject = m; } /** * Returns the parent (enclosing) scope of the object. */ public Scriptable getParentScope() { return parentScopeObject; } /** * Sets the parent (enclosing) scope of the object. */ public void setParentScope(Scriptable m) { parentScopeObject = m; } /** * Returns an array of ids for the properties of the object. * *

Any properties with the attribute DONTENUM are not listed.

* * @return an array of java.lang.Objects with an entry for every * listed property. Properties accessed via an integer index will * have a corresponding * Integer entry in the returned array. Properties accessed by * a String will have a String entry in the returned array. */ public Object[] getIds() { return getIds(false); } /** * Returns an array of ids for the properties of the object. * *

All properties, even those with attribute DONTENUM, are listed.

* * @return an array of java.lang.Objects with an entry for every * listed property. Properties accessed via an integer index will * have a corresponding * Integer entry in the returned array. Properties accessed by * a String will have a String entry in the returned array. */ public Object[] getAllIds() { return getIds(true); } /** * Implements the [[DefaultValue]] internal method. * *

Note that the toPrimitive conversion is a no-op for * every type other than Object, for which [[DefaultValue]] * is called. See ECMA 9.1.

* * A hint of null means "no hint". * * @param typeHint the type hint * @return the default value for the object * * See ECMA 8.6.2.6. */ public Object getDefaultValue(Class typeHint) { return getDefaultValue(this, typeHint); } public static Object getDefaultValue(Scriptable object, Class typeHint) { Context cx = null; for (int i=0; i < 2; i++) { boolean tryToString; if (typeHint == ScriptRuntime.StringClass) { tryToString = (i == 0); } else { tryToString = (i == 1); } String methodName; Object[] args; if (tryToString) { methodName = "toString"; args = ScriptRuntime.emptyArgs; } else { methodName = "valueOf"; args = new Object[1]; String hint; if (typeHint == null) { hint = "undefined"; } else if (typeHint == ScriptRuntime.StringClass) { hint = "string"; } else if (typeHint == ScriptRuntime.ScriptableClass) { hint = "object"; } else if (typeHint == ScriptRuntime.FunctionClass) { hint = "function"; } else if (typeHint == ScriptRuntime.BooleanClass || typeHint == Boolean.TYPE) { hint = "boolean"; } else if (typeHint == ScriptRuntime.NumberClass || typeHint == ScriptRuntime.ByteClass || typeHint == Byte.TYPE || typeHint == ScriptRuntime.ShortClass || typeHint == Short.TYPE || typeHint == ScriptRuntime.IntegerClass || typeHint == Integer.TYPE || typeHint == ScriptRuntime.FloatClass || typeHint == Float.TYPE || typeHint == ScriptRuntime.DoubleClass || typeHint == Double.TYPE) { hint = "number"; } else { throw Context.reportRuntimeError1( "msg.invalid.type", typeHint.toString()); } args[0] = hint; } Object v = getProperty(object, methodName); if (!(v instanceof Function)) continue; Function fun = (Function) v; if (cx == null) cx = Context.getContext(); v = fun.call(cx, fun.getParentScope(), object, args); if (v != null) { if (!(v instanceof Scriptable)) { return v; } if (typeHint == ScriptRuntime.ScriptableClass || typeHint == ScriptRuntime.FunctionClass) { return v; } if (tryToString && v instanceof Wrapper) { // Let a wrapped java.lang.String pass for a primitive // string. Object u = ((Wrapper)v).unwrap(); if (u instanceof String) return u; } } } // fall through to error String arg = (typeHint == null) ? "undefined" : typeHint.getName(); throw ScriptRuntime.typeError1("msg.default.value", arg); } /** * Implements the instanceof operator. * *

This operator has been proposed to ECMA. * * @param instance The value that appeared on the LHS of the instanceof * operator * @return true if "this" appears in value's prototype chain * */ public boolean hasInstance(Scriptable instance) { // Default for JS objects (other than Function) is to do prototype // chasing. This will be overridden in NativeFunction and non-JS // objects. return ScriptRuntime.jsDelegatesTo(instance, this); } /** * Emulate the SpiderMonkey (and Firefox) feature of allowing * custom objects to avoid detection by normal "object detection" * code patterns. This is used to implement document.all. * See https://bugzilla.mozilla.org/show_bug.cgi?id=412247. * This is an analog to JOF_DETECTING from SpiderMonkey; see * https://bugzilla.mozilla.org/show_bug.cgi?id=248549. * Other than this special case, embeddings should return false. * @return true if this object should avoid object detection * @since 1.7R1 */ public boolean avoidObjectDetection() { return false; } /** * Custom == operator. * Must return {@link Scriptable#NOT_FOUND} if this object does not * have custom equality operator for the given value, * Boolean.TRUE if this object is equivalent to value, * Boolean.FALSE if this object is not equivalent to * value. *

* The default implementation returns Boolean.TRUE * if this == value or {@link Scriptable#NOT_FOUND} otherwise. * It indicates that by default custom equality is available only if * value is this in which case true is returned. */ protected Object equivalentValues(Object value) { return (this == value) ? Boolean.TRUE : Scriptable.NOT_FOUND; } /** * Defines JavaScript objects from a Java class that implements Scriptable. * * If the given class has a method *

     * static void init(Context cx, Scriptable scope, boolean sealed);
* * or its compatibility form *
     * static void init(Scriptable scope);
* * then it is invoked and no further initialization is done.

* * However, if no such a method is found, then the class's constructors and * methods are used to initialize a class in the following manner.

* * First, the zero-parameter constructor of the class is called to * create the prototype. If no such constructor exists, * a {@link EvaluatorException} is thrown.

* * Next, all methods are scanned for special prefixes that indicate that they * have special meaning for defining JavaScript objects. * These special prefixes are *

    *
  • jsFunction_ for a JavaScript function *
  • jsStaticFunction_ for a JavaScript function that * is a property of the constructor *
  • jsGet_ for a getter of a JavaScript property *
  • jsSet_ for a setter of a JavaScript property *
  • jsConstructor for a JavaScript function that * is the constructor *

* * If the method's name begins with "jsFunction_", a JavaScript function * is created with a name formed from the rest of the Java method name * following "jsFunction_". So a Java method named "jsFunction_foo" will * define a JavaScript method "foo". Calling this JavaScript function * will cause the Java method to be called. The parameters of the method * must be of number and types as defined by the FunctionObject class. * The JavaScript function is then added as a property * of the prototype.

* * If the method's name begins with "jsStaticFunction_", it is handled * similarly except that the resulting JavaScript function is added as a * property of the constructor object. The Java method must be static. * * If the method's name begins with "jsGet_" or "jsSet_", the method is * considered to define a property. Accesses to the defined property * will result in calls to these getter and setter methods. If no * setter is defined, the property is defined as READONLY.

* * If the method's name is "jsConstructor", the method is * considered to define the body of the constructor. Only one * method of this name may be defined. You may use the varargs forms * for constructors documented in {@link FunctionObject#FunctionObject(String, Member, Scriptable)} * * If no method is found that can serve as constructor, a Java * constructor will be selected to serve as the JavaScript * constructor in the following manner. If the class has only one * Java constructor, that constructor is used to define * the JavaScript constructor. If the the class has two constructors, * one must be the zero-argument constructor (otherwise an * {@link EvaluatorException} would have already been thrown * when the prototype was to be created). In this case * the Java constructor with one or more parameters will be used * to define the JavaScript constructor. If the class has three * or more constructors, an {@link EvaluatorException} * will be thrown.

* * Finally, if there is a method *

     * static void finishInit(Scriptable scope, FunctionObject constructor,
     *                        Scriptable prototype)
* * it will be called to finish any initialization. The scope * argument will be passed, along with the newly created constructor and * the newly created prototype.

* * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @see org.mozilla.javascript.Function * @see org.mozilla.javascript.FunctionObject * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject * #defineProperty(String, Class, int) */ public static void defineClass( Scriptable scope, Class clazz) throws IllegalAccessException, InstantiationException, InvocationTargetException { defineClass(scope, clazz, false, false); } /** * Defines JavaScript objects from a Java class, optionally * allowing sealing. * * Similar to defineClass(Scriptable scope, Class clazz) * except that sealing is allowed. An object that is sealed cannot have * properties added or removed. Note that sealing is not allowed in * the current ECMA/ISO language specification, but is likely for * the next version. * * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. The class must implement Scriptable. * @param sealed Whether or not to create sealed standard objects that * cannot be modified. * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @since 1.4R3 */ public static void defineClass( Scriptable scope, Class clazz, boolean sealed) throws IllegalAccessException, InstantiationException, InvocationTargetException { defineClass(scope, clazz, sealed, false); } /** * Defines JavaScript objects from a Java class, optionally * allowing sealing and mapping of Java inheritance to JavaScript * prototype-based inheritance. * * Similar to defineClass(Scriptable scope, Class clazz) * except that sealing and inheritance mapping are allowed. An object * that is sealed cannot have properties added or removed. Note that * sealing is not allowed in the current ECMA/ISO language specification, * but is likely for the next version. * * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. The class must implement Scriptable. * @param sealed Whether or not to create sealed standard objects that * cannot be modified. * @param mapInheritance Whether or not to map Java inheritance to * JavaScript prototype-based inheritance. * @return the class name for the prototype of the specified class * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @since 1.6R2 */ public static String defineClass( Scriptable scope, Class clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { BaseFunction ctor = buildClassCtor(scope, clazz, sealed, mapInheritance); if (ctor == null) return null; String name = ctor.getClassPrototype().getClassName(); defineProperty(scope, name, ctor, ScriptableObject.DONTENUM); return name; } static BaseFunction buildClassCtor( Scriptable scope, Class clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals("init")) continue; Class[] parmTypes = method.getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ContextClass && parmTypes[1] == ScriptRuntime.ScriptableClass && parmTypes[2] == Boolean.TYPE && Modifier.isStatic(method.getModifiers())) { Object args[] = { Context.getContext(), scope, sealed ? Boolean.TRUE : Boolean.FALSE }; method.invoke(null, args); return null; } if (parmTypes.length == 1 && parmTypes[0] == ScriptRuntime.ScriptableClass && Modifier.isStatic(method.getModifiers())) { Object args[] = { scope }; method.invoke(null, args); return null; } } // If we got here, there isn't an "init" method with the right // parameter types. Constructor[] ctors = clazz.getConstructors(); Constructor protoCtor = null; for (int i=0; i < ctors.length; i++) { if (ctors[i].getParameterTypes().length == 0) { protoCtor = ctors[i]; break; } } if (protoCtor == null) { throw Context.reportRuntimeError1( "msg.zero.arg.ctor", clazz.getName()); } Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs); String className = proto.getClassName(); // Set the prototype's prototype, trying to map Java inheritance to JS // prototype-based inheritance if requested to do so. Scriptable superProto = null; if (mapInheritance) { Class superClass = clazz.getSuperclass(); if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) && !Modifier.isAbstract(superClass.getModifiers())) { Class superScriptable = extendsScriptable(superClass); String name = ScriptableObject.defineClass(scope, superScriptable, sealed, mapInheritance); if (name != null) { superProto = ScriptableObject.getClassPrototype(scope, name); } } } if (superProto == null) { superProto = ScriptableObject.getObjectPrototype(scope); } proto.setPrototype(superProto); // Find out whether there are any methods that begin with // "js". If so, then only methods that begin with special // prefixes will be defined as JavaScript entities. final String functionPrefix = "jsFunction_"; final String staticFunctionPrefix = "jsStaticFunction_"; final String getterPrefix = "jsGet_"; final String setterPrefix = "jsSet_"; final String ctorName = "jsConstructor"; Member ctorMember = FunctionObject.findSingleMethod(methods, ctorName); if (ctorMember == null) { if (ctors.length == 1) { ctorMember = ctors[0]; } else if (ctors.length == 2) { if (ctors[0].getParameterTypes().length == 0) ctorMember = ctors[1]; else if (ctors[1].getParameterTypes().length == 0) ctorMember = ctors[0]; } if (ctorMember == null) { throw Context.reportRuntimeError1( "msg.ctor.multiple.parms", clazz.getName()); } } FunctionObject ctor = new FunctionObject(className, ctorMember, scope); if (ctor.isVarArgsMethod()) { throw Context.reportRuntimeError1 ("msg.varargs.ctor", ctorMember.getName()); } ctor.initAsConstructor(scope, proto); Method finishInit = null; HashSet names = new HashSet(methods.length); for (int i=0; i < methods.length; i++) { if (methods[i] == ctorMember) { continue; } String name = methods[i].getName(); if (name.equals("finishInit")) { Class[] parmTypes = methods[i].getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ScriptableClass && parmTypes[1] == FunctionObject.class && parmTypes[2] == ScriptRuntime.ScriptableClass && Modifier.isStatic(methods[i].getModifiers())) { finishInit = methods[i]; continue; } } // ignore any compiler generated methods. if (name.indexOf('$') != -1) continue; if (name.equals(ctorName)) continue; String prefix = null; if (name.startsWith(functionPrefix)) { prefix = functionPrefix; } else if (name.startsWith(staticFunctionPrefix)) { prefix = staticFunctionPrefix; if (!Modifier.isStatic(methods[i].getModifiers())) { throw Context.reportRuntimeError( "jsStaticFunction must be used with static method."); } } else if (name.startsWith(getterPrefix)) { prefix = getterPrefix; } else { // note that setterPrefix is among the unhandled names here - // we deal with that when we see the getter continue; } String propName = name.substring(prefix.length()); if (names.contains(propName)) { throw Context.reportRuntimeError2("duplicate.defineClass.name", name, propName); } names.add(propName); name = name.substring(prefix.length()); if (prefix == getterPrefix) { if (!(proto instanceof ScriptableObject)) { throw Context.reportRuntimeError2( "msg.extend.scriptable", proto.getClass().toString(), name); } Method setter = FunctionObject.findSingleMethod( methods, setterPrefix + name); int attr = ScriptableObject.PERMANENT | ScriptableObject.DONTENUM | (setter != null ? 0 : ScriptableObject.READONLY); ((ScriptableObject) proto).defineProperty(name, null, methods[i], setter, attr); continue; } FunctionObject f = new FunctionObject(name, methods[i], proto); if (f.isVarArgsConstructor()) { throw Context.reportRuntimeError1 ("msg.varargs.fun", ctorMember.getName()); } Scriptable dest = prefix == staticFunctionPrefix ? ctor : proto; defineProperty(dest, name, f, DONTENUM); if (sealed) { f.sealObject(); } } // Call user code to complete initialization if necessary. if (finishInit != null) { Object[] finishArgs = { scope, ctor, proto }; finishInit.invoke(null, finishArgs); } // Seal the object if necessary. if (sealed) { ctor.sealObject(); if (proto instanceof ScriptableObject) { ((ScriptableObject) proto).sealObject(); } } return ctor; } @SuppressWarnings({"unchecked"}) private static Class extendsScriptable(Class c) { if (ScriptRuntime.ScriptableClass.isAssignableFrom(c)) return (Class) c; return null; } /** * Define a JavaScript property. * * Creates the property with an initial value and sets its attributes. * * @param propertyName the name of the property to define. * @param value the initial value of the property * @param attributes the attributes of the JavaScript property * @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object) */ public void defineProperty(String propertyName, Object value, int attributes) { checkNotSealed(propertyName, 0); put(propertyName, this, value); setAttributes(propertyName, attributes); } /** * Utility method to add properties to arbitrary Scriptable object. * If destination is instance of ScriptableObject, calls * defineProperty there, otherwise calls put in destination * ignoring attributes */ public static void defineProperty(Scriptable destination, String propertyName, Object value, int attributes) { if (!(destination instanceof ScriptableObject)) { destination.put(propertyName, destination, value); return; } ScriptableObject so = (ScriptableObject)destination; so.defineProperty(propertyName, value, attributes); } /** * Utility method to add properties to arbitrary Scriptable object. * If destination is instance of ScriptableObject, calls * defineProperty there, otherwise calls put in destination * ignoring attributes */ public static void defineConstProperty(Scriptable destination, String propertyName) { if (destination instanceof ConstProperties) { ConstProperties cp = (ConstProperties)destination; cp.defineConst(propertyName, destination); } else defineProperty(destination, propertyName, Undefined.instance, CONST); } /** * Define a JavaScript property with getter and setter side effects. * * If the setter is not found, the attribute READONLY is added to * the given attributes.

* * The getter must be a method with zero parameters, and the setter, if * found, must be a method with one parameter.

* * @param propertyName the name of the property to define. This name * also affects the name of the setter and getter * to search for. If the propertyId is "foo", then * clazz will be searched for "getFoo" * and "setFoo" methods. * @param clazz the Java class to search for the getter and setter * @param attributes the attributes of the JavaScript property * @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object) */ public void defineProperty(String propertyName, Class clazz, int attributes) { int length = propertyName.length(); if (length == 0) throw new IllegalArgumentException(); char[] buf = new char[3 + length]; propertyName.getChars(0, length, buf, 3); buf[3] = Character.toUpperCase(buf[3]); buf[0] = 'g'; buf[1] = 'e'; buf[2] = 't'; String getterName = new String(buf); buf[0] = 's'; String setterName = new String(buf); Method[] methods = FunctionObject.getMethodList(clazz); Method getter = FunctionObject.findSingleMethod(methods, getterName); Method setter = FunctionObject.findSingleMethod(methods, setterName); if (setter == null) attributes |= ScriptableObject.READONLY; defineProperty(propertyName, null, getter, setter == null ? null : setter, attributes); } /** * Define a JavaScript property. * * Use this method only if you wish to define getters and setters for * a given property in a ScriptableObject. To create a property without * special getter or setter side effects, use * defineProperty(String,int). * * If setter is null, the attribute READONLY is added to * the given attributes.

* * Several forms of getters or setters are allowed. In all cases the * type of the value parameter can be any one of the following types: * Object, String, boolean, Scriptable, byte, short, int, long, float, * or double. The runtime will perform appropriate conversions based * upon the type of the parameter (see description in FunctionObject). * The first forms are nonstatic methods of the class referred to * by 'this': *

     * Object getFoo();
     * void setFoo(SomeType value);
* Next are static methods that may be of any class; the object whose * property is being accessed is passed in as an extra argument: *
     * static Object getFoo(Scriptable obj);
     * static void setFoo(Scriptable obj, SomeType value);
* Finally, it is possible to delegate to another object entirely using * the delegateTo parameter. In this case the methods are * nonstatic methods of the class delegated to, and the object whose * property is being accessed is passed in as an extra argument: *
     * Object getFoo(Scriptable obj);
     * void setFoo(Scriptable obj, SomeType value);
* * @param propertyName the name of the property to define. * @param delegateTo an object to call the getter and setter methods on, * or null, depending on the form used above. * @param getter the method to invoke to get the value of the property * @param setter the method to invoke to set the value of the property * @param attributes the attributes of the JavaScript property */ public void defineProperty(String propertyName, Object delegateTo, Method getter, Method setter, int attributes) { MemberBox getterBox = null; if (getter != null) { getterBox = new MemberBox(getter); boolean delegatedForm; if (!Modifier.isStatic(getter.getModifiers())) { delegatedForm = (delegateTo != null); getterBox.delegateTo = delegateTo; } else { delegatedForm = true; // Ignore delegateTo for static getter but store // non-null delegateTo indicator. getterBox.delegateTo = Void.TYPE; } String errorId = null; Class[] parmTypes = getter.getParameterTypes(); if (parmTypes.length == 0) { if (delegatedForm) { errorId = "msg.obj.getter.parms"; } } else if (parmTypes.length == 1) { Object argType = parmTypes[0]; // Allow ScriptableObject for compatibility if (!(argType == ScriptRuntime.ScriptableClass || argType == ScriptRuntime.ScriptableObjectClass)) { errorId = "msg.bad.getter.parms"; } else if (!delegatedForm) { errorId = "msg.bad.getter.parms"; } } else { errorId = "msg.bad.getter.parms"; } if (errorId != null) { throw Context.reportRuntimeError1(errorId, getter.toString()); } } MemberBox setterBox = null; if (setter != null) { if (setter.getReturnType() != Void.TYPE) throw Context.reportRuntimeError1("msg.setter.return", setter.toString()); setterBox = new MemberBox(setter); boolean delegatedForm; if (!Modifier.isStatic(setter.getModifiers())) { delegatedForm = (delegateTo != null); setterBox.delegateTo = delegateTo; } else { delegatedForm = true; // Ignore delegateTo for static setter but store // non-null delegateTo indicator. setterBox.delegateTo = Void.TYPE; } String errorId = null; Class[] parmTypes = setter.getParameterTypes(); if (parmTypes.length == 1) { if (delegatedForm) { errorId = "msg.setter2.expected"; } } else if (parmTypes.length == 2) { Object argType = parmTypes[0]; // Allow ScriptableObject for compatibility if (!(argType == ScriptRuntime.ScriptableClass || argType == ScriptRuntime.ScriptableObjectClass)) { errorId = "msg.setter2.parms"; } else if (!delegatedForm) { errorId = "msg.setter1.parms"; } } else { errorId = "msg.setter.parms"; } if (errorId != null) { throw Context.reportRuntimeError1(errorId, setter.toString()); } } GetterSlot gslot = (GetterSlot)getSlot(propertyName, 0, SLOT_MODIFY_GETTER_SETTER); gslot.setAttributes(attributes); gslot.getter = getterBox; gslot.setter = setterBox; } public void defineOwnProperties(Context cx, ScriptableObject props) { Object[] ids = props.getIds(); for (Object id : ids) { String name = ScriptRuntime.toString(id); Object descObj = props.get(id); ScriptableObject desc = ensureScriptableObject(descObj); checkValidPropertyDefinition(getSlot(name, 0, SLOT_QUERY), desc); } for (Object id : ids) { String name = ScriptRuntime.toString(id); ScriptableObject desc = (ScriptableObject) props.get(id); defineOwnProperty(cx, name, desc, false); } } /** * Defines a property on an object * * Based on [[DefineOwnProperty]] from 8.12.10 of the spec * * @param name the name of the property * @param desc the new property descriptor, as described in 8.6.1 */ public void defineOwnProperty(Context cx, Object id, ScriptableObject desc) { defineOwnProperty(cx, id, desc, true); } private void defineOwnProperty(Context cx, Object id, ScriptableObject desc, boolean checkValid) { Slot slot = getSlot(cx, id, SLOT_QUERY); if (checkValid) checkValidPropertyDefinition(slot, desc); final int attributes; if (slot == null) { // new slot slot = getSlot(cx, id, SLOT_MODIFY); attributes = applyDescriptorToAttributeBitset(DONTENUM|READONLY|PERMANENT, desc); } else { attributes = applyDescriptorToAttributeBitset(slot.getAttributes(), desc); } defineOwnProperty(cx, slot, desc, attributes); } private void defineOwnProperty(Context cx, Slot slot, ScriptableObject desc, int attributes) { if (isAccessorDescriptor(desc)) { if ( !(slot instanceof GetterSlot) ) slot = getSlot(cx, slot.name, SLOT_MODIFY_GETTER_SETTER); GetterSlot gslot = (GetterSlot) slot; Object getter = getProperty(desc, "get"); if (getter != NOT_FOUND) { gslot.getter = getter; } Object setter = getProperty(desc, "set"); if (setter != NOT_FOUND) { gslot.setter = setter; } gslot.value = Undefined.instance; gslot.setAttributes(attributes); } else { if (slot instanceof GetterSlot && isDataDescriptor(desc)) { slot = getSlot(cx, slot.name, SLOT_CONVERT_ACCESSOR_TO_DATA); } Object value = getProperty(desc, "value"); if (value != NOT_FOUND) { slot.value = value; } slot.setAttributes(attributes); } } private void checkValidPropertyDefinition(Slot slot, ScriptableObject desc) { Object getter = getProperty(desc, "get"); if (getter != NOT_FOUND && !(getter instanceof Callable)) { throw ScriptRuntime.notFunctionError(getter); } Object setter = getProperty(desc, "set"); if (setter != NOT_FOUND && !(setter instanceof Callable)) { throw ScriptRuntime.notFunctionError(setter); } if (slot == null) { // new property if (!isExtensible()) throw ScriptRuntime.typeError("msg.not.extensible"); } else { String name = slot.name; ScriptableObject current = getOwnPropertyDescriptor(Context.getContext(), name); if (Boolean.FALSE.equals(current.get("configurable")) ) { if (Boolean.TRUE.equals(tryBoolean(getProperty(desc, "configurable")))) throw ScriptRuntime.typeError1("msg.change.configurable.false.to.true", name); if (changes(current.get("enumerable"), tryBoolean(getProperty(desc, "enumerable")))) throw ScriptRuntime.typeError1("msg.change.enumerable.with.configurable.false", name); if (isGenericDescriptor(desc)) { // no further validation required } else if (isDataDescriptor(desc) && isDataDescriptor(current)) { if (Boolean.FALSE.equals(current.get("writable"))) { if (Boolean.TRUE.equals(tryBoolean(getProperty(desc, "writable")))) throw ScriptRuntime.typeError1("msg.change.writable.false.to.true.with.configurable.false", name); if (changes(current.get("value"), getProperty(desc, "value"))) throw ScriptRuntime.typeError1("msg.change.value.with.writable.false", name); } } else if (isAccessorDescriptor(desc) && isAccessorDescriptor(current)) { if (changes(current.get("set"), setter)) throw ScriptRuntime.typeError1("msg.change.setter.with.configurable.false", name); if (changes(current.get("get"), getter)) throw ScriptRuntime.typeError1("msg.change.getter.with.configurable.false", name); } else { if (isDataDescriptor(current)) throw ScriptRuntime.typeError1("msg.change.property.data.to.accessor.with.configurable.false", name); else throw ScriptRuntime.typeError1("msg.change.property.accessor.to.data.with.configurable.false", name); } } } } private static Object tryBoolean(Object value) { if (value == NOT_FOUND) return NOT_FOUND; return ScriptRuntime.toBoolean(value); } private boolean changes(Object currentValue, Object newValue) { return (newValue != NOT_FOUND) && (currentValue == NOT_FOUND || ! ScriptRuntime.shallowEq(currentValue, newValue)); } private int applyDescriptorToAttributeBitset(int attributes, ScriptableObject desc) { Object enumerable = getProperty(desc, "enumerable"); if (enumerable != NOT_FOUND) { attributes = ScriptRuntime.toBoolean(enumerable) ? attributes & ~DONTENUM : attributes | DONTENUM; } Object writable = getProperty(desc, "writable"); if (writable != NOT_FOUND) { attributes = ScriptRuntime.toBoolean(writable) ? attributes & ~READONLY : attributes | READONLY; } Object configurable = getProperty(desc, "configurable"); if (configurable != NOT_FOUND) { attributes = ScriptRuntime.toBoolean(configurable) ? attributes & ~PERMANENT : attributes | PERMANENT; } return attributes; } protected boolean isDataDescriptor(ScriptableObject desc) { return hasProperty(desc, "value") || hasProperty(desc, "writable"); } protected boolean isAccessorDescriptor(ScriptableObject desc) { return hasProperty(desc, "get") || hasProperty(desc, "set"); } protected boolean isGenericDescriptor(ScriptableObject desc) { return !isDataDescriptor(desc) && !isAccessorDescriptor(desc); } protected Scriptable ensureScriptable(Object arg) { if ( !(arg instanceof Scriptable) ) throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg)); return (Scriptable) arg; } protected ScriptableObject ensureScriptableObject(Object arg) { if ( !(arg instanceof ScriptableObject) ) throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg)); return (ScriptableObject) arg; } /** * Search for names in a class, adding the resulting methods * as properties. * *

Uses reflection to find the methods of the given names. Then * FunctionObjects are constructed from the methods found, and * are added to this object as properties with the given names. * * @param names the names of the Methods to add as function properties * @param clazz the class to search for the Methods * @param attributes the attributes of the new properties * @see org.mozilla.javascript.FunctionObject */ public void defineFunctionProperties(String[] names, Class clazz, int attributes) { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < names.length; i++) { String name = names[i]; Method m = FunctionObject.findSingleMethod(methods, name); if (m == null) { throw Context.reportRuntimeError2( "msg.method.not.found", name, clazz.getName()); } FunctionObject f = new FunctionObject(name, m, this); defineProperty(name, f, attributes); } } /** * Get the Object.prototype property. * See ECMA 15.2.4. */ public static Scriptable getObjectPrototype(Scriptable scope) { return getClassPrototype(scope, "Object"); } /** * Get the Function.prototype property. * See ECMA 15.3.4. */ public static Scriptable getFunctionPrototype(Scriptable scope) { return getClassPrototype(scope, "Function"); } /** * Get the prototype for the named class. * * For example, getClassPrototype(s, "Date") will first * walk up the parent chain to find the outermost scope, then will * search that scope for the Date constructor, and then will * return Date.prototype. If any of the lookups fail, or * the prototype is not a JavaScript object, then null will * be returned. * * @param scope an object in the scope chain * @param className the name of the constructor * @return the prototype for the named class, or null if it * cannot be found. */ public static Scriptable getClassPrototype(Scriptable scope, String className) { scope = getTopLevelScope(scope); Object ctor = getProperty(scope, className); Object proto; if (ctor instanceof BaseFunction) { proto = ((BaseFunction)ctor).getPrototypeProperty(); } else if (ctor instanceof Scriptable) { Scriptable ctorObj = (Scriptable)ctor; proto = ctorObj.get("prototype", ctorObj); } else { return null; } if (proto instanceof Scriptable) { return (Scriptable)proto; } return null; } /** * Get the global scope. * *

Walks the parent scope chain to find an object with a null * parent scope (the global object). * * @param obj a JavaScript object * @return the corresponding global scope */ public static Scriptable getTopLevelScope(Scriptable obj) { for (;;) { Scriptable parent = obj.getParentScope(); if (parent == null) { return obj; } obj = parent; } } public boolean isExtensible() { return isExtensible; } public void preventExtensions() { isExtensible = false; } /** * Seal this object. * * It is an error to add properties to or delete properties from * a sealed object. It is possible to change the value of an * existing property. Once an object is sealed it may not be unsealed. * * @since 1.4R3 */ public synchronized void sealObject() { if (count >= 0) { // Make sure all LazilyLoadedCtors are initialized before sealing. Slot slot = firstAdded; while (slot != null) { if (slot.value instanceof LazilyLoadedCtor) { LazilyLoadedCtor initializer = (LazilyLoadedCtor) slot.value; try { initializer.init(); } finally { slot.value = initializer.getValue(); } } slot = slot.orderedNext; } count = ~count; } } /** * Return true if this object is sealed. * * @return true if sealed, false otherwise. * @since 1.4R3 * @see #sealObject() */ public final boolean isSealed() { return count < 0; } private void checkNotSealed(String name, int index) { if (!isSealed()) return; String str = (name != null) ? name : Integer.toString(index); throw Context.reportRuntimeError1("msg.modify.sealed", str); } /** * Gets a named property from an object or any object in its prototype chain. *

* Searches the prototype chain for a property named name. *

* @param obj a JavaScript object * @param name a property name * @return the value of a property with name name found in * obj or any object in its prototype chain, or * Scriptable.NOT_FOUND if not found * @since 1.5R2 */ public static Object getProperty(Scriptable obj, String name) { Scriptable start = obj; Object result; do { result = obj.get(name, start); if (result != Scriptable.NOT_FOUND) break; obj = obj.getPrototype(); } while (obj != null); return result; } /** * Gets an indexed property from an object or any object in its prototype chain. *

* Searches the prototype chain for a property with integral index * index. Note that if you wish to look for properties with numerical * but non-integral indicies, you should use getProperty(Scriptable,String) with * the string value of the index. *

* @param obj a JavaScript object * @param index an integral index * @return the value of a property with index index found in * obj or any object in its prototype chain, or * Scriptable.NOT_FOUND if not found * @since 1.5R2 */ public static Object getProperty(Scriptable obj, int index) { Scriptable start = obj; Object result; do { result = obj.get(index, start); if (result != Scriptable.NOT_FOUND) break; obj = obj.getPrototype(); } while (obj != null); return result; } /** * Returns whether a named property is defined in an object or any object * in its prototype chain. *

* Searches the prototype chain for a property named name. *

* @param obj a JavaScript object * @param name a property name * @return the true if property was found * @since 1.5R2 */ public static boolean hasProperty(Scriptable obj, String name) { return null != getBase(obj, name); } /** * If hasProperty(obj, name) would return true, then if the property that * was found is compatible with the new property, this method just returns. * If the property is not compatible, then an exception is thrown. * * A property redefinition is incompatible if the first definition was a * const declaration or if this one is. They are compatible only if neither * was const. */ public static void redefineProperty(Scriptable obj, String name, boolean isConst) { Scriptable base = getBase(obj, name); if (base == null) return; if (base instanceof ConstProperties) { ConstProperties cp = (ConstProperties)base; if (cp.isConst(name)) throw Context.reportRuntimeError1("msg.const.redecl", name); } if (isConst) throw Context.reportRuntimeError1("msg.var.redecl", name); } /** * Returns whether an indexed property is defined in an object or any object * in its prototype chain. *

* Searches the prototype chain for a property with index index. *

* @param obj a JavaScript object * @param index a property index * @return the true if property was found * @since 1.5R2 */ public static boolean hasProperty(Scriptable obj, int index) { return null != getBase(obj, index); } /** * Puts a named property in an object or in an object in its prototype chain. *

* Searches for the named property in the prototype chain. If it is found, * the value of the property in obj is changed through a call * to {@link Scriptable#put(String, Scriptable, Object)} on the * prototype passing obj as the start argument. * This allows the prototype to veto the property setting in case the * prototype defines the property with [[ReadOnly]] attribute. If the * property is not found, it is added in obj. * @param obj a JavaScript object * @param name a property name * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putProperty(Scriptable obj, String name, Object value) { Scriptable base = getBase(obj, name); if (base == null) base = obj; base.put(name, obj, value); } /** * Puts a named property in an object or in an object in its prototype chain. *

* Searches for the named property in the prototype chain. If it is found, * the value of the property in obj is changed through a call * to {@link Scriptable#put(String, Scriptable, Object)} on the * prototype passing obj as the start argument. * This allows the prototype to veto the property setting in case the * prototype defines the property with [[ReadOnly]] attribute. If the * property is not found, it is added in obj. * @param obj a JavaScript object * @param name a property name * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putConstProperty(Scriptable obj, String name, Object value) { Scriptable base = getBase(obj, name); if (base == null) base = obj; if (base instanceof ConstProperties) ((ConstProperties)base).putConst(name, obj, value); } /** * Puts an indexed property in an object or in an object in its prototype chain. *

* Searches for the indexed property in the prototype chain. If it is found, * the value of the property in obj is changed through a call * to {@link Scriptable#put(int, Scriptable, Object)} on the prototype * passing obj as the start argument. This allows * the prototype to veto the property setting in case the prototype defines * the property with [[ReadOnly]] attribute. If the property is not found, * it is added in obj. * @param obj a JavaScript object * @param index a property index * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putProperty(Scriptable obj, int index, Object value) { Scriptable base = getBase(obj, index); if (base == null) base = obj; base.put(index, obj, value); } /** * Removes the property from an object or its prototype chain. *

* Searches for a property with name in obj or * its prototype chain. If it is found, the object's delete * method is called. * @param obj a JavaScript object * @param name a property name * @return true if the property doesn't exist or was successfully removed * @since 1.5R2 */ public static boolean deleteProperty(Scriptable obj, String name) { Scriptable base = getBase(obj, name); if (base == null) return true; base.delete(name); return !base.has(name, obj); } /** * Removes the property from an object or its prototype chain. *

* Searches for a property with index in obj or * its prototype chain. If it is found, the object's delete * method is called. * @param obj a JavaScript object * @param index a property index * @return true if the property doesn't exist or was successfully removed * @since 1.5R2 */ public static boolean deleteProperty(Scriptable obj, int index) { Scriptable base = getBase(obj, index); if (base == null) return true; base.delete(index); return !base.has(index, obj); } /** * Returns an array of all ids from an object and its prototypes. *

* @param obj a JavaScript object * @return an array of all ids from all object in the prototype chain. * If a given id occurs multiple times in the prototype chain, * it will occur only once in this list. * @since 1.5R2 */ public static Object[] getPropertyIds(Scriptable obj) { if (obj == null) { return ScriptRuntime.emptyArgs; } Object[] result = obj.getIds(); ObjToIntMap map = null; for (;;) { obj = obj.getPrototype(); if (obj == null) { break; } Object[] ids = obj.getIds(); if (ids.length == 0) { continue; } if (map == null) { if (result.length == 0) { result = ids; continue; } map = new ObjToIntMap(result.length + ids.length); for (int i = 0; i != result.length; ++i) { map.intern(result[i]); } result = null; // Allow to GC the result } for (int i = 0; i != ids.length; ++i) { map.intern(ids[i]); } } if (map != null) { result = map.getKeys(); } return result; } /** * Call a method of an object. * @param obj the JavaScript object * @param methodName the name of the function property * @param args the arguments for the call * * @see Context#getCurrentContext() */ public static Object callMethod(Scriptable obj, String methodName, Object[] args) { return callMethod(null, obj, methodName, args); } /** * Call a method of an object. * @param cx the Context object associated with the current thread. * @param obj the JavaScript object * @param methodName the name of the function property * @param args the arguments for the call */ public static Object callMethod(Context cx, Scriptable obj, String methodName, Object[] args) { Object funObj = getProperty(obj, methodName); if (!(funObj instanceof Function)) { throw ScriptRuntime.notFunctionError(obj, methodName); } Function fun = (Function)funObj; // XXX: What should be the scope when calling funObj? // The following favor scope stored in the object on the assumption // that is more useful especially under dynamic scope setup. // An alternative is to check for dynamic scope flag // and use ScriptableObject.getTopLevelScope(fun) if the flag is not // set. But that require access to Context and messy code // so for now it is not checked. Scriptable scope = ScriptableObject.getTopLevelScope(obj); if (cx != null) { return fun.call(cx, scope, obj, args); } else { return Context.call(null, fun, scope, obj, args); } } private static Scriptable getBase(Scriptable obj, String name) { do { if (obj.has(name, obj)) break; obj = obj.getPrototype(); } while(obj != null); return obj; } private static Scriptable getBase(Scriptable obj, int index) { do { if (obj.has(index, obj)) break; obj = obj.getPrototype(); } while(obj != null); return obj; } /** * Get arbitrary application-specific value associated with this object. * @param key key object to select particular value. * @see #associateValue(Object key, Object value) */ public final Object getAssociatedValue(Object key) { Map h = associatedValues; if (h == null) return null; return h.get(key); } /** * Get arbitrary application-specific value associated with the top scope * of the given scope. * The method first calls {@link #getTopLevelScope(Scriptable scope)} * and then searches the prototype chain of the top scope for the first * object containing the associated value with the given key. * * @param scope the starting scope. * @param key key object to select particular value. * @see #getAssociatedValue(Object key) */ public static Object getTopScopeValue(Scriptable scope, Object key) { scope = ScriptableObject.getTopLevelScope(scope); for (;;) { if (scope instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)scope; Object value = so.getAssociatedValue(key); if (value != null) { return value; } } scope = scope.getPrototype(); if (scope == null) { return null; } } } /** * Associate arbitrary application-specific value with this object. * Value can only be associated with the given object and key only once. * The method ignores any subsequent attempts to change the already * associated value. *

The associated values are not serialized. * @param key key object to select particular value. * @param value the value to associate * @return the passed value if the method is called first time for the * given key or old value for any subsequent calls. * @see #getAssociatedValue(Object key) */ public synchronized final Object associateValue(Object key, Object value) { if (value == null) throw new IllegalArgumentException(); Map h = associatedValues; if (h == null) { h = new HashMap(); associatedValues = h; } return Kit.initHash(h, key, value); } private Object getImpl(String name, int index, Scriptable start) { Slot slot = getSlot(name, index, SLOT_QUERY); if (slot == null) { return Scriptable.NOT_FOUND; } if (!(slot instanceof GetterSlot)) { return slot.value; } Object getterObj = ((GetterSlot)slot).getter; if (getterObj != null) { if (getterObj instanceof MemberBox) { MemberBox nativeGetter = (MemberBox)getterObj; Object getterThis; Object[] args; if (nativeGetter.delegateTo == null) { getterThis = start; args = ScriptRuntime.emptyArgs; } else { getterThis = nativeGetter.delegateTo; args = new Object[] { start }; } return nativeGetter.invoke(getterThis, args); } else { Function f = (Function)getterObj; Context cx = Context.getContext(); return f.call(cx, f.getParentScope(), start, ScriptRuntime.emptyArgs); } } Object value = slot.value; if (value instanceof LazilyLoadedCtor) { LazilyLoadedCtor initializer = (LazilyLoadedCtor)value; try { initializer.init(); } finally { value = initializer.getValue(); slot.value = value; } } return value; } /** * * @param name * @param index * @param start * @param value * @param constFlag EMPTY means normal put. UNINITIALIZED_CONST means * defineConstProperty. READONLY means const initialization expression. * @return false if this != start and no slot was found. true if this == start * or this != start and a READONLY slot was found. */ private boolean putImpl(String name, int index, Scriptable start, Object value, int constFlag) { Slot slot; if (this != start) { slot = getSlot(name, index, SLOT_QUERY); if (slot == null) { return false; } } else if (!isExtensible()) { slot = getSlot(name, index, SLOT_QUERY); if (slot == null) { return true; } } else { checkNotSealed(name, index); // either const hoisted declaration or initialization if (constFlag != EMPTY) { slot = getSlot(name, index, SLOT_MODIFY_CONST); int attr = slot.getAttributes(); if ((attr & READONLY) == 0) throw Context.reportRuntimeError1("msg.var.redecl", name); if ((attr & UNINITIALIZED_CONST) != 0) { slot.value = value; // clear the bit on const initialization if (constFlag != UNINITIALIZED_CONST) slot.setAttributes(attr & ~UNINITIALIZED_CONST); } return true; } slot = getSlot(name, index, SLOT_MODIFY); } if ((slot.getAttributes() & READONLY) != 0) return true; if (slot instanceof GetterSlot) { Object setterObj = ((GetterSlot)slot).setter; if (setterObj == null) { if (((GetterSlot)slot).getter != null) { if (Context.getContext().hasFeature(Context.FEATURE_HTMLUNIT_WRITE_READONLY_PROPERTIES)) { // Odd case: Assignment to a property with only a getter // defined. The assignment cancels out the getter. ((GetterSlot)slot).getter = null; } else { // Based on TC39 ES3.1 Draft of 9-Feb-2009, 8.12.4, step 2, // we should throw a TypeError in this case. throw ScriptRuntime.typeError1("msg.set.prop.no.setter", name); } } } else { Context cx = Context.getContext(); if (setterObj instanceof MemberBox) { MemberBox nativeSetter = (MemberBox)setterObj; Class pTypes[] = nativeSetter.argTypes; // XXX: cache tag since it is already calculated in // defineProperty ? Class valueType = pTypes[pTypes.length - 1]; int tag = FunctionObject.getTypeTag(valueType); Object actualArg = FunctionObject.convertArg(cx, start, value, tag); Object setterThis; Object[] args; if (nativeSetter.delegateTo == null) { setterThis = start; args = new Object[] { actualArg }; } else { setterThis = nativeSetter.delegateTo; args = new Object[] { start, actualArg }; } nativeSetter.invoke(setterThis, args); } else { Function f = (Function)setterObj; f.call(cx, f.getParentScope(), start, new Object[] { value }); } return true; } } if (this == start) { slot.value = value; return true; } else { return false; } } private Slot findAttributeSlot(String name, int index, int accessType) { Slot slot = getSlot(name, index, accessType); if (slot == null) { String str = (name != null ? name : Integer.toString(index)); throw Context.reportRuntimeError1("msg.prop.not.found", str); } return slot; } /** * Locate the slot with given name or index. * * @param name property name or null if slot holds spare array index. * @param index index or 0 if slot holds property name. */ private Slot getSlot(String name, int index, int accessType) { Slot slot; // Query last access cache and check that it was not deleted. lastAccessCheck: { slot = lastAccess; if (name != null) { if (name != slot.name) break lastAccessCheck; // No String.equals here as successful slot search update // name object with fresh reference of the same string. } else { if (slot.name != null || index != slot.indexOrHash) break lastAccessCheck; } if (slot.wasDeleted) break lastAccessCheck; if (accessType == SLOT_MODIFY_GETTER_SETTER && !(slot instanceof GetterSlot)) break lastAccessCheck; if (accessType == SLOT_CONVERT_ACCESSOR_TO_DATA && (slot instanceof GetterSlot)) break lastAccessCheck; return slot; } slot = accessSlot(name, index, accessType); if (slot != null) { // Update the cache lastAccess = slot; } return slot; } private Slot accessSlot(String name, int index, int accessType) { int indexOrHash = (name != null ? name.hashCode() : index); if (accessType == SLOT_QUERY || accessType == SLOT_MODIFY || accessType == SLOT_MODIFY_CONST || accessType == SLOT_MODIFY_GETTER_SETTER || accessType == SLOT_CONVERT_ACCESSOR_TO_DATA) { // Check the hashtable without using synchronization Slot[] slotsLocalRef = slots; // Get stable local reference if (slotsLocalRef == null) { if (accessType == SLOT_QUERY) return null; } else { int tableSize = slotsLocalRef.length; int slotIndex = getSlotIndex(tableSize, indexOrHash); Slot slot = slotsLocalRef[slotIndex]; while (slot != null) { String sname = slot.name; if (sname != null) { if (sname == name) break; if (name != null && indexOrHash == slot.indexOrHash) { if (name.equals(sname)) { // This will avoid calling String.equals when // slot is accessed with same string object // next time. slot.name = name; break; } } } else if (name == null && indexOrHash == slot.indexOrHash) { break; } slot = slot.next; } if (accessType == SLOT_QUERY) { return slot; } else if (accessType == SLOT_MODIFY) { if (slot != null) return slot; } else if (accessType == SLOT_MODIFY_GETTER_SETTER) { if (slot instanceof GetterSlot) return slot; } else if (accessType == SLOT_MODIFY_CONST) { if (slot != null) return slot; } else if (accessType == SLOT_CONVERT_ACCESSOR_TO_DATA) { if ( !(slot instanceof GetterSlot) ) return slot; } } // A new slot has to be inserted or the old has to be replaced // by GetterSlot. Time to synchronize. synchronized (this) { // Refresh local ref if another thread triggered grow slotsLocalRef = slots; int insertPos; if (count == 0) { // Always throw away old slots if any on empty insert slotsLocalRef = new Slot[5]; slots = slotsLocalRef; insertPos = getSlotIndex(slotsLocalRef.length, indexOrHash); } else { int tableSize = slotsLocalRef.length; insertPos = getSlotIndex(tableSize, indexOrHash); Slot prev = slotsLocalRef[insertPos]; Slot slot = prev; while (slot != null) { if (slot.indexOrHash == indexOrHash && (slot.name == name || (name != null && name.equals(slot.name)))) { break; } prev = slot; slot = slot.next; } if (slot != null) { // Another thread just added a slot with same // name/index before this one entered synchronized // block. This is a race in application code and // probably indicates bug there. But for the hashtable // implementation it is harmless with the only // complication is the need to replace the added slot // if we need GetterSlot and the old one is not. Slot newSlot; if (accessType == SLOT_MODIFY_GETTER_SETTER && !(slot instanceof GetterSlot)) { newSlot = new GetterSlot(name, indexOrHash, slot.getAttributes()); } else if (accessType == SLOT_CONVERT_ACCESSOR_TO_DATA && (slot instanceof GetterSlot)) { newSlot = new Slot(name, indexOrHash, slot.getAttributes()); } else if (accessType == SLOT_MODIFY_CONST) { return null; } else { return slot; } newSlot.value = slot.value; newSlot.next = slot.next; // add new slot to linked list if (lastAdded != null) lastAdded.orderedNext = newSlot; if (firstAdded == null) firstAdded = newSlot; lastAdded = newSlot; // add new slot to hash table if (prev == slot) { slotsLocalRef[insertPos] = newSlot; } else { prev.next = newSlot; } // other housekeeping slot.wasDeleted = true; slot.value = null; slot.name = null; if (slot == lastAccess) { lastAccess = REMOVED; } return newSlot; } else { // Check if the table is not too full before inserting. if (4 * (count + 1) > 3 * slotsLocalRef.length) { slotsLocalRef = new Slot[slotsLocalRef.length * 2 + 1]; copyTable(slots, slotsLocalRef, count); slots = slotsLocalRef; insertPos = getSlotIndex(slotsLocalRef.length, indexOrHash); } } } Slot newSlot = (accessType == SLOT_MODIFY_GETTER_SETTER ? new GetterSlot(name, indexOrHash, 0) : new Slot(name, indexOrHash, 0)); if (accessType == SLOT_MODIFY_CONST) newSlot.setAttributes(CONST); ++count; // add new slot to linked list if (lastAdded != null) lastAdded.orderedNext = newSlot; if (firstAdded == null) firstAdded = newSlot; lastAdded = newSlot; // add new slot to hash table, return it addKnownAbsentSlot(slotsLocalRef, newSlot, insertPos); return newSlot; } } else if (accessType == SLOT_REMOVE) { synchronized (this) { Slot[] slotsLocalRef = slots; if (count != 0) { int tableSize = slots.length; int slotIndex = getSlotIndex(tableSize, indexOrHash); Slot prev = slotsLocalRef[slotIndex]; Slot slot = prev; while (slot != null) { if (slot.indexOrHash == indexOrHash && (slot.name == name || (name != null && name.equals(slot.name)))) { break; } prev = slot; slot = slot.next; } if (slot != null && (slot.getAttributes() & PERMANENT) == 0) { count--; // remove slot from hash table if (prev == slot) { slotsLocalRef[slotIndex] = slot.next; } else { prev.next = slot.next; } // Mark the slot as removed. It is still referenced // from the order-added linked list, but will be // cleaned up later slot.wasDeleted = true; slot.value = null; slot.name = null; if (slot == lastAccess) { lastAccess = REMOVED; } } } } return null; } else { throw Kit.codeBug(); } } private static int getSlotIndex(int tableSize, int indexOrHash) { return (indexOrHash & 0x7fffffff) % tableSize; } // Must be inside synchronized (this) private static void copyTable(Slot[] slots, Slot[] newSlots, int count) { if (count == 0) throw Kit.codeBug(); int tableSize = newSlots.length; int i = slots.length; for (;;) { --i; Slot slot = slots[i]; while (slot != null) { int insertPos = getSlotIndex(tableSize, slot.indexOrHash); Slot next = slot.next; addKnownAbsentSlot(newSlots, slot, insertPos); slot.next = null; slot = next; if (--count == 0) return; } } } /** * Add slot with keys that are known to absent from the table. * This is an optimization to use when inserting into empty table, * after table growth or during deserialization. */ private static void addKnownAbsentSlot(Slot[] slots, Slot slot, int insertPos) { if (slots[insertPos] == null) { slots[insertPos] = slot; } else { Slot prev = slots[insertPos]; while (prev.next != null) { prev = prev.next; } prev.next = slot; } } Object[] getIds(boolean getAll) { Slot[] s = slots; Object[] a = ScriptRuntime.emptyArgs; if (s == null) return a; int c = 0; Slot slot = firstAdded; while (slot != null && slot.wasDeleted) { // as long as we're traversing the order-added linked list, // remove deleted slots slot = slot.orderedNext; } firstAdded = slot; if (slot != null) { for (;;) { if (getAll || (slot.getAttributes() & DONTENUM) == 0) { if (c == 0) a = new Object[s.length]; a[c++] = slot.name != null ? (Object) slot.name : Integer.valueOf(slot.indexOrHash); } Slot next = slot.orderedNext; while (next != null && next.wasDeleted) { // remove deleted slots next = next.orderedNext; } slot.orderedNext = next; if (next == null) { break; } slot = next; } } lastAdded = slot; if (c == a.length) return a; Object[] result = new Object[c]; System.arraycopy(a, 0, result, 0, c); return result; } private synchronized void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); int objectsCount = count; if (objectsCount < 0) { // "this" was sealed objectsCount = ~objectsCount; } if (objectsCount == 0) { out.writeInt(0); } else { out.writeInt(slots.length); Slot slot = firstAdded; while (slot != null && slot.wasDeleted) { // as long as we're traversing the order-added linked list, // remove deleted slots slot = slot.orderedNext; } firstAdded = slot; while (slot != null) { out.writeObject(slot); Slot next = slot.orderedNext; while (next != null && next.wasDeleted) { // remove deleted slots next = next.orderedNext; } slot.orderedNext = next; slot = next; } } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); lastAccess = REMOVED; int tableSize = in.readInt(); if (tableSize != 0) { slots = new Slot[tableSize]; int objectsCount = count; if (objectsCount < 0) { // "this" was sealed objectsCount = ~objectsCount; } Slot prev = null; for (int i=0; i != objectsCount; ++i) { lastAdded = (Slot)in.readObject(); if (i==0) { firstAdded = lastAdded; } else { prev.orderedNext = lastAdded; } int slotIndex = getSlotIndex(tableSize, lastAdded.indexOrHash); addKnownAbsentSlot(slots, lastAdded, slotIndex); prev = lastAdded; } } } protected ScriptableObject getOwnPropertyDescriptor(Context cx, Object id) { Slot slot = getSlot(cx, id, SLOT_QUERY); if (slot == null) return null; Scriptable scope = getParentScope(); return slot.getPropertyDescriptor(cx, (scope == null ? this : scope)); } protected Slot getSlot(Context cx, Object id, int accessType) { final Slot slot; String name = ScriptRuntime.toStringIdOrIndex(cx, id); if (name == null) { int index = ScriptRuntime.lastIndexResult(cx); slot = getSlot(null, index, accessType); } else { slot = getSlot(name, 0, accessType); } return slot; } // Methods and classes to implement java.util.Map interface public int size() { return count; } public boolean isEmpty() { return count == 0; } public boolean containsKey(Object key) { if (key instanceof String) { return has((String) key, this); } else if (key instanceof Number) { return has(((Number) key).intValue(), this); } return false; } public boolean containsValue(Object value) { for (Object obj : values()) { if (value == obj || value != null && value.equals(obj)) { return true; } } return false; } public Object get(Object key) { Object value = null; if (key instanceof String) { value = get((String) key, this); } else if (key instanceof Number) { value = get(((Number) key).intValue(), this); } if (value == Scriptable.NOT_FOUND || value == Undefined.instance) { return null; } else if (value instanceof Wrapper) { return ((Wrapper) value).unwrap(); } else { return value; } } public Object remove(Object key) { Object value = get(key); if (key instanceof String) { delete((String) key); } else if (key instanceof Number) { delete(((Number) key).intValue()); } return value; } public Set keySet() { return new KeySet(); } public Collection values() { return new ValueCollection(); } public Set> entrySet() { return new EntrySet(); } public Object put(Object key, Object value) { throw new UnsupportedOperationException(); } public void putAll(Map m) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } class EntrySet extends AbstractSet> { @Override public Iterator> iterator() { return new Iterator>() { Object[] ids = getIds(); Object key = null; int index = 0; public boolean hasNext() { return index < ids.length; } public Map.Entry next() { final Object ekey = key = ids[index++]; final Object value = get(key); return new Map.Entry() { public Object getKey() { return ekey; } public Object getValue() { return value; } public Object setValue(Object value) { throw new UnsupportedOperationException(); } public boolean equals(Object other) { if (!(other instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) other; return (ekey == null ? e.getKey() == null : ekey.equals(e.getKey())) && (value == null ? e.getValue() == null : value.equals(e.getValue())); } public int hashCode() { return (ekey == null ? 0 : ekey.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public String toString() { return ekey + "=" + value; } }; } public void remove() { if (key == null) { throw new IllegalStateException(); } ScriptableObject.this.remove(key); key = null; } }; } @Override public int size() { return count; } } class KeySet extends AbstractSet { @Override public boolean contains(Object key) { return containsKey(key); } @Override public Iterator iterator() { return new Iterator() { Object[] ids = getIds(); Object key; int index = 0; public boolean hasNext() { return index < ids.length; } public Object next() { return (key = ids[index++]); } public void remove() { if (key == null) { throw new IllegalStateException(); } ScriptableObject.this.remove(key); key = null; } }; } @Override public int size() { return count; } } class ValueCollection extends AbstractCollection { @Override public Iterator iterator() { return new Iterator() { Object[] ids = getIds(); Object key; int index = 0; public boolean hasNext() { return index < ids.length; } public Object next() { return get((key = ids[index++])); } public void remove() { if (key == null) { throw new IllegalStateException(); } ScriptableObject.this.remove(key); key = null; } }; } @Override public int size() { return count; } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/Interpreter.java0000644000175000017500000034243411314263504033263 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Patrick Beard * Norris Boyd * Igor Bukanov * Ethan Hugg * Bob Jervis * Terry Lucas * Roger Lawrence * Milen Nankov * Hannes Wallnoefer * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.io.PrintStream; import java.io.Serializable; import java.util.List; import java.util.ArrayList; import java.util.Collections; import org.mozilla.javascript.ast.FunctionNode; import org.mozilla.javascript.ast.ScriptNode; import org.mozilla.javascript.ScriptRuntime.NoSuchMethodShim; import org.mozilla.javascript.debug.DebugFrame; public final class Interpreter extends Icode implements Evaluator { // data for parsing CompilerEnvirons compilerEnv; InterpreterData itsData; static final int EXCEPTION_TRY_START_SLOT = 0; static final int EXCEPTION_TRY_END_SLOT = 1; static final int EXCEPTION_HANDLER_SLOT = 2; static final int EXCEPTION_TYPE_SLOT = 3; static final int EXCEPTION_LOCAL_SLOT = 4; static final int EXCEPTION_SCOPE_SLOT = 5; // SLOT_SIZE: space for try start/end, handler, start, handler type, // exception local and scope local static final int EXCEPTION_SLOT_SIZE = 6; /** * Class to hold data corresponding to one interpreted call stack frame. */ private static class CallFrame implements Cloneable, Serializable { static final long serialVersionUID = -2843792508994958978L; CallFrame parentFrame; // amount of stack frames before this one on the interpretation stack int frameIndex; // If true indicates read-only frame that is a part of continuation boolean frozen; InterpretedFunction fnOrScript; InterpreterData idata; // Stack structure // stack[0 <= i < localShift]: arguments and local variables // stack[localShift <= i <= emptyStackTop]: used for local temporaries // stack[emptyStackTop < i < stack.length]: stack data // sDbl[i]: if stack[i] is UniqueTag.DOUBLE_MARK, sDbl[i] holds the number value Object[] stack; int[] stackAttributes; double[] sDbl; CallFrame varSource; // defaults to this unless continuation frame int localShift; int emptyStackTop; DebugFrame debuggerFrame; boolean useActivation; boolean isContinuationsTopFrame; Scriptable thisObj; Scriptable[] scriptRegExps; // The values that change during interpretation Object result; double resultDbl; int pc; int pcPrevBranch; int pcSourceLineStart; Scriptable scope; int savedStackTop; int savedCallOp; Object throwable; CallFrame cloneFrozen() { if (!frozen) Kit.codeBug(); CallFrame copy; try { copy = (CallFrame)clone(); } catch (CloneNotSupportedException ex) { throw new IllegalStateException(); } // clone stack but keep varSource to point to values // from this frame to share variables. copy.stack = stack.clone(); copy.stackAttributes = stackAttributes.clone(); copy.sDbl = sDbl.clone(); copy.frozen = false; return copy; } } private static final class ContinuationJump implements Serializable { static final long serialVersionUID = 7687739156004308247L; CallFrame capturedFrame; CallFrame branchFrame; Object result; double resultDbl; ContinuationJump(NativeContinuation c, CallFrame current) { this.capturedFrame = (CallFrame)c.getImplementation(); if (this.capturedFrame == null || current == null) { // Continuation and current execution does not share // any frames if there is nothing to capture or // if there is no currently executed frames this.branchFrame = null; } else { // Search for branch frame where parent frame chains starting // from captured and current meet. CallFrame chain1 = this.capturedFrame; CallFrame chain2 = current; // First work parents of chain1 or chain2 until the same // frame depth. int diff = chain1.frameIndex - chain2.frameIndex; if (diff != 0) { if (diff < 0) { // swap to make sure that // chain1.frameIndex > chain2.frameIndex and diff > 0 chain1 = current; chain2 = this.capturedFrame; diff = -diff; } do { chain1 = chain1.parentFrame; } while (--diff != 0); if (chain1.frameIndex != chain2.frameIndex) Kit.codeBug(); } // Now walk parents in parallel until a shared frame is found // or until the root is reached. while (chain1 != chain2 && chain1 != null) { chain1 = chain1.parentFrame; chain2 = chain2.parentFrame; } this.branchFrame = chain1; if (this.branchFrame != null && !this.branchFrame.frozen) Kit.codeBug(); } } } private static CallFrame captureFrameForGenerator(CallFrame frame) { frame.frozen = true; CallFrame result = frame.cloneFrozen(); frame.frozen = false; // now isolate this frame from its previous context result.parentFrame = null; result.frameIndex = 0; return result; } static { // Checks for byte code consistencies, good compiler can eliminate them if (Token.LAST_BYTECODE_TOKEN > 127) { String str = "Violation of Token.LAST_BYTECODE_TOKEN <= 127"; System.err.println(str); throw new IllegalStateException(str); } if (MIN_ICODE < -128) { String str = "Violation of Interpreter.MIN_ICODE >= -128"; System.err.println(str); throw new IllegalStateException(str); } } public Object compile(CompilerEnvirons compilerEnv, ScriptNode tree, String encodedSource, boolean returnFunction) { this.compilerEnv = compilerEnv; CodeGenerator cgen = new CodeGenerator(); itsData = cgen.compile(compilerEnv, tree, encodedSource, returnFunction); return itsData; } public Script createScriptObject(Object bytecode, Object staticSecurityDomain) { if(bytecode != itsData) { Kit.codeBug(); } return InterpretedFunction.createScript(itsData, staticSecurityDomain); } public void setEvalScriptFlag(Script script) { ((InterpretedFunction)script).idata.evalScriptFlag = true; } public Function createFunctionObject(Context cx, Scriptable scope, Object bytecode, Object staticSecurityDomain) { if(bytecode != itsData) { Kit.codeBug(); } return InterpretedFunction.createFunction(cx, scope, itsData, staticSecurityDomain); } private static int getShort(byte[] iCode, int pc) { return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF); } private static int getIndex(byte[] iCode, int pc) { return ((iCode[pc] & 0xFF) << 8) | (iCode[pc + 1] & 0xFF); } private static int getInt(byte[] iCode, int pc) { return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16) | ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF); } private static int getExceptionHandler(CallFrame frame, boolean onlyFinally) { int[] exceptionTable = frame.idata.itsExceptionTable; if (exceptionTable == null) { // No exception handlers return -1; } // Icode switch in the interpreter increments PC immediately // and it is necessary to subtract 1 from the saved PC // to point it before the start of the next instruction. int pc = frame.pc - 1; // OPT: use binary search int best = -1, bestStart = 0, bestEnd = 0; for (int i = 0; i != exceptionTable.length; i += EXCEPTION_SLOT_SIZE) { int start = exceptionTable[i + EXCEPTION_TRY_START_SLOT]; int end = exceptionTable[i + EXCEPTION_TRY_END_SLOT]; if (!(start <= pc && pc < end)) { continue; } if (onlyFinally && exceptionTable[i + EXCEPTION_TYPE_SLOT] != 1) { continue; } if (best >= 0) { // Since handlers always nest and they never have shared end // although they can share start it is sufficient to compare // handlers ends if (bestEnd < end) { continue; } // Check the above assumption if (bestStart > start) Kit.codeBug(); // should be nested if (bestEnd == end) Kit.codeBug(); // no ens sharing } best = i; bestStart = start; bestEnd = end; } return best; } static void dumpICode(InterpreterData idata) { if (!Token.printICode) { return; } byte iCode[] = idata.itsICode; int iCodeLength = iCode.length; String[] strings = idata.itsStringTable; PrintStream out = System.out; out.println("ICode dump, for " + idata.itsName + ", length = " + iCodeLength); out.println("MaxStack = " + idata.itsMaxStack); int indexReg = 0; for (int pc = 0; pc < iCodeLength; ) { out.flush(); out.print(" [" + pc + "] "); int token = iCode[pc]; int icodeLength = bytecodeSpan(token); String tname = Icode.bytecodeName(token); int old_pc = pc; ++pc; switch (token) { default: if (icodeLength != 1) Kit.codeBug(); out.println(tname); break; case Icode_GOSUB : case Token.GOTO : case Token.IFEQ : case Token.IFNE : case Icode_IFEQ_POP : case Icode_LEAVEDQ : { int newPC = pc + getShort(iCode, pc) - 1; out.println(tname + " " + newPC); pc += 2; break; } case Icode_VAR_INC_DEC : case Icode_NAME_INC_DEC : case Icode_PROP_INC_DEC : case Icode_ELEM_INC_DEC : case Icode_REF_INC_DEC: { int incrDecrType = iCode[pc]; out.println(tname + " " + incrDecrType); ++pc; break; } case Icode_CALLSPECIAL : { int callType = iCode[pc] & 0xFF; boolean isNew = (iCode[pc + 1] != 0); int line = getIndex(iCode, pc+2); out.println(tname+" "+callType+" "+isNew+" "+indexReg+" "+line); pc += 4; break; } case Token.CATCH_SCOPE: { boolean afterFisrtFlag = (iCode[pc] != 0); out.println(tname+" "+afterFisrtFlag); ++pc; } break; case Token.REGEXP : out.println(tname+" "+idata.itsRegExpLiterals[indexReg]); break; case Token.OBJECTLIT : case Icode_SPARE_ARRAYLIT : out.println(tname+" "+idata.literalIds[indexReg]); break; case Icode_CLOSURE_EXPR : case Icode_CLOSURE_STMT : out.println(tname+" "+idata.itsNestedFunctions[indexReg]); break; case Token.CALL : case Icode_TAIL_CALL : case Token.REF_CALL : case Token.NEW : out.println(tname+' '+indexReg); break; case Token.THROW : case Token.YIELD : case Icode_GENERATOR : case Icode_GENERATOR_END : { int line = getIndex(iCode, pc); out.println(tname + " : " + line); pc += 2; break; } case Icode_SHORTNUMBER : { int value = getShort(iCode, pc); out.println(tname + " " + value); pc += 2; break; } case Icode_INTNUMBER : { int value = getInt(iCode, pc); out.println(tname + " " + value); pc += 4; break; } case Token.NUMBER : { double value = idata.itsDoubleTable[indexReg]; out.println(tname + " " + value); break; } case Icode_LINE : { int line = getIndex(iCode, pc); out.println(tname + " : " + line); pc += 2; break; } case Icode_REG_STR1: { String str = strings[0xFF & iCode[pc]]; out.println(tname + " \"" + str + '"'); ++pc; break; } case Icode_REG_STR2: { String str = strings[getIndex(iCode, pc)]; out.println(tname + " \"" + str + '"'); pc += 2; break; } case Icode_REG_STR4: { String str = strings[getInt(iCode, pc)]; out.println(tname + " \"" + str + '"'); pc += 4; break; } case Icode_REG_IND_C0: indexReg = 0; out.println(tname); break; case Icode_REG_IND_C1: indexReg = 1; out.println(tname); break; case Icode_REG_IND_C2: indexReg = 2; out.println(tname); break; case Icode_REG_IND_C3: indexReg = 3; out.println(tname); break; case Icode_REG_IND_C4: indexReg = 4; out.println(tname); break; case Icode_REG_IND_C5: indexReg = 5; out.println(tname); break; case Icode_REG_IND1: { indexReg = 0xFF & iCode[pc]; out.println(tname+" "+indexReg); ++pc; break; } case Icode_REG_IND2: { indexReg = getIndex(iCode, pc); out.println(tname+" "+indexReg); pc += 2; break; } case Icode_REG_IND4: { indexReg = getInt(iCode, pc); out.println(tname+" "+indexReg); pc += 4; break; } case Icode_GETVAR1: case Icode_SETVAR1: case Icode_SETCONSTVAR1: indexReg = iCode[pc]; out.println(tname+" "+indexReg); ++pc; break; } if (old_pc + icodeLength != pc) Kit.codeBug(); } int[] table = idata.itsExceptionTable; if (table != null) { out.println("Exception handlers: " +table.length / EXCEPTION_SLOT_SIZE); for (int i = 0; i != table.length; i += EXCEPTION_SLOT_SIZE) { int tryStart = table[i + EXCEPTION_TRY_START_SLOT]; int tryEnd = table[i + EXCEPTION_TRY_END_SLOT]; int handlerStart = table[i + EXCEPTION_HANDLER_SLOT]; int type = table[i + EXCEPTION_TYPE_SLOT]; int exceptionLocal = table[i + EXCEPTION_LOCAL_SLOT]; int scopeLocal = table[i + EXCEPTION_SCOPE_SLOT]; out.println(" tryStart="+tryStart+" tryEnd="+tryEnd +" handlerStart="+handlerStart +" type="+(type == 0 ? "catch" : "finally") +" exceptionLocal="+exceptionLocal); } } out.flush(); } private static int bytecodeSpan(int bytecode) { switch (bytecode) { case Token.THROW : case Token.YIELD: case Icode_GENERATOR: case Icode_GENERATOR_END: // source line return 1 + 2; case Icode_GOSUB : case Token.GOTO : case Token.IFEQ : case Token.IFNE : case Icode_IFEQ_POP : case Icode_LEAVEDQ : // target pc offset return 1 + 2; case Icode_CALLSPECIAL : // call type // is new // line number return 1 + 1 + 1 + 2; case Token.CATCH_SCOPE: // scope flag return 1 + 1; case Icode_VAR_INC_DEC: case Icode_NAME_INC_DEC: case Icode_PROP_INC_DEC: case Icode_ELEM_INC_DEC: case Icode_REF_INC_DEC: // type of ++/-- return 1 + 1; case Icode_SHORTNUMBER : // short number return 1 + 2; case Icode_INTNUMBER : // int number return 1 + 4; case Icode_REG_IND1: // ubyte index return 1 + 1; case Icode_REG_IND2: // ushort index return 1 + 2; case Icode_REG_IND4: // int index return 1 + 4; case Icode_REG_STR1: // ubyte string index return 1 + 1; case Icode_REG_STR2: // ushort string index return 1 + 2; case Icode_REG_STR4: // int string index return 1 + 4; case Icode_GETVAR1: case Icode_SETVAR1: case Icode_SETCONSTVAR1: // byte var index return 1 + 1; case Icode_LINE : // line number return 1 + 2; } if (!validBytecode(bytecode)) throw Kit.codeBug(); return 1; } static int[] getLineNumbers(InterpreterData data) { UintMap presentLines = new UintMap(); byte[] iCode = data.itsICode; int iCodeLength = iCode.length; for (int pc = 0; pc != iCodeLength;) { int bytecode = iCode[pc]; int span = bytecodeSpan(bytecode); if (bytecode == Icode_LINE) { if (span != 3) Kit.codeBug(); int line = getIndex(iCode, pc + 1); presentLines.put(line, 0); } pc += span; } return presentLines.getKeys(); } public void captureStackInfo(RhinoException ex) { Context cx = Context.getCurrentContext(); if (cx == null || cx.lastInterpreterFrame == null) { // No interpreter invocations ex.interpreterStackInfo = null; ex.interpreterLineData = null; return; } // has interpreter frame on the stack CallFrame[] array; if (cx.previousInterpreterInvocations == null || cx.previousInterpreterInvocations.size() == 0) { array = new CallFrame[1]; } else { int previousCount = cx.previousInterpreterInvocations.size(); if (cx.previousInterpreterInvocations.peek() == cx.lastInterpreterFrame) { // It can happen if exception was generated after // frame was pushed to cx.previousInterpreterInvocations // but before assignment to cx.lastInterpreterFrame. // In this case frames has to be ignored. --previousCount; } array = new CallFrame[previousCount + 1]; cx.previousInterpreterInvocations.toArray(array); } array[array.length - 1] = (CallFrame)cx.lastInterpreterFrame; int interpreterFrameCount = 0; for (int i = 0; i != array.length; ++i) { interpreterFrameCount += 1 + array[i].frameIndex; } int[] linePC = new int[interpreterFrameCount]; // Fill linePC with pc positions from all interpreter frames. // Start from the most nested frame int linePCIndex = interpreterFrameCount; for (int i = array.length; i != 0;) { --i; CallFrame frame = array[i]; while (frame != null) { --linePCIndex; linePC[linePCIndex] = frame.pcSourceLineStart; frame = frame.parentFrame; } } if (linePCIndex != 0) Kit.codeBug(); ex.interpreterStackInfo = array; ex.interpreterLineData = linePC; } public String getSourcePositionFromStack(Context cx, int[] linep) { CallFrame frame = (CallFrame)cx.lastInterpreterFrame; InterpreterData idata = frame.idata; if (frame.pcSourceLineStart >= 0) { linep[0] = getIndex(idata.itsICode, frame.pcSourceLineStart); } else { linep[0] = 0; } return idata.itsSourceFile; } public String getPatchedStack(RhinoException ex, String nativeStackTrace) { String tag = "org.mozilla.javascript.Interpreter.interpretLoop"; StringBuffer sb = new StringBuffer(nativeStackTrace.length() + 1000); String lineSeparator = SecurityUtilities.getSystemProperty("line.separator"); CallFrame[] array = (CallFrame[])ex.interpreterStackInfo; int[] linePC = ex.interpreterLineData; int arrayIndex = array.length; int linePCIndex = linePC.length; int offset = 0; while (arrayIndex != 0) { --arrayIndex; int pos = nativeStackTrace.indexOf(tag, offset); if (pos < 0) { break; } // Skip tag length pos += tag.length(); // Skip until the end of line for (; pos != nativeStackTrace.length(); ++pos) { char c = nativeStackTrace.charAt(pos); if (c == '\n' || c == '\r') { break; } } sb.append(nativeStackTrace.substring(offset, pos)); offset = pos; CallFrame frame = array[arrayIndex]; while (frame != null) { if (linePCIndex == 0) Kit.codeBug(); --linePCIndex; InterpreterData idata = frame.idata; sb.append(lineSeparator); sb.append("\tat script"); if (idata.itsName != null && idata.itsName.length() != 0) { sb.append('.'); sb.append(idata.itsName); } sb.append('('); sb.append(idata.itsSourceFile); int pc = linePC[linePCIndex]; if (pc >= 0) { // Include line info only if available sb.append(':'); sb.append(getIndex(idata.itsICode, pc)); } sb.append(')'); frame = frame.parentFrame; } } sb.append(nativeStackTrace.substring(offset)); return sb.toString(); } public List getScriptStack(RhinoException ex) { if (ex.interpreterStackInfo == null) { return null; } List list = new ArrayList(); String lineSeparator = SecurityUtilities.getSystemProperty("line.separator"); CallFrame[] array = (CallFrame[])ex.interpreterStackInfo; int[] linePC = ex.interpreterLineData; int arrayIndex = array.length; int linePCIndex = linePC.length; while (arrayIndex != 0) { --arrayIndex; StringBuilder sb = new StringBuilder(); CallFrame frame = array[arrayIndex]; while (frame != null) { if (linePCIndex == 0) Kit.codeBug(); --linePCIndex; InterpreterData idata = frame.idata; sb.append("\tat "); sb.append(idata.itsSourceFile); int pc = linePC[linePCIndex]; if (pc >= 0) { // Include line info only if available sb.append(':'); sb.append(getIndex(idata.itsICode, pc)); } if (idata.itsName != null && idata.itsName.length() != 0) { sb.append(" ("); sb.append(idata.itsName); sb.append(')'); } sb.append(lineSeparator); frame = frame.parentFrame; } list.add(sb.toString()); } return list; } public List> buildScriptStack(RhinoException ex) { if (ex.interpreterStackInfo == null) { return Collections.emptyList(); } List> list = new ArrayList>(); CallFrame[] array = (CallFrame[])ex.interpreterStackInfo; int[] linePC = ex.interpreterLineData; int arrayIndex = array.length; int linePCIndex = linePC.length; while (arrayIndex != 0) { --arrayIndex; List sb = new ArrayList(); CallFrame frame = array[arrayIndex]; while (frame != null) { if (linePCIndex == 0) Kit.codeBug(); --linePCIndex; InterpreterData idata = frame.idata; int pc = linePC[linePCIndex]; sb.add(new StackTraceElement("script", idata.itsName!=null?idata.itsName:"", idata.itsSourceFile, pc>=0 ? getIndex(idata.itsICode, pc) : -1 )); frame = frame.parentFrame; } list.add(sb); } return list; } static String getEncodedSource(InterpreterData idata) { if (idata.encodedSource == null) { return null; } return idata.encodedSource.substring(idata.encodedSourceStart, idata.encodedSourceEnd); } private static void initFunction(Context cx, Scriptable scope, InterpretedFunction parent, int index) { InterpretedFunction fn; fn = InterpretedFunction.createFunction(cx, scope, parent, index); ScriptRuntime.initFunction(cx, scope, fn, fn.idata.itsFunctionType, parent.idata.evalScriptFlag); } static Object interpret(InterpretedFunction ifun, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!ScriptRuntime.hasTopCall(cx)) Kit.codeBug(); if (cx.interpreterSecurityDomain != ifun.securityDomain) { Object savedDomain = cx.interpreterSecurityDomain; cx.interpreterSecurityDomain = ifun.securityDomain; try { return ifun.securityController.callWithDomain( ifun.securityDomain, cx, ifun, scope, thisObj, args); } finally { cx.interpreterSecurityDomain = savedDomain; } } CallFrame frame = new CallFrame(); initFrame(cx, scope, thisObj, args, null, 0, args.length, ifun, null, frame); frame.isContinuationsTopFrame = cx.isContinuationsTopCall; cx.isContinuationsTopCall = false; return interpretLoop(cx, frame, null); } static class GeneratorState { GeneratorState(int operation, Object value) { this.operation = operation; this.value = value; } int operation; Object value; RuntimeException returnedException; } public static Object resumeGenerator(Context cx, Scriptable scope, int operation, Object savedState, Object value) { CallFrame frame = (CallFrame) savedState; GeneratorState generatorState = new GeneratorState(operation, value); if (operation == NativeGenerator.GENERATOR_CLOSE) { try { return interpretLoop(cx, frame, generatorState); } catch (RuntimeException e) { // Only propagate exceptions other than closingException if (e != value) throw e; } return Undefined.instance; } Object result = interpretLoop(cx, frame, generatorState); if (generatorState.returnedException != null) throw generatorState.returnedException; return result; } public static Object restartContinuation(NativeContinuation c, Context cx, Scriptable scope, Object[] args) { if (!ScriptRuntime.hasTopCall(cx)) { return ScriptRuntime.doTopCall(c, cx, scope, null, args); } Object arg; if (args.length == 0) { arg = Undefined.instance; } else { arg = args[0]; } CallFrame capturedFrame = (CallFrame)c.getImplementation(); if (capturedFrame == null) { // No frames to restart return arg; } ContinuationJump cjump = new ContinuationJump(c, null); cjump.result = arg; return interpretLoop(cx, null, cjump); } private static Object interpretLoop(Context cx, CallFrame frame, Object throwable) { // throwable holds exception object to rethrow or catch // It is also used for continuation restart in which case // it holds ContinuationJump final Object DBL_MRK = UniqueTag.DOUBLE_MARK; final Object undefined = Undefined.instance; final boolean instructionCounting = (cx.instructionThreshold != 0); // arbitrary number to add to instructionCount when calling // other functions final int INVOCATION_COST = 100; // arbitrary exception cost for instruction counting final int EXCEPTION_COST = 100; String stringReg = null; int indexReg = -1; if (cx.lastInterpreterFrame != null) { // save the top frame from the previous interpretLoop // invocation on the stack if (cx.previousInterpreterInvocations == null) { cx.previousInterpreterInvocations = new ObjArray(); } cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame); } // When restarting continuation throwable is not null and to jump // to the code that rewind continuation state indexReg should be set // to -1. // With the normal call throwable == null and indexReg == -1 allows to // catch bugs with using indeReg to access array elements before // initializing indexReg. GeneratorState generatorState = null; if (throwable != null) { if (throwable instanceof GeneratorState) { generatorState = (GeneratorState) throwable; // reestablish this call frame enterFrame(cx, frame, ScriptRuntime.emptyArgs, true); throwable = null; } else if (!(throwable instanceof ContinuationJump)) { // It should be continuation Kit.codeBug(); } } Object interpreterResult = null; double interpreterResultDbl = 0.0; StateLoop: for (;;) { withoutExceptions: try { if (throwable != null) { // Need to return both 'frame' and 'throwable' from // 'processThrowable', so just added a 'throwable' // member in 'frame'. frame = processThrowable(cx, throwable, frame, indexReg, instructionCounting); throwable = frame.throwable; frame.throwable = null; } else { if (generatorState == null && frame.frozen) Kit.codeBug(); } // Use local variables for constant values in frame // for faster access Object[] stack = frame.stack; double[] sDbl = frame.sDbl; Object[] vars = frame.varSource.stack; double[] varDbls = frame.varSource.sDbl; int[] varAttributes = frame.varSource.stackAttributes; byte[] iCode = frame.idata.itsICode; String[] strings = frame.idata.itsStringTable; // Use local for stackTop as well. Since execption handlers // can only exist at statement level where stack is empty, // it is necessary to save/restore stackTop only across // function calls and normal returns. int stackTop = frame.savedStackTop; // Store new frame in cx which is used for error reporting etc. cx.lastInterpreterFrame = frame; Loop: for (;;) { // Exception handler assumes that PC is already incremented // pass the instruction start when it searches the // exception handler int op = iCode[frame.pc++]; jumplessRun: { // Back indent to ease implementation reading switch (op) { case Icode_GENERATOR: { if (!frame.frozen) { // First time encountering this opcode: create new generator // object and return frame.pc--; // we want to come back here when we resume CallFrame generatorFrame = captureFrameForGenerator(frame); generatorFrame.frozen = true; NativeGenerator generator = new NativeGenerator(frame.scope, generatorFrame.fnOrScript, generatorFrame); frame.result = generator; break Loop; } else { // We are now resuming execution. Fall through to YIELD case. } } // fall through... case Token.YIELD: { if (!frame.frozen) { return freezeGenerator(cx, frame, stackTop, generatorState); } else { Object obj = thawGenerator(frame, stackTop, generatorState, op); if (obj != Scriptable.NOT_FOUND) { throwable = obj; break withoutExceptions; } continue Loop; } } case Icode_GENERATOR_END: { // throw StopIteration frame.frozen = true; int sourceLine = getIndex(iCode, frame.pc); generatorState.returnedException = new JavaScriptException( NativeIterator.getStopIterationObject(frame.scope), frame.idata.itsSourceFile, sourceLine); break Loop; } case Token.THROW: { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; int sourceLine = getIndex(iCode, frame.pc); throwable = new JavaScriptException(value, frame.idata.itsSourceFile, sourceLine); break withoutExceptions; } case Token.RETHROW: { indexReg += frame.localShift; throwable = stack[indexReg]; break withoutExceptions; } case Token.GE : case Token.LE : case Token.GT : case Token.LT : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; object_compare: { number_compare: { double rDbl, lDbl; if (rhs == DBL_MRK) { rDbl = sDbl[stackTop + 1]; lDbl = stack_double(frame, stackTop); } else if (lhs == DBL_MRK) { rDbl = ScriptRuntime.toNumber(rhs); lDbl = sDbl[stackTop]; } else { break number_compare; } switch (op) { case Token.GE: valBln = (lDbl >= rDbl); break object_compare; case Token.LE: valBln = (lDbl <= rDbl); break object_compare; case Token.GT: valBln = (lDbl > rDbl); break object_compare; case Token.LT: valBln = (lDbl < rDbl); break object_compare; default: throw Kit.codeBug(); } } switch (op) { case Token.GE: valBln = ScriptRuntime.cmp_LE(rhs, lhs); break; case Token.LE: valBln = ScriptRuntime.cmp_LE(lhs, rhs); break; case Token.GT: valBln = ScriptRuntime.cmp_LT(rhs, lhs); break; case Token.LT: valBln = ScriptRuntime.cmp_LT(lhs, rhs); break; default: throw Kit.codeBug(); } } stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.IN : case Token.INSTANCEOF : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); boolean valBln; if (op == Token.IN) { valBln = ScriptRuntime.in(lhs, rhs, cx); } else { valBln = ScriptRuntime.instanceOf(lhs, rhs, cx); } stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.EQ : case Token.NE : { --stackTop; boolean valBln; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; if (rhs == DBL_MRK) { if (lhs == DBL_MRK) { valBln = (sDbl[stackTop] == sDbl[stackTop + 1]); } else { valBln = ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs); } } else { if (lhs == DBL_MRK) { valBln = ScriptRuntime.eqNumber(sDbl[stackTop], rhs); } else { valBln = ScriptRuntime.eq(lhs, rhs); } } valBln ^= (op == Token.NE); stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.SHEQ : case Token.SHNE : { --stackTop; boolean valBln = shallowEquals(stack, sDbl, stackTop); valBln ^= (op == Token.SHNE); stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.IFNE : if (stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } break jumplessRun; case Token.IFEQ : if (!stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } break jumplessRun; case Icode_IFEQ_POP : if (!stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } stack[stackTop--] = null; break jumplessRun; case Token.GOTO : break jumplessRun; case Icode_GOSUB : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = frame.pc + 2; break jumplessRun; case Icode_STARTSUB : if (stackTop == frame.emptyStackTop + 1) { // Call from Icode_GOSUB: store return PC address in the local indexReg += frame.localShift; stack[indexReg] = stack[stackTop]; sDbl[indexReg] = sDbl[stackTop]; --stackTop; } else { // Call from exception handler: exception object is already stored // in the local if (stackTop != frame.emptyStackTop) Kit.codeBug(); } continue Loop; case Icode_RETSUB : { // indexReg: local to store return address if (instructionCounting) { addInstructionCount(cx, frame, 0); } indexReg += frame.localShift; Object value = stack[indexReg]; if (value != DBL_MRK) { // Invocation from exception handler, restore object to rethrow throwable = value; break withoutExceptions; } // Normal return from GOSUB frame.pc = (int)sDbl[indexReg]; if (instructionCounting) { frame.pcPrevBranch = frame.pc; } continue Loop; } case Icode_POP : stack[stackTop] = null; stackTop--; continue Loop; case Icode_POP_RESULT : frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; stack[stackTop] = null; --stackTop; continue Loop; case Icode_DUP : stack[stackTop + 1] = stack[stackTop]; sDbl[stackTop + 1] = sDbl[stackTop]; stackTop++; continue Loop; case Icode_DUP2 : stack[stackTop + 1] = stack[stackTop - 1]; sDbl[stackTop + 1] = sDbl[stackTop - 1]; stack[stackTop + 2] = stack[stackTop]; sDbl[stackTop + 2] = sDbl[stackTop]; stackTop += 2; continue Loop; case Icode_SWAP : { Object o = stack[stackTop]; stack[stackTop] = stack[stackTop - 1]; stack[stackTop - 1] = o; double d = sDbl[stackTop]; sDbl[stackTop] = sDbl[stackTop - 1]; sDbl[stackTop - 1] = d; continue Loop; } case Token.RETURN : frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; --stackTop; break Loop; case Token.RETURN_RESULT : break Loop; case Icode_RETUNDEF : frame.result = undefined; break Loop; case Token.BITNOT : { int rIntValue = stack_int32(frame, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ~rIntValue; continue Loop; } case Token.BITAND : case Token.BITOR : case Token.BITXOR : case Token.LSH : case Token.RSH : { int lIntValue = stack_int32(frame, stackTop-1); int rIntValue = stack_int32(frame, stackTop); stack[--stackTop] = DBL_MRK; switch (op) { case Token.BITAND: lIntValue &= rIntValue; break; case Token.BITOR: lIntValue |= rIntValue; break; case Token.BITXOR: lIntValue ^= rIntValue; break; case Token.LSH: lIntValue <<= rIntValue; break; case Token.RSH: lIntValue >>= rIntValue; break; } sDbl[stackTop] = lIntValue; continue Loop; } case Token.URSH : { double lDbl = stack_double(frame, stackTop-1); int rIntValue = stack_int32(frame, stackTop) & 0x1F; stack[--stackTop] = DBL_MRK; sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue; continue Loop; } case Token.NEG : case Token.POS : { double rDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; if (op == Token.NEG) { rDbl = -rDbl; } sDbl[stackTop] = rDbl; continue Loop; } case Token.ADD : --stackTop; do_add(stack, sDbl, stackTop, cx); continue Loop; case Token.SUB : case Token.MUL : case Token.DIV : case Token.MOD : { double rDbl = stack_double(frame, stackTop); --stackTop; double lDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; switch (op) { case Token.SUB: lDbl -= rDbl; break; case Token.MUL: lDbl *= rDbl; break; case Token.DIV: lDbl /= rDbl; break; case Token.MOD: lDbl %= rDbl; break; } sDbl[stackTop] = lDbl; continue Loop; } case Token.NOT : stack[stackTop] = ScriptRuntime.wrapBoolean( !stack_boolean(frame, stackTop)); continue Loop; case Token.BINDNAME : stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg); continue Loop; case Token.SETNAME : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setName(lhs, rhs, cx, frame.scope, stringReg); continue Loop; } case Icode_SETCONST: { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg); continue Loop; } case Token.DELPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx); continue Loop; } case Token.GETPROPNOWARN : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getObjectPropNoWarn(lhs, stringReg, cx); continue Loop; } case Token.GETPROP : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg, cx, frame.scope); continue Loop; } case Token.SETPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs, cx); continue Loop; } case Icode_PROP_INC_DEC : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.GETELEM : { --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) { lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); } Object value; Object id = stack[stackTop + 1]; if (id != DBL_MRK) { value = ScriptRuntime.getObjectElem(lhs, id, cx, frame.scope); } else { double d = sDbl[stackTop + 1]; value = ScriptRuntime.getObjectIndex(lhs, d, cx); } stack[stackTop] = value; continue Loop; } case Token.SETELEM : { stackTop -= 2; Object rhs = stack[stackTop + 2]; if (rhs == DBL_MRK) { rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]); } Object lhs = stack[stackTop]; if (lhs == DBL_MRK) { lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); } Object value; Object id = stack[stackTop + 1]; if (id != DBL_MRK) { value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx); } else { double d = sDbl[stackTop + 1]; value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx); } stack[stackTop] = value; continue Loop; } case Icode_ELEM_INC_DEC: { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.GET_REF : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refGet(ref, cx); continue Loop; } case Token.SET_REF : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refSet(ref, value, cx); continue Loop; } case Token.DEL_REF : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refDel(ref, cx); continue Loop; } case Icode_REF_INC_DEC : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.LOCAL_LOAD : ++stackTop; indexReg += frame.localShift; stack[stackTop] = stack[indexReg]; sDbl[stackTop] = sDbl[indexReg]; continue Loop; case Icode_LOCAL_CLEAR : indexReg += frame.localShift; stack[indexReg] = null; continue Loop; case Icode_NAME_AND_THIS : // stringReg: name ++stackTop; stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg, cx, frame.scope); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; case Icode_PROP_AND_THIS: { Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); // stringReg: property stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg, cx, frame.scope); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_ELEM_AND_THIS: { Object obj = stack[stackTop - 1]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]); Object id = stack[stackTop]; if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx); stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_VALUE_AND_THIS : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_CALLSPECIAL : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } int callType = iCode[frame.pc] & 0xFF; boolean isNew = (iCode[frame.pc + 1] != 0); int sourceLine = getIndex(iCode, frame.pc + 2); // indexReg: number of arguments if (isNew) { // stack change: function arg0 .. argN -> newResult stackTop -= indexReg; Object function = stack[stackTop]; if (function == DBL_MRK) function = ScriptRuntime.wrapNumber(sDbl[stackTop]); Object[] outArgs = getArgsArray( stack, sDbl, stackTop + 1, indexReg); stack[stackTop] = ScriptRuntime.newSpecial( cx, function, outArgs, frame.scope, callType); } else { // stack change: function thisObj arg0 .. argN -> result stackTop -= 1 + indexReg; // Call code generation ensure that stack here // is ... Callable Scriptable Scriptable functionThis = (Scriptable)stack[stackTop + 1]; Callable function = (Callable)stack[stackTop]; Object[] outArgs = getArgsArray( stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = ScriptRuntime.callSpecial( cx, function, functionThis, outArgs, frame.scope, frame.thisObj, callType, frame.idata.itsSourceFile, sourceLine); } frame.pc += 4; continue Loop; } case Token.CALL : case Icode_TAIL_CALL : case Token.REF_CALL : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } // stack change: function thisObj arg0 .. argN -> result // indexReg: number of arguments stackTop -= 1 + indexReg; // CALL generation ensures that fun and funThisObj // are already Scriptable and Callable objects respectively Callable fun = (Callable)stack[stackTop]; Scriptable funThisObj = (Scriptable)stack[stackTop + 1]; if (op == Token.REF_CALL) { Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj, outArgs, cx); continue Loop; } Scriptable calleeScope = frame.scope; if (frame.useActivation) { calleeScope = ScriptableObject.getTopLevelScope(frame.scope); } if (fun instanceof InterpretedFunction) { InterpretedFunction ifun = (InterpretedFunction)fun; if (frame.fnOrScript.securityDomain == ifun.securityDomain) { CallFrame callParentFrame = frame; CallFrame calleeFrame = new CallFrame(); if (op == Icode_TAIL_CALL) { // In principle tail call can re-use the current // frame and its stack arrays but it is hard to // do properly. Any exceptions that can legally // happen during frame re-initialization including // StackOverflowException during innocent looking // System.arraycopy may leave the current frame // data corrupted leading to undefined behaviour // in the catch code bellow that unwinds JS stack // on exceptions. Then there is issue about frame release // end exceptions there. // To avoid frame allocation a released frame // can be cached for re-use which would also benefit // non-tail calls but it is not clear that this caching // would gain in performance due to potentially // bad interaction with GC. callParentFrame = frame.parentFrame; // Release the current frame. See Bug #344501 to see why // it is being done here. exitFrame(cx, frame, null); } initFrame(cx, calleeScope, funThisObj, stack, sDbl, stackTop + 2, indexReg, ifun, callParentFrame, calleeFrame); if (op != Icode_TAIL_CALL) { frame.savedStackTop = stackTop; frame.savedCallOp = op; } frame = calleeFrame; continue StateLoop; } } if (fun instanceof NativeContinuation) { // Jump to the captured continuation ContinuationJump cjump; cjump = new ContinuationJump((NativeContinuation)fun, frame); // continuation result is the first argument if any // of continuation call if (indexReg == 0) { cjump.result = undefined; } else { cjump.result = stack[stackTop + 2]; cjump.resultDbl = sDbl[stackTop + 2]; } // Start the real unwind job throwable = cjump; break withoutExceptions; } if (fun instanceof IdFunctionObject) { IdFunctionObject ifun = (IdFunctionObject)fun; if (NativeContinuation.isContinuationConstructor(ifun)) { frame.stack[stackTop] = captureContinuation(cx, frame.parentFrame, false); continue Loop; } // Bug 405654 -- make best effort to keep Function.apply and // Function.call within this interpreter loop invocation if (BaseFunction.isApplyOrCall(ifun)) { Callable applyCallable = ScriptRuntime.getCallable(funThisObj); if (applyCallable instanceof InterpretedFunction) { InterpretedFunction iApplyCallable = (InterpretedFunction)applyCallable; if (frame.fnOrScript.securityDomain == iApplyCallable.securityDomain) { frame = initFrameForApplyOrCall(cx, frame, indexReg, stack, sDbl, stackTop, op, calleeScope, ifun, iApplyCallable); continue StateLoop; } } } } // Bug 447697 -- make best effort to keep __noSuchMethod__ within this // interpreter loop invocation if (fun instanceof NoSuchMethodShim) { // get the shim and the actual method NoSuchMethodShim noSuchMethodShim = (NoSuchMethodShim) fun; Callable noSuchMethodMethod = noSuchMethodShim.noSuchMethodMethod; // if the method is in fact an InterpretedFunction if (noSuchMethodMethod instanceof InterpretedFunction) { InterpretedFunction ifun = (InterpretedFunction) noSuchMethodMethod; if (frame.fnOrScript.securityDomain == ifun.securityDomain) { frame = initFrameForNoSuchMethod(cx, frame, indexReg, stack, sDbl, stackTop, op, funThisObj, calleeScope, noSuchMethodShim, ifun); continue StateLoop; } } } cx.lastInterpreterFrame = frame; frame.savedCallOp = op; frame.savedStackTop = stackTop; stack[stackTop] = fun.call(cx, calleeScope, funThisObj, getArgsArray(stack, sDbl, stackTop + 2, indexReg)); continue Loop; } case Token.NEW : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } // stack change: function arg0 .. argN -> newResult // indexReg: number of arguments stackTop -= indexReg; Object lhs = stack[stackTop]; if (lhs instanceof InterpretedFunction) { InterpretedFunction f = (InterpretedFunction)lhs; if (frame.fnOrScript.securityDomain == f.securityDomain) { Scriptable newInstance = f.createObject(cx, frame.scope); CallFrame calleeFrame = new CallFrame(); initFrame(cx, frame.scope, newInstance, stack, sDbl, stackTop + 1, indexReg, f, frame, calleeFrame); stack[stackTop] = newInstance; frame.savedStackTop = stackTop; frame.savedCallOp = op; frame = calleeFrame; continue StateLoop; } } if (!(lhs instanceof Function)) { if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); throw ScriptRuntime.notFunctionError(lhs); } Function fun = (Function)lhs; if (fun instanceof IdFunctionObject) { IdFunctionObject ifun = (IdFunctionObject)fun; if (NativeContinuation.isContinuationConstructor(ifun)) { frame.stack[stackTop] = captureContinuation(cx, frame.parentFrame, false); continue Loop; } } Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg); stack[stackTop] = fun.construct(cx, frame.scope, outArgs); continue Loop; } case Token.TYPEOF : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.typeof(lhs); continue Loop; } case Icode_TYPEOFNAME : stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg); continue Loop; case Token.STRING : stack[++stackTop] = stringReg; continue Loop; case Icode_SHORTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getShort(iCode, frame.pc); frame.pc += 2; continue Loop; case Icode_INTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getInt(iCode, frame.pc); frame.pc += 4; continue Loop; case Token.NUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg]; continue Loop; case Token.NAME : stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg); continue Loop; case Icode_NAME_INC_DEC : stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg, cx, iCode[frame.pc]); ++frame.pc; continue Loop; case Icode_SETCONSTVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.SETCONSTVAR : if (!frame.useActivation) { if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) { throw Context.reportRuntimeError1("msg.var.redecl", frame.idata.argNames[indexReg]); } if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST) != 0) { vars[indexReg] = stack[stackTop]; varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST; varDbls[indexReg] = sDbl[stackTop]; } } else { Object val = stack[stackTop]; if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]); stringReg = frame.idata.argNames[indexReg]; if (frame.scope instanceof ConstProperties) { ConstProperties cp = (ConstProperties)frame.scope; cp.putConst(stringReg, frame.scope, val); } else throw Kit.codeBug(); } continue Loop; case Icode_SETVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.SETVAR : if (!frame.useActivation) { if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) { vars[indexReg] = stack[stackTop]; varDbls[indexReg] = sDbl[stackTop]; } } else { Object val = stack[stackTop]; if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]); stringReg = frame.idata.argNames[indexReg]; frame.scope.put(stringReg, frame.scope, val); } continue Loop; case Icode_GETVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.GETVAR : ++stackTop; if (!frame.useActivation) { stack[stackTop] = vars[indexReg]; sDbl[stackTop] = varDbls[indexReg]; } else { stringReg = frame.idata.argNames[indexReg]; stack[stackTop] = frame.scope.get(stringReg, frame.scope); } continue Loop; case Icode_VAR_INC_DEC : { // indexReg : varindex ++stackTop; int incrDecrMask = iCode[frame.pc]; if (!frame.useActivation) { stack[stackTop] = DBL_MRK; Object varValue = vars[indexReg]; double d; if (varValue == DBL_MRK) { d = varDbls[indexReg]; } else { d = ScriptRuntime.toNumber(varValue); vars[indexReg] = DBL_MRK; } double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0) ? d + 1.0 : d - 1.0; varDbls[indexReg] = d2; sDbl[stackTop] = ((incrDecrMask & Node.POST_FLAG) == 0) ? d2 : d; } else { String varName = frame.idata.argNames[indexReg]; stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName, cx, incrDecrMask); } ++frame.pc; continue Loop; } case Icode_ZERO : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 0; continue Loop; case Icode_ONE : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 1; continue Loop; case Token.NULL : stack[++stackTop] = null; continue Loop; case Token.THIS : stack[++stackTop] = frame.thisObj; continue Loop; case Token.THISFN : stack[++stackTop] = frame.fnOrScript; continue Loop; case Token.FALSE : stack[++stackTop] = Boolean.FALSE; continue Loop; case Token.TRUE : stack[++stackTop] = Boolean.TRUE; continue Loop; case Icode_UNDEF : stack[++stackTop] = undefined; continue Loop; case Token.ENTERWITH : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope); continue Loop; } case Token.LEAVEWITH : frame.scope = ScriptRuntime.leaveWith(frame.scope); continue Loop; case Token.CATCH_SCOPE : { // stack top: exception object // stringReg: name of exception variable // indexReg: local for exception scope --stackTop; indexReg += frame.localShift; boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0); Throwable caughtException = (Throwable)stack[stackTop + 1]; Scriptable lastCatchScope; if (!afterFirstScope) { lastCatchScope = null; } else { lastCatchScope = (Scriptable)stack[indexReg]; } stack[indexReg] = ScriptRuntime.newCatchScope(caughtException, lastCatchScope, stringReg, cx, frame.scope); ++frame.pc; continue Loop; } case Token.ENUM_INIT_KEYS : case Token.ENUM_INIT_VALUES : case Token.ENUM_INIT_ARRAY : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; indexReg += frame.localShift; int enumType = op == Token.ENUM_INIT_KEYS ? ScriptRuntime.ENUMERATE_KEYS : op == Token.ENUM_INIT_VALUES ? ScriptRuntime.ENUMERATE_VALUES : ScriptRuntime.ENUMERATE_ARRAY; stack[indexReg] = ScriptRuntime.enumInit(lhs, cx, enumType); continue Loop; } case Token.ENUM_NEXT : case Token.ENUM_ID : { indexReg += frame.localShift; Object val = stack[indexReg]; ++stackTop; stack[stackTop] = (op == Token.ENUM_NEXT) ? (Object)ScriptRuntime.enumNext(val) : (Object)ScriptRuntime.enumId(val, cx); continue Loop; } case Token.REF_SPECIAL : { //stringReg: name of special property Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg, cx); continue Loop; } case Token.REF_MEMBER: { //indexReg: flags Object elem = stack[stackTop]; if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, indexReg); continue Loop; } case Token.REF_NS_MEMBER: { //indexReg: flags Object elem = stack[stackTop]; if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object ns = stack[stackTop]; if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, indexReg); continue Loop; } case Token.REF_NAME: { //indexReg: flags Object name = stack[stackTop]; if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope, indexReg); continue Loop; } case Token.REF_NS_NAME: { //indexReg: flags Object name = stack[stackTop]; if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object ns = stack[stackTop]; if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope, indexReg); continue Loop; } case Icode_SCOPE_LOAD : indexReg += frame.localShift; frame.scope = (Scriptable)stack[indexReg]; continue Loop; case Icode_SCOPE_SAVE : indexReg += frame.localShift; stack[indexReg] = frame.scope; continue Loop; case Icode_CLOSURE_EXPR : stack[++stackTop] = InterpretedFunction.createFunction(cx, frame.scope, frame.fnOrScript, indexReg); continue Loop; case Icode_CLOSURE_STMT : initFunction(cx, frame.scope, frame.fnOrScript, indexReg); continue Loop; case Token.REGEXP : stack[++stackTop] = frame.scriptRegExps[indexReg]; continue Loop; case Icode_LITERAL_NEW : // indexReg: number of values in the literal ++stackTop; stack[stackTop] = new int[indexReg]; ++stackTop; stack[stackTop] = new Object[indexReg]; sDbl[stackTop] = 0; continue Loop; case Icode_LITERAL_SET : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; sDbl[stackTop] = i + 1; continue Loop; } case Icode_LITERAL_GETTER : { Object value = stack[stackTop]; --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; ((int[])stack[stackTop - 1])[i] = -1; sDbl[stackTop] = i + 1; continue Loop; } case Icode_LITERAL_SETTER : { Object value = stack[stackTop]; --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; ((int[])stack[stackTop - 1])[i] = +1; sDbl[stackTop] = i + 1; continue Loop; } case Token.ARRAYLIT : case Icode_SPARE_ARRAYLIT : case Token.OBJECTLIT : { Object[] data = (Object[])stack[stackTop]; --stackTop; int[] getterSetters = (int[])stack[stackTop]; Object val; if (op == Token.OBJECTLIT) { Object[] ids = (Object[])frame.idata.literalIds[indexReg]; val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx, frame.scope); } else { int[] skipIndexces = null; if (op == Icode_SPARE_ARRAYLIT) { skipIndexces = (int[])frame.idata.literalIds[indexReg]; } val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx, frame.scope); } stack[stackTop] = val; continue Loop; } case Icode_ENTERDQ : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope); continue Loop; } case Icode_LEAVEDQ : { boolean valBln = stack_boolean(frame, stackTop); Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope); if (x != null) { stack[stackTop] = x; frame.scope = ScriptRuntime.leaveDotQuery(frame.scope); frame.pc += 2; continue Loop; } // reset stack and PC to code after ENTERDQ --stackTop; break jumplessRun; } case Token.DEFAULTNAMESPACE : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx); continue Loop; } case Token.ESCXMLATTR : { Object value = stack[stackTop]; if (value != DBL_MRK) { stack[stackTop] = ScriptRuntime.escapeAttributeValue(value, cx); } continue Loop; } case Token.ESCXMLTEXT : { Object value = stack[stackTop]; if (value != DBL_MRK) { stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx); } continue Loop; } case Icode_DEBUGGER: if (frame.debuggerFrame != null) { frame.debuggerFrame.onDebuggerStatement(cx); } continue Loop; case Icode_LINE : frame.pcSourceLineStart = frame.pc; if (frame.debuggerFrame != null) { int line = getIndex(iCode, frame.pc); frame.debuggerFrame.onLineChange(cx, line); } frame.pc += 2; continue Loop; case Icode_REG_IND_C0: indexReg = 0; continue Loop; case Icode_REG_IND_C1: indexReg = 1; continue Loop; case Icode_REG_IND_C2: indexReg = 2; continue Loop; case Icode_REG_IND_C3: indexReg = 3; continue Loop; case Icode_REG_IND_C4: indexReg = 4; continue Loop; case Icode_REG_IND_C5: indexReg = 5; continue Loop; case Icode_REG_IND1: indexReg = 0xFF & iCode[frame.pc]; ++frame.pc; continue Loop; case Icode_REG_IND2: indexReg = getIndex(iCode, frame.pc); frame.pc += 2; continue Loop; case Icode_REG_IND4: indexReg = getInt(iCode, frame.pc); frame.pc += 4; continue Loop; case Icode_REG_STR_C0: stringReg = strings[0]; continue Loop; case Icode_REG_STR_C1: stringReg = strings[1]; continue Loop; case Icode_REG_STR_C2: stringReg = strings[2]; continue Loop; case Icode_REG_STR_C3: stringReg = strings[3]; continue Loop; case Icode_REG_STR1: stringReg = strings[0xFF & iCode[frame.pc]]; ++frame.pc; continue Loop; case Icode_REG_STR2: stringReg = strings[getIndex(iCode, frame.pc)]; frame.pc += 2; continue Loop; case Icode_REG_STR4: stringReg = strings[getInt(iCode, frame.pc)]; frame.pc += 4; continue Loop; default : dumpICode(frame.idata); throw new RuntimeException( "Unknown icode : "+op+" @ pc : "+(frame.pc-1)); } // end of interpreter switch } // end of jumplessRun label block // This should be reachable only for jump implementation // when pc points to encoded target offset if (instructionCounting) { addInstructionCount(cx, frame, 2); } int offset = getShort(iCode, frame.pc); if (offset != 0) { // -1 accounts for pc pointing to jump opcode + 1 frame.pc += offset - 1; } else { frame.pc = frame.idata.longJumps. getExistingInt(frame.pc); } if (instructionCounting) { frame.pcPrevBranch = frame.pc; } continue Loop; } // end of Loop: for exitFrame(cx, frame, null); interpreterResult = frame.result; interpreterResultDbl = frame.resultDbl; if (frame.parentFrame != null) { frame = frame.parentFrame; if (frame.frozen) { frame = frame.cloneFrozen(); } setCallResult( frame, interpreterResult, interpreterResultDbl); interpreterResult = null; // Help GC continue StateLoop; } break StateLoop; } // end of interpreter withoutExceptions: try catch (Throwable ex) { if (throwable != null) { // This is serious bug and it is better to track it ASAP ex.printStackTrace(System.err); throw new IllegalStateException(); } throwable = ex; } // This should be reachable only after above catch or from // finally when it needs to propagate exception or from // explicit throw if (throwable == null) Kit.codeBug(); // Exception type final int EX_CATCH_STATE = 2; // Can execute JS catch final int EX_FINALLY_STATE = 1; // Can execute JS finally final int EX_NO_JS_STATE = 0; // Terminate JS execution int exState; ContinuationJump cjump = null; if (generatorState != null && generatorState.operation == NativeGenerator.GENERATOR_CLOSE && throwable == generatorState.value) { exState = EX_FINALLY_STATE; } else if (throwable instanceof JavaScriptException) { exState = EX_CATCH_STATE; } else if (throwable instanceof EcmaError) { // an offical ECMA error object, exState = EX_CATCH_STATE; } else if (throwable instanceof EvaluatorException) { exState = EX_CATCH_STATE; } else if (throwable instanceof RuntimeException) { exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS) ? EX_CATCH_STATE : EX_FINALLY_STATE; } else if (throwable instanceof Error) { exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS) ? EX_CATCH_STATE : EX_NO_JS_STATE; } else if (throwable instanceof ContinuationJump) { // It must be ContinuationJump exState = EX_FINALLY_STATE; cjump = (ContinuationJump)throwable; } else { exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS) ? EX_CATCH_STATE : EX_FINALLY_STATE; } if (instructionCounting) { try { addInstructionCount(cx, frame, EXCEPTION_COST); } catch (RuntimeException ex) { throwable = ex; exState = EX_FINALLY_STATE; } catch (Error ex) { // Error from instruction counting // => unconditionally terminate JS throwable = ex; cjump = null; exState = EX_NO_JS_STATE; } } if (frame.debuggerFrame != null && throwable instanceof RuntimeException) { // Call debugger only for RuntimeException RuntimeException rex = (RuntimeException)throwable; try { frame.debuggerFrame.onExceptionThrown(cx, rex); } catch (Throwable ex) { // Any exception from debugger // => unconditionally terminate JS throwable = ex; cjump = null; exState = EX_NO_JS_STATE; } } for (;;) { if (exState != EX_NO_JS_STATE) { boolean onlyFinally = (exState != EX_CATCH_STATE); indexReg = getExceptionHandler(frame, onlyFinally); if (indexReg >= 0) { // We caught an exception, restart the loop // with exception pending the processing at the loop // start continue StateLoop; } } // No allowed exception handlers in this frame, unwind // to parent and try to look there exitFrame(cx, frame, throwable); frame = frame.parentFrame; if (frame == null) { break; } if (cjump != null && cjump.branchFrame == frame) { // Continuation branch point was hit, // restart the state loop to reenter continuation indexReg = -1; continue StateLoop; } } // No more frames, rethrow the exception or deal with continuation if (cjump != null) { if (cjump.branchFrame != null) { // The above loop should locate the top frame Kit.codeBug(); } if (cjump.capturedFrame != null) { // Restarting detached continuation indexReg = -1; continue StateLoop; } // Return continuation result to the caller interpreterResult = cjump.result; interpreterResultDbl = cjump.resultDbl; throwable = null; } break StateLoop; } // end of StateLoop: for(;;) // Do cleanups/restorations before the final return or throw if (cx.previousInterpreterInvocations != null && cx.previousInterpreterInvocations.size() != 0) { cx.lastInterpreterFrame = cx.previousInterpreterInvocations.pop(); } else { // It was the last interpreter frame on the stack cx.lastInterpreterFrame = null; // Force GC of the value cx.previousInterpreterInvocations cx.previousInterpreterInvocations = null; } if (throwable != null) { if (throwable instanceof RuntimeException) { throw (RuntimeException)throwable; } else { // Must be instance of Error or code bug throw (Error)throwable; } } return (interpreterResult != DBL_MRK) ? interpreterResult : ScriptRuntime.wrapNumber(interpreterResultDbl); } /** * Call __noSuchMethod__. */ private static CallFrame initFrameForNoSuchMethod(Context cx, CallFrame frame, int indexReg, Object[] stack, double[] sDbl, int stackTop, int op, Scriptable funThisObj, Scriptable calleeScope, NoSuchMethodShim noSuchMethodShim, InterpretedFunction ifun) { // create an args array from the stack Object[] argsArray = null; // exactly like getArgsArray except that the first argument // is the method name from the shim int shift = stackTop + 2; Object[] elements = new Object[indexReg]; for (int i=0; i < indexReg; ++i, ++shift) { Object val = stack[shift]; if (val == UniqueTag.DOUBLE_MARK) { val = ScriptRuntime.wrapNumber(sDbl[shift]); } elements[i] = val; } argsArray = new Object[2]; argsArray[0] = noSuchMethodShim.methodName; argsArray[1] = cx.newArray(calleeScope, elements); // exactly the same as if it's a regular InterpretedFunction CallFrame callParentFrame = frame; CallFrame calleeFrame = new CallFrame(); if (op == Icode_TAIL_CALL) { callParentFrame = frame.parentFrame; exitFrame(cx, frame, null); } // init the frame with the underlying method with the // adjusted args array and shim's function initFrame(cx, calleeScope, funThisObj, argsArray, null, 0, 2, ifun, callParentFrame, calleeFrame); if (op != Icode_TAIL_CALL) { frame.savedStackTop = stackTop; frame.savedCallOp = op; } return calleeFrame; } private static boolean shallowEquals(Object[] stack, double[] sDbl, int stackTop) { Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; final Object DBL_MRK = UniqueTag.DOUBLE_MARK; double rdbl, ldbl; if (rhs == DBL_MRK) { rdbl = sDbl[stackTop + 1]; if (lhs == DBL_MRK) { ldbl = sDbl[stackTop]; } else if (lhs instanceof Number) { ldbl = ((Number)lhs).doubleValue(); } else { return false; } } else if (lhs == DBL_MRK) { ldbl = sDbl[stackTop]; if (rhs == DBL_MRK) { rdbl = sDbl[stackTop + 1]; } else if (rhs instanceof Number) { rdbl = ((Number)rhs).doubleValue(); } else { return false; } } else { return ScriptRuntime.shallowEq(lhs, rhs); } return (ldbl == rdbl); } private static CallFrame processThrowable(Context cx, Object throwable, CallFrame frame, int indexReg, boolean instructionCounting) { // Recovering from exception, indexReg contains // the index of handler if (indexReg >= 0) { // Normal exception handler, transfer // control appropriately if (frame.frozen) { // XXX Deal with exceptios!!! frame = frame.cloneFrozen(); } int[] table = frame.idata.itsExceptionTable; frame.pc = table[indexReg + EXCEPTION_HANDLER_SLOT]; if (instructionCounting) { frame.pcPrevBranch = frame.pc; } frame.savedStackTop = frame.emptyStackTop; int scopeLocal = frame.localShift + table[indexReg + EXCEPTION_SCOPE_SLOT]; int exLocal = frame.localShift + table[indexReg + EXCEPTION_LOCAL_SLOT]; frame.scope = (Scriptable)frame.stack[scopeLocal]; frame.stack[exLocal] = throwable; throwable = null; } else { // Continuation restoration ContinuationJump cjump = (ContinuationJump)throwable; // Clear throwable to indicate that exceptions are OK throwable = null; if (cjump.branchFrame != frame) Kit.codeBug(); // Check that we have at least one frozen frame // in the case of detached continuation restoration: // unwind code ensure that if (cjump.capturedFrame == null) Kit.codeBug(); // Need to rewind branchFrame, capturedFrame // and all frames in between int rewindCount = cjump.capturedFrame.frameIndex + 1; if (cjump.branchFrame != null) { rewindCount -= cjump.branchFrame.frameIndex; } int enterCount = 0; CallFrame[] enterFrames = null; CallFrame x = cjump.capturedFrame; for (int i = 0; i != rewindCount; ++i) { if (!x.frozen) Kit.codeBug(); if (isFrameEnterExitRequired(x)) { if (enterFrames == null) { // Allocate enough space to store the rest // of rewind frames in case all of them // would require to enter enterFrames = new CallFrame[rewindCount - i]; } enterFrames[enterCount] = x; ++enterCount; } x = x.parentFrame; } while (enterCount != 0) { // execute enter: walk enterFrames in the reverse // order since they were stored starting from // the capturedFrame, not branchFrame --enterCount; x = enterFrames[enterCount]; enterFrame(cx, x, ScriptRuntime.emptyArgs, true); } // Continuation jump is almost done: capturedFrame // points to the call to the function that captured // continuation, so clone capturedFrame and // emulate return that function with the suplied result frame = cjump.capturedFrame.cloneFrozen(); setCallResult(frame, cjump.result, cjump.resultDbl); // restart the execution } frame.throwable = throwable; return frame; } private static Object freezeGenerator(Context cx, CallFrame frame, int stackTop, GeneratorState generatorState) { if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) { // Error: no yields when generator is closing throw ScriptRuntime.typeError0("msg.yield.closing"); } // return to our caller (which should be a method of NativeGenerator) frame.frozen = true; frame.result = frame.stack[stackTop]; frame.resultDbl = frame.sDbl[stackTop]; frame.savedStackTop = stackTop; frame.pc--; // we want to come back here when we resume ScriptRuntime.exitActivationFunction(cx); return (frame.result != UniqueTag.DOUBLE_MARK) ? frame.result : ScriptRuntime.wrapNumber(frame.resultDbl); } private static Object thawGenerator(CallFrame frame, int stackTop, GeneratorState generatorState, int op) { // we are resuming execution frame.frozen = false; int sourceLine = getIndex(frame.idata.itsICode, frame.pc); frame.pc += 2; // skip line number data if (generatorState.operation == NativeGenerator.GENERATOR_THROW) { // processing a call to .throw(exception): must // act as if exception was thrown from resumption point return new JavaScriptException(generatorState.value, frame.idata.itsSourceFile, sourceLine); } if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) { return generatorState.value; } if (generatorState.operation != NativeGenerator.GENERATOR_SEND) throw Kit.codeBug(); if (op == Token.YIELD) frame.stack[stackTop] = generatorState.value; return Scriptable.NOT_FOUND; } private static CallFrame initFrameForApplyOrCall(Context cx, CallFrame frame, int indexReg, Object[] stack, double[] sDbl, int stackTop, int op, Scriptable calleeScope, IdFunctionObject ifun, InterpretedFunction iApplyCallable) { Scriptable applyThis; if (indexReg != 0) { Object obj = stack[stackTop + 2]; if (obj == UniqueTag.DOUBLE_MARK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]); applyThis = ScriptRuntime.toObjectOrNull(cx, obj); } else { applyThis = null; } if (applyThis == null) { // This covers the case of args[0] == (null|undefined) as well. applyThis = ScriptRuntime.getTopCallScope(cx); } if(op == Icode_TAIL_CALL) { exitFrame(cx, frame, null); frame = frame.parentFrame; } else { frame.savedStackTop = stackTop; frame.savedCallOp = op; } CallFrame calleeFrame = new CallFrame(); if(BaseFunction.isApply(ifun)) { Object[] callArgs = indexReg < 2 ? ScriptRuntime.emptyArgs : ScriptRuntime.getApplyArguments(cx, stack[stackTop + 3]); initFrame(cx, calleeScope, applyThis, callArgs, null, 0, callArgs.length, iApplyCallable, frame, calleeFrame); } else { // Shift args left for(int i = 1; i < indexReg; ++i) { stack[stackTop + 1 + i] = stack[stackTop + 2 + i]; sDbl[stackTop + 1 + i] = sDbl[stackTop + 2 + i]; } int argCount = indexReg < 2 ? 0 : indexReg - 1; initFrame(cx, calleeScope, applyThis, stack, sDbl, stackTop + 2, argCount, iApplyCallable, frame, calleeFrame); } frame = calleeFrame; return frame; } private static void initFrame(Context cx, Scriptable callerScope, Scriptable thisObj, Object[] args, double[] argsDbl, int argShift, int argCount, InterpretedFunction fnOrScript, CallFrame parentFrame, CallFrame frame) { InterpreterData idata = fnOrScript.idata; boolean useActivation = idata.itsNeedsActivation; DebugFrame debuggerFrame = null; if (cx.debugger != null) { debuggerFrame = cx.debugger.getFrame(cx, idata); if (debuggerFrame != null) { useActivation = true; } } if (useActivation) { // Copy args to new array to pass to enterActivationFunction // or debuggerFrame.onEnter if (argsDbl != null) { args = getArgsArray(args, argsDbl, argShift, argCount); } argShift = 0; argsDbl = null; } Scriptable scope; if (idata.itsFunctionType != 0) { if (!idata.useDynamicScope) { scope = fnOrScript.getParentScope(); } else { scope = callerScope; } if (useActivation) { scope = ScriptRuntime.createFunctionActivation( fnOrScript, scope, args); } } else { scope = callerScope; ScriptRuntime.initScript(fnOrScript, thisObj, cx, scope, fnOrScript.idata.evalScriptFlag); } if (idata.itsNestedFunctions != null) { if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) Kit.codeBug(); for (int i = 0; i < idata.itsNestedFunctions.length; i++) { InterpreterData fdata = idata.itsNestedFunctions[i]; if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) { initFunction(cx, scope, fnOrScript, i); } } } Scriptable[] scriptRegExps = null; if (idata.itsRegExpLiterals != null) { // Wrapped regexps for functions are stored in // InterpretedFunction // but for script which should not contain references to scope // the regexps re-wrapped during each script execution if (idata.itsFunctionType != 0) { scriptRegExps = fnOrScript.functionRegExps; } else { scriptRegExps = fnOrScript.createRegExpWraps(cx, scope); } } // Initialize args, vars, locals and stack int emptyStackTop = idata.itsMaxVars + idata.itsMaxLocals - 1; int maxFrameArray = idata.itsMaxFrameArray; if (maxFrameArray != emptyStackTop + idata.itsMaxStack + 1) Kit.codeBug(); Object[] stack; int[] stackAttributes; double[] sDbl; boolean stackReuse; if (frame.stack != null && maxFrameArray <= frame.stack.length) { // Reuse stacks from old frame stackReuse = true; stack = frame.stack; stackAttributes = frame.stackAttributes; sDbl = frame.sDbl; } else { stackReuse = false; stack = new Object[maxFrameArray]; stackAttributes = new int[maxFrameArray]; sDbl = new double[maxFrameArray]; } int varCount = idata.getParamAndVarCount(); for (int i = 0; i < varCount; i++) { if (idata.getParamOrVarConst(i)) stackAttributes[i] = ScriptableObject.CONST; } int definedArgs = idata.argCount; if (definedArgs > argCount) { definedArgs = argCount; } // Fill the frame structure frame.parentFrame = parentFrame; frame.frameIndex = (parentFrame == null) ? 0 : parentFrame.frameIndex + 1; if(frame.frameIndex > cx.getMaximumInterpreterStackDepth()) { throw Context.reportRuntimeError("Exceeded maximum stack depth"); } frame.frozen = false; frame.fnOrScript = fnOrScript; frame.idata = idata; frame.stack = stack; frame.stackAttributes = stackAttributes; frame.sDbl = sDbl; frame.varSource = frame; frame.localShift = idata.itsMaxVars; frame.emptyStackTop = emptyStackTop; frame.debuggerFrame = debuggerFrame; frame.useActivation = useActivation; frame.thisObj = thisObj; frame.scriptRegExps = scriptRegExps; // Initialize initial values of variables that change during // interpretation. frame.result = Undefined.instance; frame.pc = 0; frame.pcPrevBranch = 0; frame.pcSourceLineStart = idata.firstLinePC; frame.scope = scope; frame.savedStackTop = emptyStackTop; frame.savedCallOp = 0; System.arraycopy(args, argShift, stack, 0, definedArgs); if (argsDbl != null) { System.arraycopy(argsDbl, argShift, sDbl, 0, definedArgs); } for (int i = definedArgs; i != idata.itsMaxVars; ++i) { stack[i] = Undefined.instance; } if (stackReuse) { // Clean the stack part and space beyond stack if any // of the old array to allow to GC objects there for (int i = emptyStackTop + 1; i != stack.length; ++i) { stack[i] = null; } } enterFrame(cx, frame, args, false); } private static boolean isFrameEnterExitRequired(CallFrame frame) { return frame.debuggerFrame != null || frame.idata.itsNeedsActivation; } private static void enterFrame(Context cx, CallFrame frame, Object[] args, boolean continuationRestart) { boolean usesActivation = frame.idata.itsNeedsActivation; boolean isDebugged = frame.debuggerFrame != null; if(usesActivation || isDebugged) { Scriptable scope = frame.scope; if(scope == null) { Kit.codeBug(); } else if (continuationRestart) { // Walk the parent chain of frame.scope until a NativeCall is // found. Normally, frame.scope is a NativeCall when called // from initFrame() for a debugged or activatable function. // However, when called from interpretLoop() as part of // restarting a continuation, it can also be a NativeWith if // the continuation was captured within a "with" or "catch" // block ("catch" implicitly uses NativeWith to create a scope // to expose the exception variable). for(;;) { if(scope instanceof NativeWith) { scope = scope.getParentScope(); if (scope == null || (frame.parentFrame != null && frame.parentFrame.scope == scope)) { // If we get here, we didn't find a NativeCall in // the call chain before reaching parent frame's // scope. This should not be possible. Kit.codeBug(); break; // Never reached, but keeps the static analyzer happy about "scope" not being null 5 lines above. } } else { break; } } } if (isDebugged) { frame.debuggerFrame.onEnter(cx, scope, frame.thisObj, args); } // Enter activation only when itsNeedsActivation true, // since debugger should not interfere with activation // chaining if (usesActivation) { ScriptRuntime.enterActivationFunction(cx, scope); } } } private static void exitFrame(Context cx, CallFrame frame, Object throwable) { if (frame.idata.itsNeedsActivation) { ScriptRuntime.exitActivationFunction(cx); } if (frame.debuggerFrame != null) { try { if (throwable instanceof Throwable) { frame.debuggerFrame.onExit(cx, true, throwable); } else { Object result; ContinuationJump cjump = (ContinuationJump)throwable; if (cjump == null) { result = frame.result; } else { result = cjump.result; } if (result == UniqueTag.DOUBLE_MARK) { double resultDbl; if (cjump == null) { resultDbl = frame.resultDbl; } else { resultDbl = cjump.resultDbl; } result = ScriptRuntime.wrapNumber(resultDbl); } frame.debuggerFrame.onExit(cx, false, result); } } catch (Throwable ex) { System.err.println( "RHINO USAGE WARNING: onExit terminated with exception"); ex.printStackTrace(System.err); } } } private static void setCallResult(CallFrame frame, Object callResult, double callResultDbl) { if (frame.savedCallOp == Token.CALL) { frame.stack[frame.savedStackTop] = callResult; frame.sDbl[frame.savedStackTop] = callResultDbl; } else if (frame.savedCallOp == Token.NEW) { // If construct returns scriptable, // then it replaces on stack top saved original instance // of the object. if (callResult instanceof Scriptable) { frame.stack[frame.savedStackTop] = callResult; } } else { Kit.codeBug(); } frame.savedCallOp = 0; } public static NativeContinuation captureContinuation(Context cx) { if (cx.lastInterpreterFrame == null || !(cx.lastInterpreterFrame instanceof CallFrame)) { throw new IllegalStateException("Interpreter frames not found"); } return captureContinuation(cx, (CallFrame)cx.lastInterpreterFrame, true); } private static NativeContinuation captureContinuation(Context cx, CallFrame frame, boolean requireContinuationsTopFrame) { NativeContinuation c = new NativeContinuation(); ScriptRuntime.setObjectProtoAndParent( c, ScriptRuntime.getTopCallScope(cx)); // Make sure that all frames are frozen CallFrame x = frame; CallFrame outermost = frame; while (x != null && !x.frozen) { x.frozen = true; // Allow to GC unused stack space for (int i = x.savedStackTop + 1; i != x.stack.length; ++i) { // Allow to GC unused stack space x.stack[i] = null; x.stackAttributes[i] = ScriptableObject.EMPTY; } if (x.savedCallOp == Token.CALL) { // the call will always overwrite the stack top with the result x.stack[x.savedStackTop] = null; } else { if (x.savedCallOp != Token.NEW) Kit.codeBug(); // the new operator uses stack top to store the constructed // object so it shall not be cleared: see comments in // setCallResult } outermost = x; x = x.parentFrame; } if (requireContinuationsTopFrame) { while (outermost.parentFrame != null) outermost = outermost.parentFrame; if (!outermost.isContinuationsTopFrame) { throw new IllegalStateException("Cannot capture continuation " + "from JavaScript code not called directly by " + "executeScriptWithContinuations or " + "callFunctionWithContinuations"); } } c.initImplementation(frame); return c; } private static int stack_int32(CallFrame frame, int i) { Object x = frame.stack[i]; double value; if (x == UniqueTag.DOUBLE_MARK) { value = frame.sDbl[i]; } else { value = ScriptRuntime.toNumber(x); } return ScriptRuntime.toInt32(value); } private static double stack_double(CallFrame frame, int i) { Object x = frame.stack[i]; if (x != UniqueTag.DOUBLE_MARK) { return ScriptRuntime.toNumber(x); } else { return frame.sDbl[i]; } } private static boolean stack_boolean(CallFrame frame, int i) { Object x = frame.stack[i]; if (x == Boolean.TRUE) { return true; } else if (x == Boolean.FALSE) { return false; } else if (x == UniqueTag.DOUBLE_MARK) { double d = frame.sDbl[i]; return d == d && d != 0.0; } else if (x == null || x == Undefined.instance) { return false; } else if (x instanceof Number) { double d = ((Number)x).doubleValue(); return (d == d && d != 0.0); } else if (x instanceof Boolean) { return ((Boolean)x).booleanValue(); } else { return ScriptRuntime.toBoolean(x); } } private static void do_add(Object[] stack, double[] sDbl, int stackTop, Context cx) { Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; double d; boolean leftRightOrder; if (rhs == UniqueTag.DOUBLE_MARK) { d = sDbl[stackTop + 1]; if (lhs == UniqueTag.DOUBLE_MARK) { sDbl[stackTop] += d; return; } leftRightOrder = true; // fallthrough to object + number code } else if (lhs == UniqueTag.DOUBLE_MARK) { d = sDbl[stackTop]; lhs = rhs; leftRightOrder = false; // fallthrough to object + number code } else { if (lhs instanceof Scriptable || rhs instanceof Scriptable) { stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx); } else if (lhs instanceof String) { String lstr = (String)lhs; String rstr = ScriptRuntime.toString(rhs); stack[stackTop] = lstr.concat(rstr); } else if (rhs instanceof String) { String lstr = ScriptRuntime.toString(lhs); String rstr = (String)rhs; stack[stackTop] = lstr.concat(rstr); } else { double lDbl = (lhs instanceof Number) ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs); double rDbl = (rhs instanceof Number) ? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs); stack[stackTop] = UniqueTag.DOUBLE_MARK; sDbl[stackTop] = lDbl + rDbl; } return; } // handle object(lhs) + number(d) code if (lhs instanceof Scriptable) { rhs = ScriptRuntime.wrapNumber(d); if (!leftRightOrder) { Object tmp = lhs; lhs = rhs; rhs = tmp; } stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx); } else if (lhs instanceof String) { String lstr = (String)lhs; String rstr = ScriptRuntime.toString(d); if (leftRightOrder) { stack[stackTop] = lstr.concat(rstr); } else { stack[stackTop] = rstr.concat(lstr); } } else { double lDbl = (lhs instanceof Number) ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs); stack[stackTop] = UniqueTag.DOUBLE_MARK; sDbl[stackTop] = lDbl + d; } } private static Object[] getArgsArray(Object[] stack, double[] sDbl, int shift, int count) { if (count == 0) { return ScriptRuntime.emptyArgs; } Object[] args = new Object[count]; for (int i = 0; i != count; ++i, ++shift) { Object val = stack[shift]; if (val == UniqueTag.DOUBLE_MARK) { val = ScriptRuntime.wrapNumber(sDbl[shift]); } args[i] = val; } return args; } private static void addInstructionCount(Context cx, CallFrame frame, int extra) { cx.instructionCount += frame.pc - frame.pcPrevBranch + extra; if (cx.instructionCount > cx.instructionThreshold) { cx.observeInstructionCount(cx.instructionCount); cx.instructionCount = 0; } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/TokenStream.java0000644000175000017500000015615311314263504033215 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Roger Lawrence * Mike McCabe * Igor Bukanov * Ethan Hugg * Bob Jervis * Terry Lucas * Milen Nankov * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.io.*; /** * This class implements the JavaScript scanner. * * It is based on the C source files jsscan.c and jsscan.h * in the jsref package. * * @see org.mozilla.javascript.Parser * * @author Mike McCabe * @author Brendan Eich */ class TokenStream { /* * For chars - because we need something out-of-range * to check. (And checking EOF by exception is annoying.) * Note distinction from EOF token type! */ private final static int EOF_CHAR = -1; TokenStream(Parser parser, Reader sourceReader, String sourceString, int lineno) { this.parser = parser; this.lineno = lineno; if (sourceReader != null) { if (sourceString != null) Kit.codeBug(); this.sourceReader = sourceReader; this.sourceBuffer = new char[512]; this.sourceEnd = 0; } else { if (sourceString == null) Kit.codeBug(); this.sourceString = sourceString; this.sourceEnd = sourceString.length(); } this.sourceCursor = this.cursor = 0; } /* This function uses the cached op, string and number fields in * TokenStream; if getToken has been called since the passed token * was scanned, the op or string printed may be incorrect. */ String tokenToString(int token) { if (Token.printTrees) { String name = Token.name(token); switch (token) { case Token.STRING: case Token.REGEXP: case Token.NAME: return name + " `" + this.string + "'"; case Token.NUMBER: return "NUMBER " + this.number; } return name; } return ""; } static boolean isKeyword(String s) { return Token.EOF != stringToKeyword(s); } private static int stringToKeyword(String name) { // #string_id_map# // The following assumes that Token.EOF == 0 final int Id_break = Token.BREAK, Id_case = Token.CASE, Id_continue = Token.CONTINUE, Id_default = Token.DEFAULT, Id_delete = Token.DELPROP, Id_do = Token.DO, Id_else = Token.ELSE, Id_export = Token.RESERVED, Id_false = Token.FALSE, Id_for = Token.FOR, Id_function = Token.FUNCTION, Id_if = Token.IF, Id_in = Token.IN, Id_let = Token.LET, Id_new = Token.NEW, Id_null = Token.NULL, Id_return = Token.RETURN, Id_switch = Token.SWITCH, Id_this = Token.THIS, Id_true = Token.TRUE, Id_typeof = Token.TYPEOF, Id_var = Token.VAR, Id_void = Token.VOID, Id_while = Token.WHILE, Id_with = Token.WITH, Id_yield = Token.YIELD, // the following are #ifdef RESERVE_JAVA_KEYWORDS in jsscan.c Id_abstract = Token.RESERVED, Id_boolean = Token.RESERVED, Id_byte = Token.RESERVED, Id_catch = Token.CATCH, Id_char = Token.RESERVED, Id_class = Token.RESERVED, Id_const = Token.CONST, Id_debugger = Token.DEBUGGER, Id_double = Token.RESERVED, Id_enum = Token.RESERVED, Id_extends = Token.RESERVED, Id_final = Token.RESERVED, Id_finally = Token.FINALLY, Id_float = Token.RESERVED, Id_goto = Token.RESERVED, Id_implements = Token.RESERVED, Id_import = Token.RESERVED, Id_instanceof = Token.INSTANCEOF, Id_int = Token.RESERVED, Id_interface = Token.RESERVED, Id_long = Token.RESERVED, Id_native = Token.RESERVED, Id_package = Token.RESERVED, Id_private = Token.RESERVED, Id_protected = Token.RESERVED, Id_public = Token.RESERVED, Id_short = Token.RESERVED, Id_static = Token.RESERVED, Id_super = Token.RESERVED, Id_synchronized = Token.RESERVED, Id_throw = Token.THROW, Id_throws = Token.RESERVED, Id_transient = Token.RESERVED, Id_try = Token.TRY, Id_volatile = Token.RESERVED; int id; String s = name; // #generated# Last update: 2007-04-18 13:53:30 PDT L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 2: c=s.charAt(1); if (c=='f') { if (s.charAt(0)=='i') {id=Id_if; break L0;} } else if (c=='n') { if (s.charAt(0)=='i') {id=Id_in; break L0;} } else if (c=='o') { if (s.charAt(0)=='d') {id=Id_do; break L0;} } break L; case 3: switch (s.charAt(0)) { case 'f': if (s.charAt(2)=='r' && s.charAt(1)=='o') {id=Id_for; break L0;} break L; case 'i': if (s.charAt(2)=='t' && s.charAt(1)=='n') {id=Id_int; break L0;} break L; case 'l': if (s.charAt(2)=='t' && s.charAt(1)=='e') {id=Id_let; break L0;} break L; case 'n': if (s.charAt(2)=='w' && s.charAt(1)=='e') {id=Id_new; break L0;} break L; case 't': if (s.charAt(2)=='y' && s.charAt(1)=='r') {id=Id_try; break L0;} break L; case 'v': if (s.charAt(2)=='r' && s.charAt(1)=='a') {id=Id_var; break L0;} break L; } break L; case 4: switch (s.charAt(0)) { case 'b': X="byte";id=Id_byte; break L; case 'c': c=s.charAt(3); if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='a') {id=Id_case; break L0;} } else if (c=='r') { if (s.charAt(2)=='a' && s.charAt(1)=='h') {id=Id_char; break L0;} } break L; case 'e': c=s.charAt(3); if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='l') {id=Id_else; break L0;} } else if (c=='m') { if (s.charAt(2)=='u' && s.charAt(1)=='n') {id=Id_enum; break L0;} } break L; case 'g': X="goto";id=Id_goto; break L; case 'l': X="long";id=Id_long; break L; case 'n': X="null";id=Id_null; break L; case 't': c=s.charAt(3); if (c=='e') { if (s.charAt(2)=='u' && s.charAt(1)=='r') {id=Id_true; break L0;} } else if (c=='s') { if (s.charAt(2)=='i' && s.charAt(1)=='h') {id=Id_this; break L0;} } break L; case 'v': X="void";id=Id_void; break L; case 'w': X="with";id=Id_with; break L; } break L; case 5: switch (s.charAt(2)) { case 'a': X="class";id=Id_class; break L; case 'e': c=s.charAt(0); if (c=='b') { X="break";id=Id_break; } else if (c=='y') { X="yield";id=Id_yield; } break L; case 'i': X="while";id=Id_while; break L; case 'l': X="false";id=Id_false; break L; case 'n': c=s.charAt(0); if (c=='c') { X="const";id=Id_const; } else if (c=='f') { X="final";id=Id_final; } break L; case 'o': c=s.charAt(0); if (c=='f') { X="float";id=Id_float; } else if (c=='s') { X="short";id=Id_short; } break L; case 'p': X="super";id=Id_super; break L; case 'r': X="throw";id=Id_throw; break L; case 't': X="catch";id=Id_catch; break L; } break L; case 6: switch (s.charAt(1)) { case 'a': X="native";id=Id_native; break L; case 'e': c=s.charAt(0); if (c=='d') { X="delete";id=Id_delete; } else if (c=='r') { X="return";id=Id_return; } break L; case 'h': X="throws";id=Id_throws; break L; case 'm': X="import";id=Id_import; break L; case 'o': X="double";id=Id_double; break L; case 't': X="static";id=Id_static; break L; case 'u': X="public";id=Id_public; break L; case 'w': X="switch";id=Id_switch; break L; case 'x': X="export";id=Id_export; break L; case 'y': X="typeof";id=Id_typeof; break L; } break L; case 7: switch (s.charAt(1)) { case 'a': X="package";id=Id_package; break L; case 'e': X="default";id=Id_default; break L; case 'i': X="finally";id=Id_finally; break L; case 'o': X="boolean";id=Id_boolean; break L; case 'r': X="private";id=Id_private; break L; case 'x': X="extends";id=Id_extends; break L; } break L; case 8: switch (s.charAt(0)) { case 'a': X="abstract";id=Id_abstract; break L; case 'c': X="continue";id=Id_continue; break L; case 'd': X="debugger";id=Id_debugger; break L; case 'f': X="function";id=Id_function; break L; case 'v': X="volatile";id=Id_volatile; break L; } break L; case 9: c=s.charAt(0); if (c=='i') { X="interface";id=Id_interface; } else if (c=='p') { X="protected";id=Id_protected; } else if (c=='t') { X="transient";id=Id_transient; } break L; case 10: c=s.charAt(1); if (c=='m') { X="implements";id=Id_implements; } else if (c=='n') { X="instanceof";id=Id_instanceof; } break L; case 12: X="synchronized";id=Id_synchronized; break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# // #/string_id_map# if (id == 0) { return Token.EOF; } return id & 0xff; } final String getSourceString() { return sourceString; } final int getLineno() { return lineno; } final String getString() { return string; } final char getQuoteChar() { return (char) quoteChar; } final double getNumber() { return number; } final boolean eof() { return hitEOF; } final int getToken() throws IOException { int c; retry: for (;;) { // Eat whitespace, possibly sensitive to newlines. for (;;) { c = getChar(); if (c == EOF_CHAR) { tokenBeg = cursor - 1; tokenEnd = cursor; return Token.EOF; } else if (c == '\n') { dirtyLine = false; tokenBeg = cursor - 1; tokenEnd = cursor; return Token.EOL; } else if (!isJSSpace(c)) { if (c != '-') { dirtyLine = true; } break; } } // Assume the token will be 1 char - fixed up below. tokenBeg = cursor - 1; tokenEnd = cursor; if (c == '@') return Token.XMLATTR; // identifier/keyword/instanceof? // watch out for starting with a boolean identifierStart; boolean isUnicodeEscapeStart = false; if (c == '\\') { c = getChar(); if (c == 'u') { identifierStart = true; isUnicodeEscapeStart = true; stringBufferTop = 0; } else { identifierStart = false; ungetChar(c); c = '\\'; } } else { identifierStart = Character.isJavaIdentifierStart((char)c); if (identifierStart) { stringBufferTop = 0; addToString(c); } } if (identifierStart) { boolean containsEscape = isUnicodeEscapeStart; for (;;) { if (isUnicodeEscapeStart) { // strictly speaking we should probably push-back // all the bad characters if the uXXXX // sequence is malformed. But since there isn't a // correct context(is there?) for a bad Unicode // escape sequence in an identifier, we can report // an error here. int escapeVal = 0; for (int i = 0; i != 4; ++i) { c = getChar(); escapeVal = Kit.xDigitToInt(c, escapeVal); // Next check takes care about c < 0 and bad escape if (escapeVal < 0) { break; } } if (escapeVal < 0) { parser.addError("msg.invalid.escape"); return Token.ERROR; } addToString(escapeVal); isUnicodeEscapeStart = false; } else { c = getChar(); if (c == '\\') { c = getChar(); if (c == 'u') { isUnicodeEscapeStart = true; containsEscape = true; } else { parser.addError("msg.illegal.character"); return Token.ERROR; } } else { if (c == EOF_CHAR || !Character.isJavaIdentifierPart((char)c)) { break; } addToString(c); } } } ungetChar(c); String str = getStringFromBuffer(); if (!containsEscape) { // OPT we shouldn't have to make a string (object!) to // check if it's a keyword. // Return the corresponding token if it's a keyword int result = stringToKeyword(str); if (result != Token.EOF) { if ((result == Token.LET || result == Token.YIELD) && parser.compilerEnv.getLanguageVersion() < Context.VERSION_1_7) { // LET and YIELD are tokens only in 1.7 and later string = result == Token.LET ? "let" : "yield"; result = Token.NAME; } if (result != Token.RESERVED) { return result; } else if (!parser.compilerEnv. isReservedKeywordAsIdentifier()) { return result; } } } this.string = (String)allStrings.intern(str); return Token.NAME; } // is it a number? if (isDigit(c) || (c == '.' && isDigit(peekChar()))) { stringBufferTop = 0; int base = 10; if (c == '0') { c = getChar(); if (c == 'x' || c == 'X') { base = 16; c = getChar(); } else if (isDigit(c)) { base = 8; } else { addToString('0'); } } if (base == 16) { while (0 <= Kit.xDigitToInt(c, 0)) { addToString(c); c = getChar(); } } else { while ('0' <= c && c <= '9') { /* * We permit 08 and 09 as decimal numbers, which * makes our behavior a superset of the ECMA * numeric grammar. We might not always be so * permissive, so we warn about it. */ if (base == 8 && c >= '8') { parser.addWarning("msg.bad.octal.literal", c == '8' ? "8" : "9"); base = 10; } addToString(c); c = getChar(); } } boolean isInteger = true; if (base == 10 && (c == '.' || c == 'e' || c == 'E')) { isInteger = false; if (c == '.') { do { addToString(c); c = getChar(); } while (isDigit(c)); } if (c == 'e' || c == 'E') { addToString(c); c = getChar(); if (c == '+' || c == '-') { addToString(c); c = getChar(); } if (!isDigit(c)) { parser.addError("msg.missing.exponent"); return Token.ERROR; } do { addToString(c); c = getChar(); } while (isDigit(c)); } } ungetChar(c); String numString = getStringFromBuffer(); this.string = numString; double dval; if (base == 10 && !isInteger) { try { // Use Java conversion to number from string... dval = Double.valueOf(numString).doubleValue(); } catch (NumberFormatException ex) { parser.addError("msg.caught.nfe"); return Token.ERROR; } } else { dval = ScriptRuntime.stringToNumber(numString, 0, base); } this.number = dval; return Token.NUMBER; } // is it a string? if (c == '"' || c == '\'') { // We attempt to accumulate a string the fast way, by // building it directly out of the reader. But if there // are any escaped characters in the string, we revert to // building it out of a StringBuffer. quoteChar = c; stringBufferTop = 0; c = getChar(); strLoop: while (c != quoteChar) { if (c == '\n' || c == EOF_CHAR) { ungetChar(c); tokenEnd = cursor; parser.addError("msg.unterminated.string.lit"); return Token.ERROR; } if (c == '\\') { // We've hit an escaped character int escapeVal; c = getChar(); switch (c) { case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; // \v a late addition to the ECMA spec, // it is not in Java, so use 0xb case 'v': c = 0xb; break; case 'u': // Get 4 hex digits; if the u escape is not // followed by 4 hex digits, use 'u' + the // literal character sequence that follows. int escapeStart = stringBufferTop; addToString('u'); escapeVal = 0; for (int i = 0; i != 4; ++i) { c = getChar(); escapeVal = Kit.xDigitToInt(c, escapeVal); if (escapeVal < 0) { continue strLoop; } addToString(c); } // prepare for replace of stored 'u' sequence // by escape value stringBufferTop = escapeStart; c = escapeVal; break; case 'x': // Get 2 hex digits, defaulting to 'x'+literal // sequence, as above. c = getChar(); escapeVal = Kit.xDigitToInt(c, 0); if (escapeVal < 0) { addToString('x'); continue strLoop; } else { int c1 = c; c = getChar(); escapeVal = Kit.xDigitToInt(c, escapeVal); if (escapeVal < 0) { addToString('x'); addToString(c1); continue strLoop; } else { // got 2 hex digits c = escapeVal; } } break; case '\n': // Remove line terminator after escape to follow // SpiderMonkey and C/C++ c = getChar(); continue strLoop; default: if ('0' <= c && c < '8') { int val = c - '0'; c = getChar(); if ('0' <= c && c < '8') { val = 8 * val + c - '0'; c = getChar(); if ('0' <= c && c < '8' && val <= 037) { // c is 3rd char of octal sequence only // if the resulting val <= 0377 val = 8 * val + c - '0'; c = getChar(); } } ungetChar(c); c = val; } } } addToString(c); c = getChar(); } String str = getStringFromBuffer(); this.string = (String)allStrings.intern(str); return Token.STRING; } switch (c) { case ';': return Token.SEMI; case '[': return Token.LB; case ']': return Token.RB; case '{': return Token.LC; case '}': return Token.RC; case '(': return Token.LP; case ')': return Token.RP; case ',': return Token.COMMA; case '?': return Token.HOOK; case ':': if (matchChar(':')) { return Token.COLONCOLON; } else { return Token.COLON; } case '.': if (matchChar('.')) { return Token.DOTDOT; } else if (matchChar('(')) { return Token.DOTQUERY; } else { return Token.DOT; } case '|': if (matchChar('|')) { return Token.OR; } else if (matchChar('=')) { return Token.ASSIGN_BITOR; } else { return Token.BITOR; } case '^': if (matchChar('=')) { return Token.ASSIGN_BITXOR; } else { return Token.BITXOR; } case '&': if (matchChar('&')) { return Token.AND; } else if (matchChar('=')) { return Token.ASSIGN_BITAND; } else { return Token.BITAND; } case '=': if (matchChar('=')) { if (matchChar('=')) { return Token.SHEQ; } else { return Token.EQ; } } else { return Token.ASSIGN; } case '!': if (matchChar('=')) { if (matchChar('=')) { return Token.SHNE; } else { return Token.NE; } } else { return Token.NOT; } case '<': /* NB:treat HTML begin-comment as comment-till-eol */ if (matchChar('!')) { if (matchChar('-')) { if (matchChar('-')) { skipLine(); continue retry; } ungetCharIgnoreLineEnd('-'); } ungetCharIgnoreLineEnd('!'); } if (matchChar('<')) { if (matchChar('=')) { return Token.ASSIGN_LSH; } else { return Token.LSH; } } else { if (matchChar('=')) { return Token.LE; } else { return Token.LT; } } case '>': if (matchChar('>')) { if (matchChar('>')) { if (matchChar('=')) { return Token.ASSIGN_URSH; } else { return Token.URSH; } } else { if (matchChar('=')) { return Token.ASSIGN_RSH; } else { return Token.RSH; } } } else { if (matchChar('=')) { return Token.GE; } else { return Token.GT; } } case '*': if (matchChar('=')) { return Token.ASSIGN_MUL; } else { return Token.MUL; } case '/': markCommentStart(); // is it a // comment? if (matchChar('/')) { tokenBeg = cursor - 2; skipLine(); commentType = Token.CommentType.LINE; return Token.COMMENT; } // is it a /* or /** comment? if (matchChar('*')) { boolean lookForSlash = false; tokenBeg = cursor - 2; if (matchChar('*')) { lookForSlash = true; commentType = Token.CommentType.JSDOC; } else { commentType = Token.CommentType.BLOCK; } for (;;) { c = getChar(); if (c == EOF_CHAR) { tokenEnd = cursor - 1; parser.addError("msg.unterminated.comment"); return Token.COMMENT; } else if (c == '*') { lookForSlash = true; } else if (c == '/') { if (lookForSlash) { tokenEnd = cursor; return Token.COMMENT; } } else { lookForSlash = false; tokenEnd = cursor; } } } if (matchChar('=')) { return Token.ASSIGN_DIV; } else { return Token.DIV; } case '%': if (matchChar('=')) { return Token.ASSIGN_MOD; } else { return Token.MOD; } case '~': return Token.BITNOT; case '+': if (matchChar('=')) { return Token.ASSIGN_ADD; } else if (matchChar('+')) { return Token.INC; } else { return Token.ADD; } case '-': if (matchChar('=')) { c = Token.ASSIGN_SUB; } else if (matchChar('-')) { if (!dirtyLine) { // treat HTML end-comment after possible whitespace // after line start as comment-until-eol if (matchChar('>')) { markCommentStart("--"); skipLine(); commentType = Token.CommentType.HTML; return Token.COMMENT; } } c = Token.DEC; } else { c = Token.SUB; } dirtyLine = true; return c; default: parser.addError("msg.illegal.character"); return Token.ERROR; } } } private static boolean isAlpha(int c) { // Use 'Z' < 'a' if (c <= 'Z') { return 'A' <= c; } else { return 'a' <= c && c <= 'z'; } } static boolean isDigit(int c) { return '0' <= c && c <= '9'; } /* As defined in ECMA. jsscan.c uses C isspace() (which allows * \v, I think.) note that code in getChar() implicitly accepts * '\r' == \u000D as well. */ static boolean isJSSpace(int c) { if (c <= 127) { return c == 0x20 || c == 0x9 || c == 0xC || c == 0xB; } else { return c == 0xA0 || Character.getType((char)c) == Character.SPACE_SEPARATOR; } } private static boolean isJSFormatChar(int c) { return c > 127 && Character.getType((char)c) == Character.FORMAT; } /** * Parser calls the method when it gets / or /= in literal context. */ void readRegExp(int startToken) throws IOException { int start = tokenBeg; stringBufferTop = 0; if (startToken == Token.ASSIGN_DIV) { // Miss-scanned /= addToString('='); } else { if (startToken != Token.DIV) Kit.codeBug(); } boolean inCharSet = false; // true if inside a '['..']' pair int c; while ((c = getChar()) != '/' || inCharSet) { if (c == '\n' || c == EOF_CHAR) { ungetChar(c); tokenEnd = cursor - 1; this.string = new String(stringBuffer, 0, stringBufferTop); parser.reportError("msg.unterminated.re.lit"); return; } if (c == '\\') { addToString(c); c = getChar(); } else if (c == '[') { inCharSet = true; } else if (c == ']') { inCharSet = false; } addToString(c); } int reEnd = stringBufferTop; while (true) { if (matchChar('g')) addToString('g'); else if (matchChar('i')) addToString('i'); else if (matchChar('m')) addToString('m'); else if (matchChar('y')) // FireFox 3 addToString('y'); else break; } tokenEnd = start + stringBufferTop + 2; // include slashes if (isAlpha(peekChar())) { parser.reportError("msg.invalid.re.flag"); } this.string = new String(stringBuffer, 0, reEnd); this.regExpFlags = new String(stringBuffer, reEnd, stringBufferTop - reEnd); } String readAndClearRegExpFlags() { String flags = this.regExpFlags; this.regExpFlags = null; return flags; } boolean isXMLAttribute() { return xmlIsAttribute; } int getFirstXMLToken() throws IOException { xmlOpenTagsCount = 0; xmlIsAttribute = false; xmlIsTagContent = false; if (!canUngetChar()) return Token.ERROR; ungetChar('<'); return getNextXMLToken(); } int getNextXMLToken() throws IOException { tokenBeg = cursor; stringBufferTop = 0; // remember the XML for (int c = getChar(); c != EOF_CHAR; c = getChar()) { if (xmlIsTagContent) { switch (c) { case '>': addToString(c); xmlIsTagContent = false; xmlIsAttribute = false; break; case '/': addToString(c); if (peekChar() == '>') { c = getChar(); addToString(c); xmlIsTagContent = false; xmlOpenTagsCount--; } break; case '{': ungetChar(c); this.string = getStringFromBuffer(); return Token.XML; case '\'': case '"': addToString(c); if (!readQuotedString(c)) return Token.ERROR; break; case '=': addToString(c); xmlIsAttribute = true; break; case ' ': case '\t': case '\r': case '\n': addToString(c); break; default: addToString(c); xmlIsAttribute = false; break; } if (!xmlIsTagContent && xmlOpenTagsCount == 0) { this.string = getStringFromBuffer(); return Token.XMLEND; } } else { switch (c) { case '<': addToString(c); c = peekChar(); switch (c) { case '!': c = getChar(); // Skip ! addToString(c); c = peekChar(); switch (c) { case '-': c = getChar(); // Skip - addToString(c); c = getChar(); if (c == '-') { addToString(c); if(!readXmlComment()) return Token.ERROR; } else { // throw away the string in progress stringBufferTop = 0; this.string = null; parser.addError("msg.XML.bad.form"); return Token.ERROR; } break; case '[': c = getChar(); // Skip [ addToString(c); if (getChar() == 'C' && getChar() == 'D' && getChar() == 'A' && getChar() == 'T' && getChar() == 'A' && getChar() == '[') { addToString('C'); addToString('D'); addToString('A'); addToString('T'); addToString('A'); addToString('['); if (!readCDATA()) return Token.ERROR; } else { // throw away the string in progress stringBufferTop = 0; this.string = null; parser.addError("msg.XML.bad.form"); return Token.ERROR; } break; default: if(!readEntity()) return Token.ERROR; break; } break; case '?': c = getChar(); // Skip ? addToString(c); if (!readPI()) return Token.ERROR; break; case '/': // End tag c = getChar(); // Skip / addToString(c); if (xmlOpenTagsCount == 0) { // throw away the string in progress stringBufferTop = 0; this.string = null; parser.addError("msg.XML.bad.form"); return Token.ERROR; } xmlIsTagContent = true; xmlOpenTagsCount--; break; default: // Start tag xmlIsTagContent = true; xmlOpenTagsCount++; break; } break; case '{': ungetChar(c); this.string = getStringFromBuffer(); return Token.XML; default: addToString(c); break; } } } tokenEnd = cursor; stringBufferTop = 0; // throw away the string in progress this.string = null; parser.addError("msg.XML.bad.form"); return Token.ERROR; } /** * */ private boolean readQuotedString(int quote) throws IOException { for (int c = getChar(); c != EOF_CHAR; c = getChar()) { addToString(c); if (c == quote) return true; } stringBufferTop = 0; // throw away the string in progress this.string = null; parser.addError("msg.XML.bad.form"); return false; } /** * */ private boolean readXmlComment() throws IOException { for (int c = getChar(); c != EOF_CHAR;) { addToString(c); if (c == '-' && peekChar() == '-') { c = getChar(); addToString(c); if (peekChar() == '>') { c = getChar(); // Skip > addToString(c); return true; } else { continue; } } c = getChar(); } stringBufferTop = 0; // throw away the string in progress this.string = null; parser.addError("msg.XML.bad.form"); return false; } /** * */ private boolean readCDATA() throws IOException { for (int c = getChar(); c != EOF_CHAR;) { addToString(c); if (c == ']' && peekChar() == ']') { c = getChar(); addToString(c); if (peekChar() == '>') { c = getChar(); // Skip > addToString(c); return true; } else { continue; } } c = getChar(); } stringBufferTop = 0; // throw away the string in progress this.string = null; parser.addError("msg.XML.bad.form"); return false; } /** * */ private boolean readEntity() throws IOException { int declTags = 1; for (int c = getChar(); c != EOF_CHAR; c = getChar()) { addToString(c); switch (c) { case '<': declTags++; break; case '>': declTags--; if (declTags == 0) return true; break; } } stringBufferTop = 0; // throw away the string in progress this.string = null; parser.addError("msg.XML.bad.form"); return false; } /** * */ private boolean readPI() throws IOException { for (int c = getChar(); c != EOF_CHAR; c = getChar()) { addToString(c); if (c == '?' && peekChar() == '>') { c = getChar(); // Skip > addToString(c); return true; } } stringBufferTop = 0; // throw away the string in progress this.string = null; parser.addError("msg.XML.bad.form"); return false; } private String getStringFromBuffer() { tokenEnd = cursor; return new String(stringBuffer, 0, stringBufferTop); } private void addToString(int c) { int N = stringBufferTop; if (N == stringBuffer.length) { char[] tmp = new char[stringBuffer.length * 2]; System.arraycopy(stringBuffer, 0, tmp, 0, N); stringBuffer = tmp; } stringBuffer[N] = (char)c; stringBufferTop = N + 1; } private boolean canUngetChar() { return ungetCursor == 0 || ungetBuffer[ungetCursor - 1] != '\n'; } private void ungetChar(int c) { // can not unread past across line boundary if (ungetCursor != 0 && ungetBuffer[ungetCursor - 1] == '\n') Kit.codeBug(); ungetBuffer[ungetCursor++] = c; cursor--; } private boolean matchChar(int test) throws IOException { int c = getCharIgnoreLineEnd(); if (c == test) { tokenEnd = cursor; return true; } else { ungetCharIgnoreLineEnd(c); return false; } } private int peekChar() throws IOException { int c = getChar(); ungetChar(c); return c; } private int getChar() throws IOException { if (ungetCursor != 0) { cursor++; return ungetBuffer[--ungetCursor]; } for(;;) { int c; if (sourceString != null) { if (sourceCursor == sourceEnd) { hitEOF = true; return EOF_CHAR; } cursor++; c = sourceString.charAt(sourceCursor++); } else { if (sourceCursor == sourceEnd) { if (!fillSourceBuffer()) { hitEOF = true; return EOF_CHAR; } } cursor++; c = sourceBuffer[sourceCursor++]; } if (lineEndChar >= 0) { if (lineEndChar == '\r' && c == '\n') { lineEndChar = '\n'; continue; } lineEndChar = -1; lineStart = sourceCursor - 1; lineno++; } if (c <= 127) { if (c == '\n' || c == '\r') { lineEndChar = c; c = '\n'; } } else { if (isJSFormatChar(c)) { continue; } if (ScriptRuntime.isJSLineTerminator(c)) { lineEndChar = c; c = '\n'; } } return c; } } private int getCharIgnoreLineEnd() throws IOException { if (ungetCursor != 0) { cursor++; return ungetBuffer[--ungetCursor]; } for(;;) { int c; if (sourceString != null) { if (sourceCursor == sourceEnd) { hitEOF = true; return EOF_CHAR; } cursor++; c = sourceString.charAt(sourceCursor++); } else { if (sourceCursor == sourceEnd) { if (!fillSourceBuffer()) { hitEOF = true; return EOF_CHAR; } } cursor++; c = sourceBuffer[sourceCursor++]; } if (c <= 127) { if (c == '\n' || c == '\r') { lineEndChar = c; c = '\n'; } } else { if (isJSFormatChar(c)) { continue; } if (ScriptRuntime.isJSLineTerminator(c)) { lineEndChar = c; c = '\n'; } } return c; } } private void ungetCharIgnoreLineEnd(int c) { ungetBuffer[ungetCursor++] = c; cursor--; } private void skipLine() throws IOException { // skip to end of line int c; while ((c = getChar()) != EOF_CHAR && c != '\n') { } ungetChar(c); tokenEnd = cursor; } /** * Returns the offset into the current line. */ final int getOffset() { int n = sourceCursor - lineStart; if (lineEndChar >= 0) { --n; } return n; } final String getLine() { if (sourceString != null) { // String case int lineEnd = sourceCursor; if (lineEndChar >= 0) { --lineEnd; } else { for (; lineEnd != sourceEnd; ++lineEnd) { int c = sourceString.charAt(lineEnd); if (ScriptRuntime.isJSLineTerminator(c)) { break; } } } return sourceString.substring(lineStart, lineEnd); } else { // Reader case int lineLength = sourceCursor - lineStart; if (lineEndChar >= 0) { --lineLength; } else { // Read until the end of line for (;; ++lineLength) { int i = lineStart + lineLength; if (i == sourceEnd) { try { if (!fillSourceBuffer()) { break; } } catch (IOException ioe) { // ignore it, we're already displaying an error... break; } // i recalculuation as fillSourceBuffer can move saved // line buffer and change lineStart i = lineStart + lineLength; } int c = sourceBuffer[i]; if (ScriptRuntime.isJSLineTerminator(c)) { break; } } } return new String(sourceBuffer, lineStart, lineLength); } } private boolean fillSourceBuffer() throws IOException { if (sourceString != null) Kit.codeBug(); if (sourceEnd == sourceBuffer.length) { if (lineStart != 0 && !isMarkingComment()) { System.arraycopy(sourceBuffer, lineStart, sourceBuffer, 0, sourceEnd - lineStart); sourceEnd -= lineStart; sourceCursor -= lineStart; lineStart = 0; } else { char[] tmp = new char[sourceBuffer.length * 2]; System.arraycopy(sourceBuffer, 0, tmp, 0, sourceEnd); sourceBuffer = tmp; } } int n = sourceReader.read(sourceBuffer, sourceEnd, sourceBuffer.length - sourceEnd); if (n < 0) { return false; } sourceEnd += n; return true; } /** * Return the current position of the scanner cursor. */ public int getCursor() { return cursor; } /** * Return the absolute source offset of the last scanned token. */ public int getTokenBeg() { return tokenBeg; } /** * Return the absolute source end-offset of the last scanned token. */ public int getTokenEnd() { return tokenEnd; } /** * Return tokenEnd - tokenBeg */ public int getTokenLength() { return tokenEnd - tokenBeg; } /** * Return the type of the last scanned comment. * @return type of last scanned comment, or 0 if none have been scanned. */ public Token.CommentType getCommentType() { return commentType; } private void markCommentStart() { markCommentStart(""); } private void markCommentStart(String prefix) { if (parser.compilerEnv.isRecordingComments() && sourceReader != null) { commentPrefix = prefix; commentCursor = sourceCursor - 1; } } private boolean isMarkingComment() { return commentCursor != -1; } final String getAndResetCurrentComment() { if (sourceString != null) { if (isMarkingComment()) Kit.codeBug(); return sourceString.substring(tokenBeg, tokenEnd); } else { if (!isMarkingComment()) Kit.codeBug(); StringBuilder comment = new StringBuilder(commentPrefix); comment.append(sourceBuffer, commentCursor, getTokenLength() - commentPrefix.length()); commentCursor = -1; return comment.toString(); } } // stuff other than whitespace since start of line private boolean dirtyLine; String regExpFlags; // Set this to an initial non-null value so that the Parser has // something to retrieve even if an error has occurred and no // string is found. Fosters one class of error, but saves lots of // code. private String string = ""; private double number; // delimiter for last string literal scanned private int quoteChar; private char[] stringBuffer = new char[128]; private int stringBufferTop; private ObjToIntMap allStrings = new ObjToIntMap(50); // Room to backtrace from to < on failed match of the last - in 0 && buf.charAt(bl) == '0') { // empty } buf.setLength(bl + 1); } /* Mapping of JSDToStrMode -> JS_dtoa mode */ private static final int dtoaModes[] = { 0, /* DTOSTR_STANDARD */ 0, /* DTOSTR_STANDARD_EXPONENTIAL, */ 3, /* DTOSTR_FIXED, */ 2, /* DTOSTR_EXPONENTIAL, */ 2}; /* DTOSTR_PRECISION */ static void JS_dtostr(StringBuffer buffer, int mode, int precision, double d) { int decPt; /* Position of decimal point relative to first digit returned by JS_dtoa */ boolean[] sign = new boolean[1]; /* true if the sign bit was set in d */ int nDigits; /* Number of significand digits returned by JS_dtoa */ // JS_ASSERT(bufferSize >= (size_t)(mode <= DTOSTR_STANDARD_EXPONENTIAL ? DTOSTR_STANDARD_BUFFER_SIZE : // DTOSTR_VARIABLE_BUFFER_SIZE(precision))); if (mode == DTOSTR_FIXED && (d >= 1e21 || d <= -1e21)) mode = DTOSTR_STANDARD; /* Change mode here rather than below because the buffer may not be large enough to hold a large integer. */ decPt = JS_dtoa(d, dtoaModes[mode], mode >= DTOSTR_FIXED, precision, sign, buffer); nDigits = buffer.length(); /* If Infinity, -Infinity, or NaN, return the string regardless of the mode. */ if (decPt != 9999) { boolean exponentialNotation = false; int minNDigits = 0; /* Minimum number of significand digits required by mode and precision */ int p; switch (mode) { case DTOSTR_STANDARD: if (decPt < -5 || decPt > 21) exponentialNotation = true; else minNDigits = decPt; break; case DTOSTR_FIXED: if (precision >= 0) minNDigits = decPt + precision; else minNDigits = decPt; break; case DTOSTR_EXPONENTIAL: // JS_ASSERT(precision > 0); minNDigits = precision; /* Fall through */ case DTOSTR_STANDARD_EXPONENTIAL: exponentialNotation = true; break; case DTOSTR_PRECISION: // JS_ASSERT(precision > 0); minNDigits = precision; if (decPt < -5 || decPt > precision) exponentialNotation = true; break; } /* If the number has fewer than minNDigits, pad it with zeros at the end */ if (nDigits < minNDigits) { p = minNDigits; nDigits = minNDigits; do { buffer.append('0'); } while (buffer.length() != p); } if (exponentialNotation) { /* Insert a decimal point if more than one significand digit */ if (nDigits != 1) { buffer.insert(1, '.'); } buffer.append('e'); if ((decPt - 1) >= 0) buffer.append('+'); buffer.append(decPt - 1); // JS_snprintf(numEnd, bufferSize - (numEnd - buffer), "e%+d", decPt-1); } else if (decPt != nDigits) { /* Some kind of a fraction in fixed notation */ // JS_ASSERT(decPt <= nDigits); if (decPt > 0) { /* dd...dd . dd...dd */ buffer.insert(decPt, '.'); } else { /* 0 . 00...00dd...dd */ for (int i = 0; i < 1 - decPt; i++) buffer.insert(0, '0'); buffer.insert(1, '.'); } } } /* If negative and neither -0.0 nor NaN, output a leading '-'. */ if (sign[0] && !(word0(d) == Sign_bit && word1(d) == 0) && !((word0(d) & Exp_mask) == Exp_mask && ((word1(d) != 0) || ((word0(d) & Frac_mask) != 0)))) { buffer.insert(0, '-'); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/NativeString.java0000644000175000017500000007126411314263504033375 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Tom Beauvais * Norris Boyd * Mike McCabe * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.text.Collator; /** * This class implements the String native object. * * See ECMA 15.5. * * String methods for dealing with regular expressions are * ported directly from C. Latest port is from version 1.40.12.19 * in the JSFUN13_BRANCH. * * @author Mike McCabe * @author Norris Boyd */ final class NativeString extends IdScriptableObject { static final long serialVersionUID = 920268368584188687L; private static final Object STRING_TAG = "String"; static void init(Scriptable scope, boolean sealed) { NativeString obj = new NativeString(""); obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed); } private NativeString(String s) { string = s; } @Override public String getClassName() { return "String"; } private static final int Id_length = 1, MAX_INSTANCE_ID = 1; @Override protected int getMaxInstanceId() { return MAX_INSTANCE_ID; } @Override protected int findInstanceIdInfo(String s) { if (s.equals("length")) { return instanceIdInfo(DONTENUM | READONLY | PERMANENT, Id_length); } return super.findInstanceIdInfo(s); } @Override protected String getInstanceIdName(int id) { if (id == Id_length) { return "length"; } return super.getInstanceIdName(id); } @Override protected Object getInstanceIdValue(int id) { if (id == Id_length) { return ScriptRuntime.wrapInt(string.length()); } return super.getInstanceIdValue(id); } @Override protected void fillConstructorProperties(IdFunctionObject ctor) { addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_fromCharCode, "fromCharCode", 1); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_charAt, "charAt", 2); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_charCodeAt, "charCodeAt", 2); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_indexOf, "indexOf", 2); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_lastIndexOf, "lastIndexOf", 2); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_split, "split", 3); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_substring, "substring", 3); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_toLowerCase, "toLowerCase", 1); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_toUpperCase, "toUpperCase", 1); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_substr, "substr", 3); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_concat, "concat", 2); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_slice, "slice", 3); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_equalsIgnoreCase, "equalsIgnoreCase", 2); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_match, "match", 2); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_search, "search", 2); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_replace, "replace", 2); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_localeCompare, "localeCompare", 2); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_toLocaleLowerCase, "toLocaleLowerCase", 1); addIdFunctionProperty(ctor, STRING_TAG, ConstructorId_fromCharCode, "fromCharCode", 1); super.fillConstructorProperties(ctor); } @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=1; s="constructor"; break; case Id_toString: arity=0; s="toString"; break; case Id_toSource: arity=0; s="toSource"; break; case Id_valueOf: arity=0; s="valueOf"; break; case Id_charAt: arity=1; s="charAt"; break; case Id_charCodeAt: arity=1; s="charCodeAt"; break; case Id_indexOf: arity=1; s="indexOf"; break; case Id_lastIndexOf: arity=1; s="lastIndexOf"; break; case Id_split: arity=2; s="split"; break; case Id_substring: arity=2; s="substring"; break; case Id_toLowerCase: arity=0; s="toLowerCase"; break; case Id_toUpperCase: arity=0; s="toUpperCase"; break; case Id_substr: arity=2; s="substr"; break; case Id_concat: arity=1; s="concat"; break; case Id_slice: arity=2; s="slice"; break; case Id_bold: arity=0; s="bold"; break; case Id_italics: arity=0; s="italics"; break; case Id_fixed: arity=0; s="fixed"; break; case Id_strike: arity=0; s="strike"; break; case Id_small: arity=0; s="small"; break; case Id_big: arity=0; s="big"; break; case Id_blink: arity=0; s="blink"; break; case Id_sup: arity=0; s="sup"; break; case Id_sub: arity=0; s="sub"; break; case Id_fontsize: arity=0; s="fontsize"; break; case Id_fontcolor: arity=0; s="fontcolor"; break; case Id_link: arity=0; s="link"; break; case Id_anchor: arity=0; s="anchor"; break; case Id_equals: arity=1; s="equals"; break; case Id_equalsIgnoreCase: arity=1; s="equalsIgnoreCase"; break; case Id_match: arity=1; s="match"; break; case Id_search: arity=1; s="search"; break; case Id_replace: arity=1; s="replace"; break; case Id_localeCompare: arity=1; s="localeCompare"; break; case Id_toLocaleLowerCase: arity=0; s="toLocaleLowerCase"; break; case Id_toLocaleUpperCase: arity=0; s="toLocaleUpperCase"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(STRING_TAG, id, s, arity); } @Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(STRING_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); again: for(;;) { switch (id) { case ConstructorId_charAt: case ConstructorId_charCodeAt: case ConstructorId_indexOf: case ConstructorId_lastIndexOf: case ConstructorId_split: case ConstructorId_substring: case ConstructorId_toLowerCase: case ConstructorId_toUpperCase: case ConstructorId_substr: case ConstructorId_concat: case ConstructorId_slice: case ConstructorId_equalsIgnoreCase: case ConstructorId_match: case ConstructorId_search: case ConstructorId_replace: case ConstructorId_localeCompare: case ConstructorId_toLocaleLowerCase: { if (args.length > 0) { thisObj = ScriptRuntime.toObject(scope, ScriptRuntime.toString(args[0])); Object[] newArgs = new Object[args.length-1]; for (int i=0; i < newArgs.length; i++) newArgs[i] = args[i+1]; args = newArgs; } else { thisObj = ScriptRuntime.toObject(scope, ScriptRuntime.toString(thisObj)); } id = -id; continue again; } case ConstructorId_fromCharCode: { int N = args.length; if (N < 1) return ""; StringBuffer sb = new StringBuffer(N); for (int i = 0; i != N; ++i) { sb.append(ScriptRuntime.toUint16(args[i])); } return sb.toString(); } case Id_constructor: { String s = (args.length >= 1) ? ScriptRuntime.toString(args[0]) : ""; if (thisObj == null) { // new String(val) creates a new String object. return new NativeString(s); } // String(val) converts val to a string value. return s; } case Id_toString: case Id_valueOf: // ECMA 15.5.4.2: 'the toString function is not generic. return realThis(thisObj, f).string; case Id_toSource: { String s = realThis(thisObj, f).string; return "(new String(\""+ScriptRuntime.escapeString(s)+"\"))"; } case Id_charAt: case Id_charCodeAt: { // See ECMA 15.5.4.[4,5] String target = ScriptRuntime.toString(thisObj); double pos = ScriptRuntime.toInteger(args, 0); if (pos < 0 || pos >= target.length()) { if (id == Id_charAt) return ""; else return ScriptRuntime.NaNobj; } char c = target.charAt((int)pos); if (id == Id_charAt) return String.valueOf(c); else return ScriptRuntime.wrapInt(c); } case Id_indexOf: return ScriptRuntime.wrapInt(js_indexOf( ScriptRuntime.toString(thisObj), args)); case Id_lastIndexOf: return ScriptRuntime.wrapInt(js_lastIndexOf( ScriptRuntime.toString(thisObj), args)); case Id_split: return ScriptRuntime.checkRegExpProxy(cx). js_split(cx, scope, ScriptRuntime.toString(thisObj), args); case Id_substring: return js_substring(cx, ScriptRuntime.toString(thisObj), args); case Id_toLowerCase: // See ECMA 15.5.4.11 return ScriptRuntime.toString(thisObj).toLowerCase(); case Id_toUpperCase: // See ECMA 15.5.4.12 return ScriptRuntime.toString(thisObj).toUpperCase(); case Id_substr: return js_substr(ScriptRuntime.toString(thisObj), args); case Id_concat: return js_concat(ScriptRuntime.toString(thisObj), args); case Id_slice: return js_slice(ScriptRuntime.toString(thisObj), args); case Id_bold: return tagify(thisObj, "b", null, null); case Id_italics: return tagify(thisObj, "i", null, null); case Id_fixed: return tagify(thisObj, "tt", null, null); case Id_strike: return tagify(thisObj, "strike", null, null); case Id_small: return tagify(thisObj, "small", null, null); case Id_big: return tagify(thisObj, "big", null, null); case Id_blink: return tagify(thisObj, "blink", null, null); case Id_sup: return tagify(thisObj, "sup", null, null); case Id_sub: return tagify(thisObj, "sub", null, null); case Id_fontsize: return tagify(thisObj, "font", "size", args); case Id_fontcolor: return tagify(thisObj, "font", "color", args); case Id_link: return tagify(thisObj, "a", "href", args); case Id_anchor: return tagify(thisObj, "a", "name", args); case Id_equals: case Id_equalsIgnoreCase: { String s1 = ScriptRuntime.toString(thisObj); String s2 = ScriptRuntime.toString(args, 0); return ScriptRuntime.wrapBoolean( (id == Id_equals) ? s1.equals(s2) : s1.equalsIgnoreCase(s2)); } case Id_match: case Id_search: case Id_replace: { int actionType; if (id == Id_match) { actionType = RegExpProxy.RA_MATCH; } else if (id == Id_search) { actionType = RegExpProxy.RA_SEARCH; } else { actionType = RegExpProxy.RA_REPLACE; } return ScriptRuntime.checkRegExpProxy(cx). action(cx, scope, thisObj, args, actionType); } // ECMA-262 1 5.5.4.9 case Id_localeCompare: { // For now, create and configure a collator instance. I can't // actually imagine that this'd be slower than caching them // a la ClassCache, so we aren't trying to outsmart ourselves // with a caching mechanism for now. Collator collator = Collator.getInstance(cx.getLocale()); collator.setStrength(Collator.IDENTICAL); collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION); return ScriptRuntime.wrapNumber(collator.compare( ScriptRuntime.toString(thisObj), ScriptRuntime.toString(args, 0))); } case Id_toLocaleLowerCase: { return ScriptRuntime.toString(thisObj) .toLowerCase(cx.getLocale()); } case Id_toLocaleUpperCase: { return ScriptRuntime.toString(thisObj) .toUpperCase(cx.getLocale()); } } throw new IllegalArgumentException(String.valueOf(id)); } } private static NativeString realThis(Scriptable thisObj, IdFunctionObject f) { if (!(thisObj instanceof NativeString)) throw incompatibleCallError(f); return (NativeString)thisObj; } /* * HTML composition aids. */ private static String tagify(Object thisObj, String tag, String attribute, Object[] args) { String str = ScriptRuntime.toString(thisObj); StringBuffer result = new StringBuffer(); result.append('<'); result.append(tag); if (attribute != null) { result.append(' '); result.append(attribute); result.append("=\""); result.append(ScriptRuntime.toString(args, 0)); result.append('"'); } result.append('>'); result.append(str); result.append("'); return result.toString(); } @Override public String toString() { return string; } /* Make array-style property lookup work for strings. * XXX is this ECMA? A version check is probably needed. In js too. */ @Override public Object get(int index, Scriptable start) { if (0 <= index && index < string.length()) { return string.substring(index, index + 1); } return super.get(index, start); } @Override public void put(int index, Scriptable start, Object value) { if (0 <= index && index < string.length()) { return; } super.put(index, start, value); } /* * * See ECMA 15.5.4.6. Uses Java String.indexOf() * OPT to add - BMH searching from jsstr.c. */ private static int js_indexOf(String target, Object[] args) { String search = ScriptRuntime.toString(args, 0); double begin = ScriptRuntime.toInteger(args, 1); if (begin > target.length()) { return -1; } else { if (begin < 0) begin = 0; return target.indexOf(search, (int)begin); } } /* * * See ECMA 15.5.4.7 * */ private static int js_lastIndexOf(String target, Object[] args) { String search = ScriptRuntime.toString(args, 0); double end = ScriptRuntime.toNumber(args, 1); if (end != end || end > target.length()) end = target.length(); else if (end < 0) end = 0; return target.lastIndexOf(search, (int)end); } /* * See ECMA 15.5.4.15 */ private static String js_substring(Context cx, String target, Object[] args) { int length = target.length(); double start = ScriptRuntime.toInteger(args, 0); double end; if (start < 0) start = 0; else if (start > length) start = length; if (args.length <= 1 || args[1] == Undefined.instance) { end = length; } else { end = ScriptRuntime.toInteger(args[1]); if (end < 0) end = 0; else if (end > length) end = length; // swap if end < start if (end < start) { if (cx.getLanguageVersion() != Context.VERSION_1_2) { double temp = start; start = end; end = temp; } else { // Emulate old JDK1.0 java.lang.String.substring() end = start; } } } return target.substring((int)start, (int)end); } int getLength() { return string.length(); } /* * Non-ECMA methods. */ private static String js_substr(String target, Object[] args) { if (args.length < 1) return target; double begin = ScriptRuntime.toInteger(args[0]); double end; int length = target.length(); if (begin < 0) { begin += length; if (begin < 0) begin = 0; } else if (begin > length) { begin = length; } if (args.length == 1) { end = length; } else { end = ScriptRuntime.toInteger(args[1]); if (end < 0) end = 0; end += begin; if (end > length) end = length; } return target.substring((int)begin, (int)end); } /* * Python-esque sequence operations. */ private static String js_concat(String target, Object[] args) { int N = args.length; if (N == 0) { return target; } else if (N == 1) { String arg = ScriptRuntime.toString(args[0]); return target.concat(arg); } // Find total capacity for the final string to avoid unnecessary // re-allocations in StringBuffer int size = target.length(); String[] argsAsStrings = new String[N]; for (int i = 0; i != N; ++i) { String s = ScriptRuntime.toString(args[i]); argsAsStrings[i] = s; size += s.length(); } StringBuffer result = new StringBuffer(size); result.append(target); for (int i = 0; i != N; ++i) { result.append(argsAsStrings[i]); } return result.toString(); } private static String js_slice(String target, Object[] args) { if (args.length != 0) { double begin = ScriptRuntime.toInteger(args[0]); double end; int length = target.length(); if (begin < 0) { begin += length; if (begin < 0) begin = 0; } else if (begin > length) { begin = length; } if (args.length == 1) { end = length; } else { end = ScriptRuntime.toInteger(args[1]); if (end < 0) { end += length; if (end < 0) end = 0; } else if (end > length) { end = length; } if (end < begin) end = begin; } return target.substring((int)begin, (int)end); } return target; } // #string_id_map# @Override protected int findPrototypeId(String s) { int id; // #generated# Last update: 2007-05-01 22:11:49 EDT L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 3: c=s.charAt(2); if (c=='b') { if (s.charAt(0)=='s' && s.charAt(1)=='u') {id=Id_sub; break L0;} } else if (c=='g') { if (s.charAt(0)=='b' && s.charAt(1)=='i') {id=Id_big; break L0;} } else if (c=='p') { if (s.charAt(0)=='s' && s.charAt(1)=='u') {id=Id_sup; break L0;} } break L; case 4: c=s.charAt(0); if (c=='b') { X="bold";id=Id_bold; } else if (c=='l') { X="link";id=Id_link; } break L; case 5: switch (s.charAt(4)) { case 'd': X="fixed";id=Id_fixed; break L; case 'e': X="slice";id=Id_slice; break L; case 'h': X="match";id=Id_match; break L; case 'k': X="blink";id=Id_blink; break L; case 'l': X="small";id=Id_small; break L; case 't': X="split";id=Id_split; break L; } break L; case 6: switch (s.charAt(1)) { case 'e': X="search";id=Id_search; break L; case 'h': X="charAt";id=Id_charAt; break L; case 'n': X="anchor";id=Id_anchor; break L; case 'o': X="concat";id=Id_concat; break L; case 'q': X="equals";id=Id_equals; break L; case 't': X="strike";id=Id_strike; break L; case 'u': X="substr";id=Id_substr; break L; } break L; case 7: switch (s.charAt(1)) { case 'a': X="valueOf";id=Id_valueOf; break L; case 'e': X="replace";id=Id_replace; break L; case 'n': X="indexOf";id=Id_indexOf; break L; case 't': X="italics";id=Id_italics; break L; } break L; case 8: c=s.charAt(4); if (c=='r') { X="toString";id=Id_toString; } else if (c=='s') { X="fontsize";id=Id_fontsize; } else if (c=='u') { X="toSource";id=Id_toSource; } break L; case 9: c=s.charAt(0); if (c=='f') { X="fontcolor";id=Id_fontcolor; } else if (c=='s') { X="substring";id=Id_substring; } break L; case 10: X="charCodeAt";id=Id_charCodeAt; break L; case 11: switch (s.charAt(2)) { case 'L': X="toLowerCase";id=Id_toLowerCase; break L; case 'U': X="toUpperCase";id=Id_toUpperCase; break L; case 'n': X="constructor";id=Id_constructor; break L; case 's': X="lastIndexOf";id=Id_lastIndexOf; break L; } break L; case 13: X="localeCompare";id=Id_localeCompare; break L; case 16: X="equalsIgnoreCase";id=Id_equalsIgnoreCase; break L; case 17: c=s.charAt(8); if (c=='L') { X="toLocaleLowerCase";id=Id_toLocaleLowerCase; } else if (c=='U') { X="toLocaleUpperCase";id=Id_toLocaleUpperCase; } break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# return id; } private static final int ConstructorId_fromCharCode = -1, Id_constructor = 1, Id_toString = 2, Id_toSource = 3, Id_valueOf = 4, Id_charAt = 5, Id_charCodeAt = 6, Id_indexOf = 7, Id_lastIndexOf = 8, Id_split = 9, Id_substring = 10, Id_toLowerCase = 11, Id_toUpperCase = 12, Id_substr = 13, Id_concat = 14, Id_slice = 15, Id_bold = 16, Id_italics = 17, Id_fixed = 18, Id_strike = 19, Id_small = 20, Id_big = 21, Id_blink = 22, Id_sup = 23, Id_sub = 24, Id_fontsize = 25, Id_fontcolor = 26, Id_link = 27, Id_anchor = 28, Id_equals = 29, Id_equalsIgnoreCase = 30, Id_match = 31, Id_search = 32, Id_replace = 33, Id_localeCompare = 34, Id_toLocaleLowerCase = 35, Id_toLocaleUpperCase = 36, MAX_PROTOTYPE_ID = 36; // #/string_id_map# private static final int ConstructorId_charAt = -Id_charAt, ConstructorId_charCodeAt = -Id_charCodeAt, ConstructorId_indexOf = -Id_indexOf, ConstructorId_lastIndexOf = -Id_lastIndexOf, ConstructorId_split = -Id_split, ConstructorId_substring = -Id_substring, ConstructorId_toLowerCase = -Id_toLowerCase, ConstructorId_toUpperCase = -Id_toUpperCase, ConstructorId_substr = -Id_substr, ConstructorId_concat = -Id_concat, ConstructorId_slice = -Id_slice, ConstructorId_equalsIgnoreCase = -Id_equalsIgnoreCase, ConstructorId_match = -Id_match, ConstructorId_search = -Id_search, ConstructorId_replace = -Id_replace, ConstructorId_localeCompare = -Id_localeCompare, ConstructorId_toLocaleLowerCase = -Id_toLocaleLowerCase; private String string; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/NativeObject.java0000644000175000017500000005143611314263504033334 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Bob Jervis * Mike McCabe * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.util.Map; import java.util.LinkedHashMap; /** * This class implements the Object native object. * See ECMA 15.2. * @author Norris Boyd */ public class NativeObject extends IdScriptableObject { static final long serialVersionUID = -6345305608474346996L; private static final Object OBJECT_TAG = "Object"; static void init(Scriptable scope, boolean sealed) { NativeObject obj = new NativeObject(); obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed); } @Override public String getClassName() { return "Object"; } @Override public String toString() { return ScriptRuntime.defaultObjectToString(this); } @Override protected void fillConstructorProperties(IdFunctionObject ctor) { addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_getPrototypeOf, "getPrototypeOf", 1); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_keys, "keys", 1); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_getOwnPropertyNames, "getOwnPropertyNames", 1); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_getOwnPropertyDescriptor, "getOwnPropertyDescriptor", 2); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_defineProperty, "defineProperty", 3); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_isExtensible, "isExtensible", 1); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_preventExtensions, "preventExtensions", 1); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_defineProperties, "defineProperties", 2); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_create, "create", 2); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_isSealed, "isSealed", 1); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_isFrozen, "isFrozen", 1); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_seal, "seal", 1); addIdFunctionProperty(ctor, OBJECT_TAG, ConstructorId_freeze, "freeze", 1); super.fillConstructorProperties(ctor); } @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=1; s="constructor"; break; case Id_toString: arity=0; s="toString"; break; case Id_toLocaleString: arity=0; s="toLocaleString"; break; case Id_valueOf: arity=0; s="valueOf"; break; case Id_hasOwnProperty: arity=1; s="hasOwnProperty"; break; case Id_propertyIsEnumerable: arity=1; s="propertyIsEnumerable"; break; case Id_isPrototypeOf: arity=1; s="isPrototypeOf"; break; case Id_toSource: arity=0; s="toSource"; break; case Id___defineGetter__: arity=2; s="__defineGetter__"; break; case Id___defineSetter__: arity=2; s="__defineSetter__"; break; case Id___lookupGetter__: arity=1; s="__lookupGetter__"; break; case Id___lookupSetter__: arity=1; s="__lookupSetter__"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(OBJECT_TAG, id, s, arity); } @Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(OBJECT_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); switch (id) { case Id_constructor: { if (thisObj != null) { // BaseFunction.construct will set up parent, proto return f.construct(cx, scope, args); } if (args.length == 0 || args[0] == null || args[0] == Undefined.instance) { return new NativeObject(); } return ScriptRuntime.toObject(cx, scope, args[0]); } case Id_toLocaleString: // For now just alias toString case Id_toString: { if (cx.hasFeature(Context.FEATURE_TO_STRING_AS_SOURCE)) { String s = ScriptRuntime.defaultObjectToSource(cx, scope, thisObj, args); int L = s.length(); if (L != 0 && s.charAt(0) == '(' && s.charAt(L - 1) == ')') { // Strip () that surrounds toSource s = s.substring(1, L - 1); } return s; } return ScriptRuntime.defaultObjectToString(thisObj); } case Id_valueOf: return thisObj; case Id_hasOwnProperty: { boolean result; if (args.length == 0) { result = false; } else { String s = ScriptRuntime.toStringIdOrIndex(cx, args[0]); if (s == null) { int index = ScriptRuntime.lastIndexResult(cx); result = thisObj.has(index, thisObj); } else { result = thisObj.has(s, thisObj); } } return ScriptRuntime.wrapBoolean(result); } case Id_propertyIsEnumerable: { boolean result; if (args.length == 0) { result = false; } else { String s = ScriptRuntime.toStringIdOrIndex(cx, args[0]); if (s == null) { int index = ScriptRuntime.lastIndexResult(cx); result = thisObj.has(index, thisObj); if (result && thisObj instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)thisObj; int attrs = so.getAttributes(index); result = ((attrs & ScriptableObject.DONTENUM) == 0); } } else { result = thisObj.has(s, thisObj); if (result && thisObj instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)thisObj; int attrs = so.getAttributes(s); result = ((attrs & ScriptableObject.DONTENUM) == 0); } } } return ScriptRuntime.wrapBoolean(result); } case Id_isPrototypeOf: { boolean result = false; if (args.length != 0 && args[0] instanceof Scriptable) { Scriptable v = (Scriptable) args[0]; do { v = v.getPrototype(); if (v == thisObj) { result = true; break; } } while (v != null); } return ScriptRuntime.wrapBoolean(result); } case Id_toSource: return ScriptRuntime.defaultObjectToSource(cx, scope, thisObj, args); case Id___defineGetter__: case Id___defineSetter__: { if (args.length < 2 || !(args[1] instanceof Callable)) { Object badArg = (args.length >= 2 ? args[1] : Undefined.instance); throw ScriptRuntime.notFunctionError(badArg); } if (!(thisObj instanceof ScriptableObject)) { throw Context.reportRuntimeError2( "msg.extend.scriptable", thisObj.getClass().getName(), String.valueOf(args[0])); } ScriptableObject so = (ScriptableObject)thisObj; String name = ScriptRuntime.toStringIdOrIndex(cx, args[0]); int index = (name != null ? 0 : ScriptRuntime.lastIndexResult(cx)); Callable getterOrSetter = (Callable)args[1]; boolean isSetter = (id == Id___defineSetter__); so.setGetterOrSetter(name, index, getterOrSetter, isSetter); if (so instanceof NativeArray) ((NativeArray)so).setDenseOnly(false); } return Undefined.instance; case Id___lookupGetter__: case Id___lookupSetter__: { if (args.length < 1 || !(thisObj instanceof ScriptableObject)) return Undefined.instance; ScriptableObject so = (ScriptableObject)thisObj; String name = ScriptRuntime.toStringIdOrIndex(cx, args[0]); int index = (name != null ? 0 : ScriptRuntime.lastIndexResult(cx)); boolean isSetter = (id == Id___lookupSetter__); Object gs; for (;;) { gs = so.getGetterOrSetter(name, index, isSetter); if (gs != null) break; // If there is no getter or setter for the object itself, // how about the prototype? Scriptable v = so.getPrototype(); if (v == null) break; if (v instanceof ScriptableObject) so = (ScriptableObject)v; else break; } if (gs != null) return gs; } return Undefined.instance; case ConstructorId_getPrototypeOf: { Object arg = args.length < 1 ? Undefined.instance : args[0]; Scriptable obj = ensureScriptable(arg); return obj.getPrototype(); } case ConstructorId_keys: { Object arg = args.length < 1 ? Undefined.instance : args[0]; Scriptable obj = ensureScriptable(arg); Object[] ids = obj.getIds(); for (int i = 0; i < ids.length; i++) { ids[i] = ScriptRuntime.toString(ids[i]); } return cx.newArray(scope, ids); } case ConstructorId_getOwnPropertyNames: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); Object[] ids = obj.getAllIds(); for (int i = 0; i < ids.length; i++) { ids[i] = ScriptRuntime.toString(ids[i]); } return cx.newArray(scope, ids); } case ConstructorId_getOwnPropertyDescriptor: { Object arg = args.length < 1 ? Undefined.instance : args[0]; // TODO(norris): There's a deeper issue here if // arg instanceof Scriptable. Should we create a new // interface to admit the new ECMAScript 5 operations? ScriptableObject obj = ensureScriptableObject(arg); Object nameArg = args.length < 2 ? Undefined.instance : args[1]; String name = ScriptRuntime.toString(nameArg); Scriptable desc = obj.getOwnPropertyDescriptor(cx, name); return desc == null ? Undefined.instance : desc; } case ConstructorId_defineProperty: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); Object name = args.length < 2 ? Undefined.instance : args[1]; Object descArg = args.length < 3 ? Undefined.instance : args[2]; ScriptableObject desc = ensureScriptableObject(descArg); obj.defineOwnProperty(cx, name, desc); return obj; } case ConstructorId_isExtensible: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); return obj.isExtensible(); } case ConstructorId_preventExtensions: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); obj.preventExtensions(); return obj; } case ConstructorId_defineProperties: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); Object propsObj = args.length < 2 ? Undefined.instance : args[1]; Scriptable props = Context.toObject(propsObj, getParentScope()); obj.defineOwnProperties(cx, ensureScriptableObject(props)); return obj; } case ConstructorId_create: { Object arg = args.length < 1 ? Undefined.instance : args[0]; Scriptable obj = ensureScriptable(arg); ScriptableObject newObject = new NativeObject(); newObject.setParentScope(this.getParentScope()); newObject.setPrototype(obj); if (args.length > 1 && args[1] != Undefined.instance) { Scriptable props = Context.toObject(args[1], getParentScope()); newObject.defineOwnProperties(cx, ensureScriptableObject(props)); } return newObject; } case ConstructorId_isSealed: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); for (Object name: obj.getAllIds()) { Object configurable = obj.getOwnPropertyDescriptor(cx, name).get("configurable"); if (Boolean.TRUE.equals(configurable)) return false; } return !obj.isExtensible(); } case ConstructorId_isFrozen: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); for (Object name: obj.getAllIds()) { ScriptableObject desc = obj.getOwnPropertyDescriptor(cx, name); if (Boolean.TRUE.equals(desc.get("configurable"))) return false; if (isDataDescriptor(desc) && Boolean.TRUE.equals(desc.get("writable"))) return false; } return !obj.isExtensible(); } case ConstructorId_seal: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); for (Object name: obj.getAllIds()) { ScriptableObject desc = obj.getOwnPropertyDescriptor(cx, name); if (Boolean.TRUE.equals(desc.get("configurable"))) { desc.put("configurable", desc, false); obj.defineOwnProperty(cx, name, desc); } } obj.preventExtensions(); return obj; } case ConstructorId_freeze: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); for (Object name: obj.getAllIds()) { ScriptableObject desc = obj.getOwnPropertyDescriptor(cx, name); if (isDataDescriptor(desc) && Boolean.TRUE.equals(desc.get("writable"))) desc.put("writable", desc, false); if (Boolean.TRUE.equals(desc.get("configurable"))) desc.put("configurable", desc, false); obj.defineOwnProperty(cx, name, desc); } obj.preventExtensions(); return obj; } default: throw new IllegalArgumentException(String.valueOf(id)); } } // #string_id_map# @Override protected int findPrototypeId(String s) { int id; // #generated# Last update: 2007-05-09 08:15:55 EDT L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 7: X="valueOf";id=Id_valueOf; break L; case 8: c=s.charAt(3); if (c=='o') { X="toSource";id=Id_toSource; } else if (c=='t') { X="toString";id=Id_toString; } break L; case 11: X="constructor";id=Id_constructor; break L; case 13: X="isPrototypeOf";id=Id_isPrototypeOf; break L; case 14: c=s.charAt(0); if (c=='h') { X="hasOwnProperty";id=Id_hasOwnProperty; } else if (c=='t') { X="toLocaleString";id=Id_toLocaleString; } break L; case 16: c=s.charAt(2); if (c=='d') { c=s.charAt(8); if (c=='G') { X="__defineGetter__";id=Id___defineGetter__; } else if (c=='S') { X="__defineSetter__";id=Id___defineSetter__; } } else if (c=='l') { c=s.charAt(8); if (c=='G') { X="__lookupGetter__";id=Id___lookupGetter__; } else if (c=='S') { X="__lookupSetter__";id=Id___lookupSetter__; } } break L; case 20: X="propertyIsEnumerable";id=Id_propertyIsEnumerable; break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# return id; } private static final int ConstructorId_getPrototypeOf = -1, ConstructorId_keys = -2, ConstructorId_getOwnPropertyNames = -3, ConstructorId_getOwnPropertyDescriptor = -4, ConstructorId_defineProperty = -5, ConstructorId_isExtensible = -6, ConstructorId_preventExtensions = -7, ConstructorId_defineProperties= -8, ConstructorId_create = -9, ConstructorId_isSealed = -10, ConstructorId_isFrozen = -11, ConstructorId_seal = -12, ConstructorId_freeze = -13, Id_constructor = 1, Id_toString = 2, Id_toLocaleString = 3, Id_valueOf = 4, Id_hasOwnProperty = 5, Id_propertyIsEnumerable = 6, Id_isPrototypeOf = 7, Id_toSource = 8, Id___defineGetter__ = 9, Id___defineSetter__ = 10, Id___lookupGetter__ = 11, Id___lookupSetter__ = 12, MAX_PROTOTYPE_ID = 12; // #/string_id_map# } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/Wrapper.java0000644000175000017500000000400011314263504032360 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; /** * Objects that can wrap other values for reflection in the JS environment * will implement Wrapper. * * Wrapper defines a single method that can be called to unwrap the object. */ public interface Wrapper { /** * Unwrap the object by returning the wrapped value. * * @return a wrapped value */ public Object unwrap(); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/CodeGenerator.java0000644000175000017500000014112711314263504033475 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Patrick Beard * Norris Boyd * Igor Bukanov * Ethan Hugg * Bob Jervis * Terry Lucas * Roger Lawrence * Milen Nankov * Hannes Wallnoefer * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import org.mozilla.javascript.ast.ScriptNode; import org.mozilla.javascript.ast.Jump; import org.mozilla.javascript.ast.FunctionNode; /** * Generates bytecode for the Interpreter. */ class CodeGenerator extends Icode { private static final int MIN_LABEL_TABLE_SIZE = 32; private static final int MIN_FIXUP_TABLE_SIZE = 40; private CompilerEnvirons compilerEnv; private boolean itsInFunctionFlag; private boolean itsInTryFlag; private InterpreterData itsData; private ScriptNode scriptOrFn; private int iCodeTop; private int stackDepth; private int lineNumber; private int doubleTableTop; private ObjToIntMap strings = new ObjToIntMap(20); private int localTop; private int[] labelTable; private int labelTableTop; // fixupTable[i] = (label_index << 32) | fixup_site private long[] fixupTable; private int fixupTableTop; private ObjArray literalIds = new ObjArray(); private int exceptionTableTop; // ECF_ or Expression Context Flags constants: for now only TAIL private static final int ECF_TAIL = 1 << 0; public InterpreterData compile(CompilerEnvirons compilerEnv, ScriptNode tree, String encodedSource, boolean returnFunction) { this.compilerEnv = compilerEnv; if (Token.printTrees) { System.out.println("before transform:"); System.out.println(tree.toStringTree(tree)); } new NodeTransformer().transform(tree); if (Token.printTrees) { System.out.println("after transform:"); System.out.println(tree.toStringTree(tree)); } if (returnFunction) { scriptOrFn = tree.getFunctionNode(0); } else { scriptOrFn = tree; } itsData = new InterpreterData(compilerEnv.getLanguageVersion(), scriptOrFn.getSourceName(), encodedSource); itsData.topLevel = true; if (returnFunction) { generateFunctionICode(); } else { generateICodeFromTree(scriptOrFn); } return itsData; } private void generateFunctionICode() { itsInFunctionFlag = true; FunctionNode theFunction = (FunctionNode)scriptOrFn; itsData.itsFunctionType = theFunction.getFunctionType(); itsData.itsNeedsActivation = theFunction.requiresActivation(); if (theFunction.getFunctionName() != null) { itsData.itsName = theFunction.getName(); } if (!theFunction.getIgnoreDynamicScope()) { if (compilerEnv.isUseDynamicScope()) { itsData.useDynamicScope = true; } } if (theFunction.isGenerator()) { addIcode(Icode_GENERATOR); addUint16(theFunction.getBaseLineno() & 0xFFFF); } generateICodeFromTree(theFunction.getLastChild()); } private void generateICodeFromTree(Node tree) { generateNestedFunctions(); generateRegExpLiterals(); visitStatement(tree, 0); fixLabelGotos(); // add RETURN_RESULT only to scripts as function always ends with RETURN if (itsData.itsFunctionType == 0) { addToken(Token.RETURN_RESULT); } if (itsData.itsICode.length != iCodeTop) { // Make itsData.itsICode length exactly iCodeTop to save memory // and catch bugs with jumps beyond icode as early as possible byte[] tmp = new byte[iCodeTop]; System.arraycopy(itsData.itsICode, 0, tmp, 0, iCodeTop); itsData.itsICode = tmp; } if (strings.size() == 0) { itsData.itsStringTable = null; } else { itsData.itsStringTable = new String[strings.size()]; ObjToIntMap.Iterator iter = strings.newIterator(); for (iter.start(); !iter.done(); iter.next()) { String str = (String)iter.getKey(); int index = iter.getValue(); if (itsData.itsStringTable[index] != null) Kit.codeBug(); itsData.itsStringTable[index] = str; } } if (doubleTableTop == 0) { itsData.itsDoubleTable = null; } else if (itsData.itsDoubleTable.length != doubleTableTop) { double[] tmp = new double[doubleTableTop]; System.arraycopy(itsData.itsDoubleTable, 0, tmp, 0, doubleTableTop); itsData.itsDoubleTable = tmp; } if (exceptionTableTop != 0 && itsData.itsExceptionTable.length != exceptionTableTop) { int[] tmp = new int[exceptionTableTop]; System.arraycopy(itsData.itsExceptionTable, 0, tmp, 0, exceptionTableTop); itsData.itsExceptionTable = tmp; } itsData.itsMaxVars = scriptOrFn.getParamAndVarCount(); // itsMaxFrameArray: interpret method needs this amount for its // stack and sDbl arrays itsData.itsMaxFrameArray = itsData.itsMaxVars + itsData.itsMaxLocals + itsData.itsMaxStack; itsData.argNames = scriptOrFn.getParamAndVarNames(); itsData.argIsConst = scriptOrFn.getParamAndVarConst(); itsData.argCount = scriptOrFn.getParamCount(); itsData.encodedSourceStart = scriptOrFn.getEncodedSourceStart(); itsData.encodedSourceEnd = scriptOrFn.getEncodedSourceEnd(); if (literalIds.size() != 0) { itsData.literalIds = literalIds.toArray(); } if (Token.printICode) Interpreter.dumpICode(itsData); } private void generateNestedFunctions() { int functionCount = scriptOrFn.getFunctionCount(); if (functionCount == 0) return; InterpreterData[] array = new InterpreterData[functionCount]; for (int i = 0; i != functionCount; i++) { FunctionNode fn = scriptOrFn.getFunctionNode(i); CodeGenerator gen = new CodeGenerator(); gen.compilerEnv = compilerEnv; gen.scriptOrFn = fn; gen.itsData = new InterpreterData(itsData); gen.generateFunctionICode(); array[i] = gen.itsData; } itsData.itsNestedFunctions = array; } private void generateRegExpLiterals() { int N = scriptOrFn.getRegexpCount(); if (N == 0) return; Context cx = Context.getContext(); RegExpProxy rep = ScriptRuntime.checkRegExpProxy(cx); Object[] array = new Object[N]; for (int i = 0; i != N; i++) { String string = scriptOrFn.getRegexpString(i); String flags = scriptOrFn.getRegexpFlags(i); array[i] = rep.compileRegExp(cx, string, flags); } itsData.itsRegExpLiterals = array; } private void updateLineNumber(Node node) { int lineno = node.getLineno(); if (lineno != lineNumber && lineno >= 0) { if (itsData.firstLinePC < 0) { itsData.firstLinePC = lineno; } lineNumber = lineno; addIcode(Icode_LINE); addUint16(lineno & 0xFFFF); } } private RuntimeException badTree(Node node) { throw new RuntimeException(node.toString()); } private void visitStatement(Node node, int initialStackDepth) { int type = node.getType(); Node child = node.getFirstChild(); switch (type) { case Token.FUNCTION: { int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP); int fnType = scriptOrFn.getFunctionNode(fnIndex). getFunctionType(); // Only function expressions or function expression // statements need closure code creating new function // object on stack as function statements are initialized // at script/function start. // In addition, function expressions can not be present here // at statement level, they must only be present as expressions. if (fnType == FunctionNode.FUNCTION_EXPRESSION_STATEMENT) { addIndexOp(Icode_CLOSURE_STMT, fnIndex); } else { if (fnType != FunctionNode.FUNCTION_STATEMENT) { throw Kit.codeBug(); } } // For function statements or function expression statements // in scripts, we need to ensure that the result of the script // is the function if it is the last statement in the script. // For example, eval("function () {}") should return a // function, not undefined. if (!itsInFunctionFlag) { addIndexOp(Icode_CLOSURE_EXPR, fnIndex); stackChange(1); addIcode(Icode_POP_RESULT); stackChange(-1); } } break; case Token.LABEL: case Token.LOOP: case Token.BLOCK: case Token.EMPTY: case Token.WITH: updateLineNumber(node); case Token.SCRIPT: // fall through while (child != null) { visitStatement(child, initialStackDepth); child = child.getNext(); } break; case Token.ENTERWITH: visitExpression(child, 0); addToken(Token.ENTERWITH); stackChange(-1); break; case Token.LEAVEWITH: addToken(Token.LEAVEWITH); break; case Token.LOCAL_BLOCK: { int local = allocLocal(); node.putIntProp(Node.LOCAL_PROP, local); updateLineNumber(node); while (child != null) { visitStatement(child, initialStackDepth); child = child.getNext(); } addIndexOp(Icode_LOCAL_CLEAR, local); releaseLocal(local); } break; case Token.DEBUGGER: addIcode(Icode_DEBUGGER); break; case Token.SWITCH: updateLineNumber(node); // See comments in IRFactory.createSwitch() for description // of SWITCH node { visitExpression(child, 0); for (Jump caseNode = (Jump)child.getNext(); caseNode != null; caseNode = (Jump)caseNode.getNext()) { if (caseNode.getType() != Token.CASE) throw badTree(caseNode); Node test = caseNode.getFirstChild(); addIcode(Icode_DUP); stackChange(1); visitExpression(test, 0); addToken(Token.SHEQ); stackChange(-1); // If true, Icode_IFEQ_POP will jump and remove case // value from stack addGoto(caseNode.target, Icode_IFEQ_POP); stackChange(-1); } addIcode(Icode_POP); stackChange(-1); } break; case Token.TARGET: markTargetLabel(node); break; case Token.IFEQ : case Token.IFNE : { Node target = ((Jump)node).target; visitExpression(child, 0); addGoto(target, type); stackChange(-1); } break; case Token.GOTO: { Node target = ((Jump)node).target; addGoto(target, type); } break; case Token.JSR: { Node target = ((Jump)node).target; addGoto(target, Icode_GOSUB); } break; case Token.FINALLY: { // Account for incomming GOTOSUB address stackChange(1); int finallyRegister = getLocalBlockRef(node); addIndexOp(Icode_STARTSUB, finallyRegister); stackChange(-1); while (child != null) { visitStatement(child, initialStackDepth); child = child.getNext(); } addIndexOp(Icode_RETSUB, finallyRegister); } break; case Token.EXPR_VOID: case Token.EXPR_RESULT: updateLineNumber(node); visitExpression(child, 0); addIcode((type == Token.EXPR_VOID) ? Icode_POP : Icode_POP_RESULT); stackChange(-1); break; case Token.TRY: { Jump tryNode = (Jump)node; int exceptionObjectLocal = getLocalBlockRef(tryNode); int scopeLocal = allocLocal(); addIndexOp(Icode_SCOPE_SAVE, scopeLocal); int tryStart = iCodeTop; boolean savedFlag = itsInTryFlag; itsInTryFlag = true; while (child != null) { visitStatement(child, initialStackDepth); child = child.getNext(); } itsInTryFlag = savedFlag; Node catchTarget = tryNode.target; if (catchTarget != null) { int catchStartPC = labelTable[getTargetLabel(catchTarget)]; addExceptionHandler( tryStart, catchStartPC, catchStartPC, false, exceptionObjectLocal, scopeLocal); } Node finallyTarget = tryNode.getFinally(); if (finallyTarget != null) { int finallyStartPC = labelTable[getTargetLabel(finallyTarget)]; addExceptionHandler( tryStart, finallyStartPC, finallyStartPC, true, exceptionObjectLocal, scopeLocal); } addIndexOp(Icode_LOCAL_CLEAR, scopeLocal); releaseLocal(scopeLocal); } break; case Token.CATCH_SCOPE: { int localIndex = getLocalBlockRef(node); int scopeIndex = node.getExistingIntProp(Node.CATCH_SCOPE_PROP); String name = child.getString(); child = child.getNext(); visitExpression(child, 0); // load expression object addStringPrefix(name); addIndexPrefix(localIndex); addToken(Token.CATCH_SCOPE); addUint8(scopeIndex != 0 ? 1 : 0); stackChange(-1); } break; case Token.THROW: updateLineNumber(node); visitExpression(child, 0); addToken(Token.THROW); addUint16(lineNumber & 0xFFFF); stackChange(-1); break; case Token.RETHROW: updateLineNumber(node); addIndexOp(Token.RETHROW, getLocalBlockRef(node)); break; case Token.RETURN: updateLineNumber(node); if (node.getIntProp(Node.GENERATOR_END_PROP, 0) != 0) { // We're in a generator, so change RETURN to GENERATOR_END addIcode(Icode_GENERATOR_END); addUint16(lineNumber & 0xFFFF); } else if (child != null) { visitExpression(child, ECF_TAIL); addToken(Token.RETURN); stackChange(-1); } else { addIcode(Icode_RETUNDEF); } break; case Token.RETURN_RESULT: updateLineNumber(node); addToken(Token.RETURN_RESULT); break; case Token.ENUM_INIT_KEYS: case Token.ENUM_INIT_VALUES: case Token.ENUM_INIT_ARRAY: visitExpression(child, 0); addIndexOp(type, getLocalBlockRef(node)); stackChange(-1); break; case Icode_GENERATOR: break; default: throw badTree(node); } if (stackDepth != initialStackDepth) { throw Kit.codeBug(); } } private void visitExpression(Node node, int contextFlags) { int type = node.getType(); Node child = node.getFirstChild(); int savedStackDepth = stackDepth; switch (type) { case Token.FUNCTION: { int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP); FunctionNode fn = scriptOrFn.getFunctionNode(fnIndex); // See comments in visitStatement for Token.FUNCTION case if (fn.getFunctionType() != FunctionNode.FUNCTION_EXPRESSION) { throw Kit.codeBug(); } addIndexOp(Icode_CLOSURE_EXPR, fnIndex); stackChange(1); } break; case Token.LOCAL_LOAD: { int localIndex = getLocalBlockRef(node); addIndexOp(Token.LOCAL_LOAD, localIndex); stackChange(1); } break; case Token.COMMA: { Node lastChild = node.getLastChild(); while (child != lastChild) { visitExpression(child, 0); addIcode(Icode_POP); stackChange(-1); child = child.getNext(); } // Preserve tail context flag if any visitExpression(child, contextFlags & ECF_TAIL); } break; case Token.USE_STACK: // Indicates that stack was modified externally, // like placed catch object stackChange(1); break; case Token.REF_CALL: case Token.CALL: case Token.NEW: { if (type == Token.NEW) { visitExpression(child, 0); } else { generateCallFunAndThis(child); } int argCount = 0; while ((child = child.getNext()) != null) { visitExpression(child, 0); ++argCount; } int callType = node.getIntProp(Node.SPECIALCALL_PROP, Node.NON_SPECIALCALL); if (callType != Node.NON_SPECIALCALL) { // embed line number and source filename addIndexOp(Icode_CALLSPECIAL, argCount); addUint8(callType); addUint8(type == Token.NEW ? 1 : 0); addUint16(lineNumber & 0xFFFF); } else { // Only use the tail call optimization if we're not in a try // or we're not generating debug info (since the // optimization will confuse the debugger) if (type == Token.CALL && (contextFlags & ECF_TAIL) != 0 && !compilerEnv.isGenerateDebugInfo() && !itsInTryFlag) { type = Icode_TAIL_CALL; } addIndexOp(type, argCount); } // adjust stack if (type == Token.NEW) { // new: f, args -> result stackChange(-argCount); } else { // call: f, thisObj, args -> result // ref_call: f, thisObj, args -> ref stackChange(-1 - argCount); } if (argCount > itsData.itsMaxCalleeArgs) { itsData.itsMaxCalleeArgs = argCount; } } break; case Token.AND: case Token.OR: { visitExpression(child, 0); addIcode(Icode_DUP); stackChange(1); int afterSecondJumpStart = iCodeTop; int jump = (type == Token.AND) ? Token.IFNE : Token.IFEQ; addGotoOp(jump); stackChange(-1); addIcode(Icode_POP); stackChange(-1); child = child.getNext(); // Preserve tail context flag if any visitExpression(child, contextFlags & ECF_TAIL); resolveForwardGoto(afterSecondJumpStart); } break; case Token.HOOK: { Node ifThen = child.getNext(); Node ifElse = ifThen.getNext(); visitExpression(child, 0); int elseJumpStart = iCodeTop; addGotoOp(Token.IFNE); stackChange(-1); // Preserve tail context flag if any visitExpression(ifThen, contextFlags & ECF_TAIL); int afterElseJumpStart = iCodeTop; addGotoOp(Token.GOTO); resolveForwardGoto(elseJumpStart); stackDepth = savedStackDepth; // Preserve tail context flag if any visitExpression(ifElse, contextFlags & ECF_TAIL); resolveForwardGoto(afterElseJumpStart); } break; case Token.GETPROP: case Token.GETPROPNOWARN: visitExpression(child, 0); child = child.getNext(); addStringOp(type, child.getString()); break; case Token.GETELEM: case Token.DELPROP: case Token.BITAND: case Token.BITOR: case Token.BITXOR: case Token.LSH: case Token.RSH: case Token.URSH: case Token.ADD: case Token.SUB: case Token.MOD: case Token.DIV: case Token.MUL: case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: case Token.IN: case Token.INSTANCEOF: case Token.LE: case Token.LT: case Token.GE: case Token.GT: visitExpression(child, 0); child = child.getNext(); visitExpression(child, 0); addToken(type); stackChange(-1); break; case Token.POS: case Token.NEG: case Token.NOT: case Token.BITNOT: case Token.TYPEOF: case Token.VOID: visitExpression(child, 0); if (type == Token.VOID) { addIcode(Icode_POP); addIcode(Icode_UNDEF); } else { addToken(type); } break; case Token.GET_REF: case Token.DEL_REF: visitExpression(child, 0); addToken(type); break; case Token.SETPROP: case Token.SETPROP_OP: { visitExpression(child, 0); child = child.getNext(); String property = child.getString(); child = child.getNext(); if (type == Token.SETPROP_OP) { addIcode(Icode_DUP); stackChange(1); addStringOp(Token.GETPROP, property); // Compensate for the following USE_STACK stackChange(-1); } visitExpression(child, 0); addStringOp(Token.SETPROP, property); stackChange(-1); } break; case Token.SETELEM: case Token.SETELEM_OP: visitExpression(child, 0); child = child.getNext(); visitExpression(child, 0); child = child.getNext(); if (type == Token.SETELEM_OP) { addIcode(Icode_DUP2); stackChange(2); addToken(Token.GETELEM); stackChange(-1); // Compensate for the following USE_STACK stackChange(-1); } visitExpression(child, 0); addToken(Token.SETELEM); stackChange(-2); break; case Token.SET_REF: case Token.SET_REF_OP: visitExpression(child, 0); child = child.getNext(); if (type == Token.SET_REF_OP) { addIcode(Icode_DUP); stackChange(1); addToken(Token.GET_REF); // Compensate for the following USE_STACK stackChange(-1); } visitExpression(child, 0); addToken(Token.SET_REF); stackChange(-1); break; case Token.SETNAME: { String name = child.getString(); visitExpression(child, 0); child = child.getNext(); visitExpression(child, 0); addStringOp(Token.SETNAME, name); stackChange(-1); } break; case Token.SETCONST: { String name = child.getString(); visitExpression(child, 0); child = child.getNext(); visitExpression(child, 0); addStringOp(Icode_SETCONST, name); stackChange(-1); } break; case Token.TYPEOFNAME: { int index = -1; // use typeofname if an activation frame exists // since the vars all exist there instead of in jregs if (itsInFunctionFlag && !itsData.itsNeedsActivation) index = scriptOrFn.getIndexForNameNode(node); if (index == -1) { addStringOp(Icode_TYPEOFNAME, node.getString()); stackChange(1); } else { addVarOp(Token.GETVAR, index); stackChange(1); addToken(Token.TYPEOF); } } break; case Token.BINDNAME: case Token.NAME: case Token.STRING: addStringOp(type, node.getString()); stackChange(1); break; case Token.INC: case Token.DEC: visitIncDec(node, child); break; case Token.NUMBER: { double num = node.getDouble(); int inum = (int)num; if (inum == num) { if (inum == 0) { addIcode(Icode_ZERO); // Check for negative zero if (1.0 / num < 0.0) { addToken(Token.NEG); } } else if (inum == 1) { addIcode(Icode_ONE); } else if ((short)inum == inum) { addIcode(Icode_SHORTNUMBER); // write short as uin16 bit pattern addUint16(inum & 0xFFFF); } else { addIcode(Icode_INTNUMBER); addInt(inum); } } else { int index = getDoubleIndex(num); addIndexOp(Token.NUMBER, index); } stackChange(1); } break; case Token.GETVAR: { if (itsData.itsNeedsActivation) Kit.codeBug(); int index = scriptOrFn.getIndexForNameNode(node); addVarOp(Token.GETVAR, index); stackChange(1); } break; case Token.SETVAR: { if (itsData.itsNeedsActivation) Kit.codeBug(); int index = scriptOrFn.getIndexForNameNode(child); child = child.getNext(); visitExpression(child, 0); addVarOp(Token.SETVAR, index); } break; case Token.SETCONSTVAR: { if (itsData.itsNeedsActivation) Kit.codeBug(); int index = scriptOrFn.getIndexForNameNode(child); child = child.getNext(); visitExpression(child, 0); addVarOp(Token.SETCONSTVAR, index); } break; case Token.NULL: case Token.THIS: case Token.THISFN: case Token.FALSE: case Token.TRUE: addToken(type); stackChange(1); break; case Token.ENUM_NEXT: case Token.ENUM_ID: addIndexOp(type, getLocalBlockRef(node)); stackChange(1); break; case Token.REGEXP: { int index = node.getExistingIntProp(Node.REGEXP_PROP); addIndexOp(Token.REGEXP, index); stackChange(1); } break; case Token.ARRAYLIT: case Token.OBJECTLIT: visitLiteral(node, child); break; case Token.ARRAYCOMP: visitArrayComprehension(node, child, child.getNext()); break; case Token.REF_SPECIAL: visitExpression(child, 0); addStringOp(type, (String)node.getProp(Node.NAME_PROP)); break; case Token.REF_MEMBER: case Token.REF_NS_MEMBER: case Token.REF_NAME: case Token.REF_NS_NAME: { int memberTypeFlags = node.getIntProp(Node.MEMBER_TYPE_PROP, 0); // generate possible target, possible namespace and member int childCount = 0; do { visitExpression(child, 0); ++childCount; child = child.getNext(); } while (child != null); addIndexOp(type, memberTypeFlags); stackChange(1 - childCount); } break; case Token.DOTQUERY: { int queryPC; updateLineNumber(node); visitExpression(child, 0); addIcode(Icode_ENTERDQ); stackChange(-1); queryPC = iCodeTop; visitExpression(child.getNext(), 0); addBackwardGoto(Icode_LEAVEDQ, queryPC); } break; case Token.DEFAULTNAMESPACE : case Token.ESCXMLATTR : case Token.ESCXMLTEXT : visitExpression(child, 0); addToken(type); break; case Token.YIELD: if (child != null) { visitExpression(child, 0); } else { addIcode(Icode_UNDEF); stackChange(1); } addToken(Token.YIELD); addUint16(node.getLineno() & 0xFFFF); break; case Token.WITHEXPR: { Node enterWith = node.getFirstChild(); Node with = enterWith.getNext(); visitExpression(enterWith.getFirstChild(), 0); addToken(Token.ENTERWITH); stackChange(-1); visitExpression(with.getFirstChild(), 0); addToken(Token.LEAVEWITH); break; } default: throw badTree(node); } if (savedStackDepth + 1 != stackDepth) { Kit.codeBug(); } } private void generateCallFunAndThis(Node left) { // Generate code to place on stack function and thisObj int type = left.getType(); switch (type) { case Token.NAME: { String name = left.getString(); // stack: ... -> ... function thisObj addStringOp(Icode_NAME_AND_THIS, name); stackChange(2); break; } case Token.GETPROP: case Token.GETELEM: { Node target = left.getFirstChild(); visitExpression(target, 0); Node id = target.getNext(); if (type == Token.GETPROP) { String property = id.getString(); // stack: ... target -> ... function thisObj addStringOp(Icode_PROP_AND_THIS, property); stackChange(1); } else { visitExpression(id, 0); // stack: ... target id -> ... function thisObj addIcode(Icode_ELEM_AND_THIS); } break; } default: // Including Token.GETVAR visitExpression(left, 0); // stack: ... value -> ... function thisObj addIcode(Icode_VALUE_AND_THIS); stackChange(1); break; } } private void visitIncDec(Node node, Node child) { int incrDecrMask = node.getExistingIntProp(Node.INCRDECR_PROP); int childType = child.getType(); switch (childType) { case Token.GETVAR : { if (itsData.itsNeedsActivation) Kit.codeBug(); int i = scriptOrFn.getIndexForNameNode(child); addVarOp(Icode_VAR_INC_DEC, i); addUint8(incrDecrMask); stackChange(1); break; } case Token.NAME : { String name = child.getString(); addStringOp(Icode_NAME_INC_DEC, name); addUint8(incrDecrMask); stackChange(1); break; } case Token.GETPROP : { Node object = child.getFirstChild(); visitExpression(object, 0); String property = object.getNext().getString(); addStringOp(Icode_PROP_INC_DEC, property); addUint8(incrDecrMask); break; } case Token.GETELEM : { Node object = child.getFirstChild(); visitExpression(object, 0); Node index = object.getNext(); visitExpression(index, 0); addIcode(Icode_ELEM_INC_DEC); addUint8(incrDecrMask); stackChange(-1); break; } case Token.GET_REF : { Node ref = child.getFirstChild(); visitExpression(ref, 0); addIcode(Icode_REF_INC_DEC); addUint8(incrDecrMask); break; } default : { throw badTree(node); } } } private void visitLiteral(Node node, Node child) { int type = node.getType(); int count; Object[] propertyIds = null; if (type == Token.ARRAYLIT) { count = 0; for (Node n = child; n != null; n = n.getNext()) { ++count; } } else if (type == Token.OBJECTLIT) { propertyIds = (Object[])node.getProp(Node.OBJECT_IDS_PROP); count = propertyIds.length; } else { throw badTree(node); } addIndexOp(Icode_LITERAL_NEW, count); stackChange(2); while (child != null) { int childType = child.getType(); if (childType == Token.GET) { visitExpression(child.getFirstChild(), 0); addIcode(Icode_LITERAL_GETTER); } else if (childType == Token.SET) { visitExpression(child.getFirstChild(), 0); addIcode(Icode_LITERAL_SETTER); } else { visitExpression(child, 0); addIcode(Icode_LITERAL_SET); } stackChange(-1); child = child.getNext(); } if (type == Token.ARRAYLIT) { int[] skipIndexes = (int[])node.getProp(Node.SKIP_INDEXES_PROP); if (skipIndexes == null) { addToken(Token.ARRAYLIT); } else { int index = literalIds.size(); literalIds.add(skipIndexes); addIndexOp(Icode_SPARE_ARRAYLIT, index); } } else { int index = literalIds.size(); literalIds.add(propertyIds); addIndexOp(Token.OBJECTLIT, index); } stackChange(-1); } private void visitArrayComprehension(Node node, Node initStmt, Node expr) { // A bit of a hack: array comprehensions are implemented using // statement nodes for the iteration, yet they appear in an // expression context. So we pass the current stack depth to // visitStatement so it can check that the depth is not altered // by statements. visitStatement(initStmt, stackDepth); visitExpression(expr, 0); } private int getLocalBlockRef(Node node) { Node localBlock = (Node)node.getProp(Node.LOCAL_BLOCK_PROP); return localBlock.getExistingIntProp(Node.LOCAL_PROP); } private int getTargetLabel(Node target) { int label = target.labelId(); if (label != -1) { return label; } label = labelTableTop; if (labelTable == null || label == labelTable.length) { if (labelTable == null) { labelTable = new int[MIN_LABEL_TABLE_SIZE]; }else { int[] tmp = new int[labelTable.length * 2]; System.arraycopy(labelTable, 0, tmp, 0, label); labelTable = tmp; } } labelTableTop = label + 1; labelTable[label] = -1; target.labelId(label); return label; } private void markTargetLabel(Node target) { int label = getTargetLabel(target); if (labelTable[label] != -1) { // Can mark label only once Kit.codeBug(); } labelTable[label] = iCodeTop; } private void addGoto(Node target, int gotoOp) { int label = getTargetLabel(target); if (!(label < labelTableTop)) Kit.codeBug(); int targetPC = labelTable[label]; if (targetPC != -1) { addBackwardGoto(gotoOp, targetPC); } else { int gotoPC = iCodeTop; addGotoOp(gotoOp); int top = fixupTableTop; if (fixupTable == null || top == fixupTable.length) { if (fixupTable == null) { fixupTable = new long[MIN_FIXUP_TABLE_SIZE]; } else { long[] tmp = new long[fixupTable.length * 2]; System.arraycopy(fixupTable, 0, tmp, 0, top); fixupTable = tmp; } } fixupTableTop = top + 1; fixupTable[top] = ((long)label << 32) | gotoPC; } } private void fixLabelGotos() { for (int i = 0; i < fixupTableTop; i++) { long fixup = fixupTable[i]; int label = (int)(fixup >> 32); int jumpSource = (int)fixup; int pc = labelTable[label]; if (pc == -1) { // Unlocated label throw Kit.codeBug(); } resolveGoto(jumpSource, pc); } fixupTableTop = 0; } private void addBackwardGoto(int gotoOp, int jumpPC) { int fromPC = iCodeTop; // Ensure that this is a jump backward if (fromPC <= jumpPC) throw Kit.codeBug(); addGotoOp(gotoOp); resolveGoto(fromPC, jumpPC); } private void resolveForwardGoto(int fromPC) { // Ensure that forward jump skips at least self bytecode if (iCodeTop < fromPC + 3) throw Kit.codeBug(); resolveGoto(fromPC, iCodeTop); } private void resolveGoto(int fromPC, int jumpPC) { int offset = jumpPC - fromPC; // Ensure that jumps do not overlap if (0 <= offset && offset <= 2) throw Kit.codeBug(); int offsetSite = fromPC + 1; if (offset != (short)offset) { if (itsData.longJumps == null) { itsData.longJumps = new UintMap(); } itsData.longJumps.put(offsetSite, jumpPC); offset = 0; } byte[] array = itsData.itsICode; array[offsetSite] = (byte)(offset >> 8); array[offsetSite + 1] = (byte)offset; } private void addToken(int token) { if (!Icode.validTokenCode(token)) throw Kit.codeBug(); addUint8(token); } private void addIcode(int icode) { if (!Icode.validIcode(icode)) throw Kit.codeBug(); // Write negative icode as uint8 bits addUint8(icode & 0xFF); } private void addUint8(int value) { if ((value & ~0xFF) != 0) throw Kit.codeBug(); byte[] array = itsData.itsICode; int top = iCodeTop; if (top == array.length) { array = increaseICodeCapacity(1); } array[top] = (byte)value; iCodeTop = top + 1; } private void addUint16(int value) { if ((value & ~0xFFFF) != 0) throw Kit.codeBug(); byte[] array = itsData.itsICode; int top = iCodeTop; if (top + 2 > array.length) { array = increaseICodeCapacity(2); } array[top] = (byte)(value >>> 8); array[top + 1] = (byte)value; iCodeTop = top + 2; } private void addInt(int i) { byte[] array = itsData.itsICode; int top = iCodeTop; if (top + 4 > array.length) { array = increaseICodeCapacity(4); } array[top] = (byte)(i >>> 24); array[top + 1] = (byte)(i >>> 16); array[top + 2] = (byte)(i >>> 8); array[top + 3] = (byte)i; iCodeTop = top + 4; } private int getDoubleIndex(double num) { int index = doubleTableTop; if (index == 0) { itsData.itsDoubleTable = new double[64]; } else if (itsData.itsDoubleTable.length == index) { double[] na = new double[index * 2]; System.arraycopy(itsData.itsDoubleTable, 0, na, 0, index); itsData.itsDoubleTable = na; } itsData.itsDoubleTable[index] = num; doubleTableTop = index + 1; return index; } private void addGotoOp(int gotoOp) { byte[] array = itsData.itsICode; int top = iCodeTop; if (top + 3 > array.length) { array = increaseICodeCapacity(3); } array[top] = (byte)gotoOp; // Offset would written later iCodeTop = top + 1 + 2; } private void addVarOp(int op, int varIndex) { switch (op) { case Token.SETCONSTVAR: if (varIndex < 128) { addIcode(Icode_SETCONSTVAR1); addUint8(varIndex); return; } addIndexOp(Icode_SETCONSTVAR, varIndex); return; case Token.GETVAR: case Token.SETVAR: if (varIndex < 128) { addIcode(op == Token.GETVAR ? Icode_GETVAR1 : Icode_SETVAR1); addUint8(varIndex); return; } // fallthrough case Icode_VAR_INC_DEC: addIndexOp(op, varIndex); return; } throw Kit.codeBug(); } private void addStringOp(int op, String str) { addStringPrefix(str); if (Icode.validIcode(op)) { addIcode(op); } else { addToken(op); } } private void addIndexOp(int op, int index) { addIndexPrefix(index); if (Icode.validIcode(op)) { addIcode(op); } else { addToken(op); } } private void addStringPrefix(String str) { int index = strings.get(str, -1); if (index == -1) { index = strings.size(); strings.put(str, index); } if (index < 4) { addIcode(Icode_REG_STR_C0 - index); } else if (index <= 0xFF) { addIcode(Icode_REG_STR1); addUint8(index); } else if (index <= 0xFFFF) { addIcode(Icode_REG_STR2); addUint16(index); } else { addIcode(Icode_REG_STR4); addInt(index); } } private void addIndexPrefix(int index) { if (index < 0) Kit.codeBug(); if (index < 6) { addIcode(Icode_REG_IND_C0 - index); } else if (index <= 0xFF) { addIcode(Icode_REG_IND1); addUint8(index); } else if (index <= 0xFFFF) { addIcode(Icode_REG_IND2); addUint16(index); } else { addIcode(Icode_REG_IND4); addInt(index); } } private void addExceptionHandler(int icodeStart, int icodeEnd, int handlerStart, boolean isFinally, int exceptionObjectLocal, int scopeLocal) { int top = exceptionTableTop; int[] table = itsData.itsExceptionTable; if (table == null) { if (top != 0) Kit.codeBug(); table = new int[Interpreter.EXCEPTION_SLOT_SIZE * 2]; itsData.itsExceptionTable = table; } else if (table.length == top) { table = new int[table.length * 2]; System.arraycopy(itsData.itsExceptionTable, 0, table, 0, top); itsData.itsExceptionTable = table; } table[top + Interpreter.EXCEPTION_TRY_START_SLOT] = icodeStart; table[top + Interpreter.EXCEPTION_TRY_END_SLOT] = icodeEnd; table[top + Interpreter.EXCEPTION_HANDLER_SLOT] = handlerStart; table[top + Interpreter.EXCEPTION_TYPE_SLOT] = isFinally ? 1 : 0; table[top + Interpreter.EXCEPTION_LOCAL_SLOT] = exceptionObjectLocal; table[top + Interpreter.EXCEPTION_SCOPE_SLOT] = scopeLocal; exceptionTableTop = top + Interpreter.EXCEPTION_SLOT_SIZE; } private byte[] increaseICodeCapacity(int extraSize) { int capacity = itsData.itsICode.length; int top = iCodeTop; if (top + extraSize <= capacity) throw Kit.codeBug(); capacity *= 2; if (top + extraSize > capacity) { capacity = top + extraSize; } byte[] array = new byte[capacity]; System.arraycopy(itsData.itsICode, 0, array, 0, top); itsData.itsICode = array; return array; } private void stackChange(int change) { if (change <= 0) { stackDepth += change; } else { int newDepth = stackDepth + change; if (newDepth > itsData.itsMaxStack) { itsData.itsMaxStack = newDepth; } stackDepth = newDepth; } } private int allocLocal() { int localSlot = localTop; ++localTop; if (localTop > itsData.itsMaxLocals) { itsData.itsMaxLocals = localTop; } return localSlot; } private void releaseLocal(int localSlot) { --localTop; if (localSlot != localTop) Kit.codeBug(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/Script.java0000644000175000017500000000523211314263504032214 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; /** * All compiled scripts implement this interface. *

* This class encapsulates script execution relative to an * object scope. * @since 1.3 * @author Norris Boyd */ public interface Script { /** * Execute the script. *

* The script is executed in a particular runtime Context, which * must be associated with the current thread. * The script is executed relative to a scope--definitions and * uses of global top-level variables and functions will access * properties of the scope object. For compliant ECMA * programs, the scope must be an object that has been initialized * as a global object using Context.initStandardObjects. *

* * @param cx the Context associated with the current thread * @param scope the scope to execute relative to * @return the result of executing the script * @see org.mozilla.javascript.Context#initStandardObjects() */ public Object exec(Context cx, Scriptable scope); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/Decompiler.java0000644000175000017500000006756511314263504033054 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Mike Ang * Igor Bukanov * Bob Jervis * Mike McCabe * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import org.mozilla.javascript.ast.FunctionNode; /** * The following class save decompilation information about the source. * Source information is returned from the parser as a String * associated with function nodes and with the toplevel script. When * saved in the constant pool of a class, this string will be UTF-8 * encoded, and token values will occupy a single byte. * Source is saved (mostly) as token numbers. The tokens saved pretty * much correspond to the token stream of a 'canonical' representation * of the input program, as directed by the parser. (There were a few * cases where tokens could have been left out where decompiler could * easily reconstruct them, but I left them in for clarity). (I also * looked adding source collection to TokenStream instead, where I * could have limited the changes to a few lines in getToken... but * this wouldn't have saved any space in the resulting source * representation, and would have meant that I'd have to duplicate * parser logic in the decompiler to disambiguate situations where * newlines are important.) The function decompile expands the * tokens back into their string representations, using simple * lookahead to correct spacing and indentation. * * Assignments are saved as two-token pairs (Token.ASSIGN, op). Number tokens * are stored inline, as a NUMBER token, a character representing the type, and * either 1 or 4 characters representing the bit-encoding of the number. String * types NAME, STRING and OBJECT are currently stored as a token type, * followed by a character giving the length of the string (assumed to * be less than 2^16), followed by the characters of the string * inlined into the source string. Changing this to some reference to * to the string in the compiled class' constant pool would probably * save a lot of space... but would require some method of deriving * the final constant pool entry from information available at parse * time. */ public class Decompiler { /** * Flag to indicate that the decompilation should omit the * function header and trailing brace. */ public static final int ONLY_BODY_FLAG = 1 << 0; /** * Flag to indicate that the decompilation generates toSource result. */ public static final int TO_SOURCE_FLAG = 1 << 1; /** * Decompilation property to specify initial ident value. */ public static final int INITIAL_INDENT_PROP = 1; /** * Decompilation property to specify default identation offset. */ public static final int INDENT_GAP_PROP = 2; /** * Decompilation property to specify identation offset for case labels. */ public static final int CASE_GAP_PROP = 3; // Marker to denote the last RC of function so it can be distinguished from // the last RC of object literals in case of function expressions private static final int FUNCTION_END = Token.LAST_TOKEN + 1; String getEncodedSource() { return sourceToString(0); } int getCurrentOffset() { return sourceTop; } int markFunctionStart(int functionType) { int savedOffset = getCurrentOffset(); addToken(Token.FUNCTION); append((char)functionType); return savedOffset; } int markFunctionEnd(int functionStart) { int offset = getCurrentOffset(); append((char)FUNCTION_END); return offset; } void addToken(int token) { if (!(0 <= token && token <= Token.LAST_TOKEN)) throw new IllegalArgumentException(); append((char)token); } void addEOL(int token) { if (!(0 <= token && token <= Token.LAST_TOKEN)) throw new IllegalArgumentException(); append((char)token); append((char)Token.EOL); } void addName(String str) { addToken(Token.NAME); appendString(str); } void addString(String str) { addToken(Token.STRING); appendString(str); } void addRegexp(String regexp, String flags) { addToken(Token.REGEXP); appendString('/' + regexp + '/' + flags); } void addNumber(double n) { addToken(Token.NUMBER); /* encode the number in the source stream. * Save as NUMBER type (char | char char char char) * where type is * 'D' - double, 'S' - short, 'J' - long. * We need to retain float vs. integer type info to keep the * behavior of liveconnect type-guessing the same after * decompilation. (Liveconnect tries to present 1.0 to Java * as a float/double) * OPT: This is no longer true. We could compress the format. * This may not be the most space-efficient encoding; * the chars created below may take up to 3 bytes in * constant pool UTF-8 encoding, so a Double could take * up to 12 bytes. */ long lbits = (long)n; if (lbits != n) { // if it's floating point, save as a Double bit pattern. // (12/15/97 our scanner only returns Double for f.p.) lbits = Double.doubleToLongBits(n); append('D'); append((char)(lbits >> 48)); append((char)(lbits >> 32)); append((char)(lbits >> 16)); append((char)lbits); } else { // we can ignore negative values, bc they're already prefixed // by NEG if (lbits < 0) Kit.codeBug(); // will it fit in a char? // this gives a short encoding for integer values up to 2^16. if (lbits <= Character.MAX_VALUE) { append('S'); append((char)lbits); } else { // Integral, but won't fit in a char. Store as a long. append('J'); append((char)(lbits >> 48)); append((char)(lbits >> 32)); append((char)(lbits >> 16)); append((char)lbits); } } } private void appendString(String str) { int L = str.length(); int lengthEncodingSize = 1; if (L >= 0x8000) { lengthEncodingSize = 2; } int nextTop = sourceTop + lengthEncodingSize + L; if (nextTop > sourceBuffer.length) { increaseSourceCapacity(nextTop); } if (L >= 0x8000) { // Use 2 chars to encode strings exceeding 32K, were the highest // bit in the first char indicates presence of the next byte sourceBuffer[sourceTop] = (char)(0x8000 | (L >>> 16)); ++sourceTop; } sourceBuffer[sourceTop] = (char)L; ++sourceTop; str.getChars(0, L, sourceBuffer, sourceTop); sourceTop = nextTop; } private void append(char c) { if (sourceTop == sourceBuffer.length) { increaseSourceCapacity(sourceTop + 1); } sourceBuffer[sourceTop] = c; ++sourceTop; } private void increaseSourceCapacity(int minimalCapacity) { // Call this only when capacity increase is must if (minimalCapacity <= sourceBuffer.length) Kit.codeBug(); int newCapacity = sourceBuffer.length * 2; if (newCapacity < minimalCapacity) { newCapacity = minimalCapacity; } char[] tmp = new char[newCapacity]; System.arraycopy(sourceBuffer, 0, tmp, 0, sourceTop); sourceBuffer = tmp; } private String sourceToString(int offset) { if (offset < 0 || sourceTop < offset) Kit.codeBug(); return new String(sourceBuffer, offset, sourceTop - offset); } /** * Decompile the source information associated with this js * function/script back into a string. For the most part, this * just means translating tokens back to their string * representations; there's a little bit of lookahead logic to * decide the proper spacing/indentation. Most of the work in * mapping the original source to the prettyprinted decompiled * version is done by the parser. * * @param source encoded source tree presentation * * @param flags flags to select output format * * @param properties indentation properties * */ public static String decompile(String source, int flags, UintMap properties) { int length = source.length(); if (length == 0) { return ""; } int indent = properties.getInt(INITIAL_INDENT_PROP, 0); if (indent < 0) throw new IllegalArgumentException(); int indentGap = properties.getInt(INDENT_GAP_PROP, 4); if (indentGap < 0) throw new IllegalArgumentException(); int caseGap = properties.getInt(CASE_GAP_PROP, 2); if (caseGap < 0) throw new IllegalArgumentException(); StringBuffer result = new StringBuffer(); boolean justFunctionBody = (0 != (flags & Decompiler.ONLY_BODY_FLAG)); boolean toSource = (0 != (flags & Decompiler.TO_SOURCE_FLAG)); // Spew tokens in source, for debugging. // as TYPE number char if (printSource) { System.err.println("length:" + length); for (int i = 0; i < length; ++i) { // Note that tokenToName will fail unless Context.printTrees // is true. String tokenname = null; if (Token.printNames) { tokenname = Token.name(source.charAt(i)); } if (tokenname == null) { tokenname = "---"; } String pad = tokenname.length() > 7 ? "\t" : "\t\t"; System.err.println (tokenname + pad + (int)source.charAt(i) + "\t'" + ScriptRuntime.escapeString (source.substring(i, i+1)) + "'"); } System.err.println(); } int braceNesting = 0; boolean afterFirstEOL = false; int i = 0; int topFunctionType; if (source.charAt(i) == Token.SCRIPT) { ++i; topFunctionType = -1; } else { topFunctionType = source.charAt(i + 1); } if (!toSource) { // add an initial newline to exactly match js. result.append('\n'); for (int j = 0; j < indent; j++) result.append(' '); } else { if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) { result.append('('); } } while (i < length) { switch(source.charAt(i)) { case Token.GET: case Token.SET: result.append(source.charAt(i) == Token.GET ? "get " : "set "); ++i; i = printSourceString(source, i + 1, false, result); // Now increment one more to get past the FUNCTION token ++i; break; case Token.NAME: case Token.REGEXP: // re-wrapped in '/'s in parser... i = printSourceString(source, i + 1, false, result); continue; case Token.STRING: i = printSourceString(source, i + 1, true, result); continue; case Token.NUMBER: i = printSourceNumber(source, i + 1, result); continue; case Token.TRUE: result.append("true"); break; case Token.FALSE: result.append("false"); break; case Token.NULL: result.append("null"); break; case Token.THIS: result.append("this"); break; case Token.FUNCTION: ++i; // skip function type result.append("function "); break; case FUNCTION_END: // Do nothing break; case Token.COMMA: result.append(", "); break; case Token.LC: ++braceNesting; if (Token.EOL == getNext(source, length, i)) indent += indentGap; result.append('{'); break; case Token.RC: { --braceNesting; /* don't print the closing RC if it closes the * toplevel function and we're called from * decompileFunctionBody. */ if (justFunctionBody && braceNesting == 0) break; result.append('}'); switch (getNext(source, length, i)) { case Token.EOL: case FUNCTION_END: indent -= indentGap; break; case Token.WHILE: case Token.ELSE: indent -= indentGap; result.append(' '); break; } break; } case Token.LP: result.append('('); break; case Token.RP: result.append(')'); if (Token.LC == getNext(source, length, i)) result.append(' '); break; case Token.LB: result.append('['); break; case Token.RB: result.append(']'); break; case Token.EOL: { if (toSource) break; boolean newLine = true; if (!afterFirstEOL) { afterFirstEOL = true; if (justFunctionBody) { /* throw away just added 'function name(...) {' * and restore the original indent */ result.setLength(0); indent -= indentGap; newLine = false; } } if (newLine) { result.append('\n'); } /* add indent if any tokens remain, * less setback if next token is * a label, case or default. */ if (i + 1 < length) { int less = 0; int nextToken = source.charAt(i + 1); if (nextToken == Token.CASE || nextToken == Token.DEFAULT) { less = indentGap - caseGap; } else if (nextToken == Token.RC) { less = indentGap; } /* elaborate check against label... skip past a * following inlined NAME and look for a COLON. */ else if (nextToken == Token.NAME) { int afterName = getSourceStringEnd(source, i + 2); if (source.charAt(afterName) == Token.COLON) less = indentGap; } for (; less < indent; less++) result.append(' '); } break; } case Token.DOT: result.append('.'); break; case Token.NEW: result.append("new "); break; case Token.DELPROP: result.append("delete "); break; case Token.IF: result.append("if "); break; case Token.ELSE: result.append("else "); break; case Token.FOR: result.append("for "); break; case Token.IN: result.append(" in "); break; case Token.WITH: result.append("with "); break; case Token.WHILE: result.append("while "); break; case Token.DO: result.append("do "); break; case Token.TRY: result.append("try "); break; case Token.CATCH: result.append("catch "); break; case Token.FINALLY: result.append("finally "); break; case Token.THROW: result.append("throw "); break; case Token.SWITCH: result.append("switch "); break; case Token.BREAK: result.append("break"); if (Token.NAME == getNext(source, length, i)) result.append(' '); break; case Token.CONTINUE: result.append("continue"); if (Token.NAME == getNext(source, length, i)) result.append(' '); break; case Token.CASE: result.append("case "); break; case Token.DEFAULT: result.append("default"); break; case Token.RETURN: result.append("return"); if (Token.SEMI != getNext(source, length, i)) result.append(' '); break; case Token.VAR: result.append("var "); break; case Token.LET: result.append("let "); break; case Token.SEMI: result.append(';'); if (Token.EOL != getNext(source, length, i)) { // separators in FOR result.append(' '); } break; case Token.ASSIGN: result.append(" = "); break; case Token.ASSIGN_ADD: result.append(" += "); break; case Token.ASSIGN_SUB: result.append(" -= "); break; case Token.ASSIGN_MUL: result.append(" *= "); break; case Token.ASSIGN_DIV: result.append(" /= "); break; case Token.ASSIGN_MOD: result.append(" %= "); break; case Token.ASSIGN_BITOR: result.append(" |= "); break; case Token.ASSIGN_BITXOR: result.append(" ^= "); break; case Token.ASSIGN_BITAND: result.append(" &= "); break; case Token.ASSIGN_LSH: result.append(" <<= "); break; case Token.ASSIGN_RSH: result.append(" >>= "); break; case Token.ASSIGN_URSH: result.append(" >>>= "); break; case Token.HOOK: result.append(" ? "); break; case Token.OBJECTLIT: // pun OBJECTLIT to mean colon in objlit property // initialization. // This needs to be distinct from COLON in the general case // to distinguish from the colon in a ternary... which needs // different spacing. result.append(':'); break; case Token.COLON: if (Token.EOL == getNext(source, length, i)) // it's the end of a label result.append(':'); else // it's the middle part of a ternary result.append(" : "); break; case Token.OR: result.append(" || "); break; case Token.AND: result.append(" && "); break; case Token.BITOR: result.append(" | "); break; case Token.BITXOR: result.append(" ^ "); break; case Token.BITAND: result.append(" & "); break; case Token.SHEQ: result.append(" === "); break; case Token.SHNE: result.append(" !== "); break; case Token.EQ: result.append(" == "); break; case Token.NE: result.append(" != "); break; case Token.LE: result.append(" <= "); break; case Token.LT: result.append(" < "); break; case Token.GE: result.append(" >= "); break; case Token.GT: result.append(" > "); break; case Token.INSTANCEOF: result.append(" instanceof "); break; case Token.LSH: result.append(" << "); break; case Token.RSH: result.append(" >> "); break; case Token.URSH: result.append(" >>> "); break; case Token.TYPEOF: result.append("typeof "); break; case Token.VOID: result.append("void "); break; case Token.CONST: result.append("const "); break; case Token.YIELD: result.append("yield "); break; case Token.NOT: result.append('!'); break; case Token.BITNOT: result.append('~'); break; case Token.POS: result.append('+'); break; case Token.NEG: result.append('-'); break; case Token.INC: result.append("++"); break; case Token.DEC: result.append("--"); break; case Token.ADD: result.append(" + "); break; case Token.SUB: result.append(" - "); break; case Token.MUL: result.append(" * "); break; case Token.DIV: result.append(" / "); break; case Token.MOD: result.append(" % "); break; case Token.COLONCOLON: result.append("::"); break; case Token.DOTDOT: result.append(".."); break; case Token.DOTQUERY: result.append(".("); break; case Token.XMLATTR: result.append('@'); break; default: // If we don't know how to decompile it, raise an exception. throw new RuntimeException("Token: " + Token.name(source.charAt(i))); } ++i; } if (!toSource) { // add that trailing newline if it's an outermost function. if (!justFunctionBody) result.append('\n'); } else { if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) { result.append(')'); } } return result.toString(); } private static int getNext(String source, int length, int i) { return (i + 1 < length) ? source.charAt(i + 1) : Token.EOF; } private static int getSourceStringEnd(String source, int offset) { return printSourceString(source, offset, false, null); } private static int printSourceString(String source, int offset, boolean asQuotedString, StringBuffer sb) { int length = source.charAt(offset); ++offset; if ((0x8000 & length) != 0) { length = ((0x7FFF & length) << 16) | source.charAt(offset); ++offset; } if (sb != null) { String str = source.substring(offset, offset + length); if (!asQuotedString) { sb.append(str); } else { sb.append('"'); sb.append(ScriptRuntime.escapeString(str)); sb.append('"'); } } return offset + length; } private static int printSourceNumber(String source, int offset, StringBuffer sb) { double number = 0.0; char type = source.charAt(offset); ++offset; if (type == 'S') { if (sb != null) { int ival = source.charAt(offset); number = ival; } ++offset; } else if (type == 'J' || type == 'D') { if (sb != null) { long lbits; lbits = (long)source.charAt(offset) << 48; lbits |= (long)source.charAt(offset + 1) << 32; lbits |= (long)source.charAt(offset + 2) << 16; lbits |= source.charAt(offset + 3); if (type == 'J') { number = lbits; } else { number = Double.longBitsToDouble(lbits); } } offset += 4; } else { // Bad source throw new RuntimeException(); } if (sb != null) { sb.append(ScriptRuntime.numberToString(number, 10)); } return offset; } private char[] sourceBuffer = new char[128]; // Per script/function source buffer top: parent source does not include a // nested functions source and uses function index as a reference instead. private int sourceTop; // whether to do a debug print of the source information, when decompiling. private static final boolean printSource = false; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ClassShutter.java0000644000175000017500000000740111314263504033374 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; /** Embeddings that wish to filter Java classes that are visible to scripts through the LiveConnect, should implement this interface. @see Context#setClassShutter(ClassShutter) @since 1.5 Release 4 @author Norris Boyd */ public interface ClassShutter { /** * Return true iff the Java class with the given name should be exposed * to scripts. *

* An embedding may filter which Java classes are exposed through * LiveConnect to JavaScript scripts. *

* Due to the fact that there is no package reflection in Java, * this method will also be called with package names. There * is no way for Rhino to tell if "Packages.a.b" is a package name * or a class that doesn't exist. What Rhino does is attempt * to load each segment of "Packages.a.b.c": It first attempts to * load class "a", then attempts to load class "a.b", then * finally attempts to load class "a.b.c". On a Rhino installation * without any ClassShutter set, and without any of the * above classes, the expression "Packages.a.b.c" will result in * a [JavaPackage a.b.c] and not an error. *

* With ClassShutter supplied, Rhino will first call * visibleToScripts before attempting to look up the class name. If * visibleToScripts returns false, the class name lookup is not * performed and subsequent Rhino execution assumes the class is * not present. So for "java.lang.System.out.println" the lookup * of "java.lang.System" is skipped and thus Rhino assumes that * "java.lang.System" doesn't exist. So then for "java.lang.System.out", * Rhino attempts to load the class "java.lang.System.out" because * it assumes that "java.lang.System" is a package name. *

* @param fullClassName the full name of the class (including the package * name, with '.' as a delimiter). For example the * standard string class is "java.lang.String" * @return whether or not to reveal this class to scripts */ public boolean visibleToScripts(String fullClassName); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/Evaluator.java0000644000175000017500000001077311314263504032720 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import org.mozilla.javascript.ast.ScriptNode; import java.util.List; /** * Abstraction of evaluation, which can be implemented either by an * interpreter or compiler. */ public interface Evaluator { /** * Compile the script or function from intermediate representation * tree into an executable form. * * @param compilerEnv Compiler environment * @param tree parse tree * @param encodedSource encoding of the source code for decompilation * @param returnFunction if true, compiling a function * @return an opaque object that can be passed to either * createFunctionObject or createScriptObject, depending on the * value of returnFunction */ public Object compile(CompilerEnvirons compilerEnv, ScriptNode tree, String encodedSource, boolean returnFunction); /** * Create a function object. * * @param cx Current context * @param scope scope of the function * @param bytecode opaque object returned by compile * @param staticSecurityDomain security domain * @return Function object that can be called */ public Function createFunctionObject(Context cx, Scriptable scope, Object bytecode, Object staticSecurityDomain); /** * Create a script object. * * @param bytecode opaque object returned by compile * @param staticSecurityDomain security domain * @return Script object that can be evaluated */ public Script createScriptObject(Object bytecode, Object staticSecurityDomain); /** * Capture stack information from the given exception. * @param ex an exception thrown during execution */ public void captureStackInfo(RhinoException ex); /** * Get the source position information by examining the stack. * @param cx Context * @param linep Array object of length >= 1; getSourcePositionFromStack * will assign the line number to linep[0]. * @return the name of the file or other source container */ public String getSourcePositionFromStack(Context cx, int[] linep); /** * Given a native stack trace, patch it with script-specific source * and line information * @param ex exception * @param nativeStackTrace the native stack trace * @return patched stack trace */ public String getPatchedStack(RhinoException ex, String nativeStackTrace); /** * Get the script stack for the given exception * @param ex exception from execution * @return list of strings for the stack trace */ public List getScriptStack(RhinoException ex); /** * Works like {@link #getScriptStack(RhinoException)} but structured. */ public List> buildScriptStack(RhinoException ex); /** * Mark the given script to indicate it was created by a call to * eval() or to a Function constructor. * @param script script to mark as from eval */ public void setEvalScriptFlag(Script script); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ObjToIntMap.java0000644000175000017500000005143111314263504033100 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.io.Serializable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Map to associate objects to integers. * The map does not synchronize any of its operation, so either use * it from a single thread or do own synchronization or perform all mutation * operations on one thread before passing the map to others * * @author Igor Bukanov * */ public class ObjToIntMap implements Serializable { static final long serialVersionUID = -1542220580748809402L; // Map implementation via hashtable, // follows "The Art of Computer Programming" by Donald E. Knuth // ObjToIntMap is a copy cat of ObjToIntMap with API adjusted to object keys public static class Iterator { Iterator(ObjToIntMap master) { this.master = master; } final void init(Object[] keys, int[] values, int keyCount) { this.keys = keys; this.values = values; this.cursor = -1; this.remaining = keyCount; } public void start() { master.initIterator(this); next(); } public boolean done() { return remaining < 0; } public void next() { if (remaining == -1) Kit.codeBug(); if (remaining == 0) { remaining = -1; cursor = -1; }else { for (++cursor; ; ++cursor) { Object key = keys[cursor]; if (key != null && key != DELETED) { --remaining; break; } } } } public Object getKey() { Object key = keys[cursor]; if (key == UniqueTag.NULL_VALUE) { key = null; } return key; } public int getValue() { return values[cursor]; } public void setValue(int value) { values[cursor] = value; } ObjToIntMap master; private int cursor; private int remaining; private Object[] keys; private int[] values; } public ObjToIntMap() { this(4); } public ObjToIntMap(int keyCountHint) { if (keyCountHint < 0) Kit.codeBug(); // Table grow when number of stored keys >= 3/4 of max capacity int minimalCapacity = keyCountHint * 4 / 3; int i; for (i = 2; (1 << i) < minimalCapacity; ++i) { } power = i; if (check && power < 2) Kit.codeBug(); } public boolean isEmpty() { return keyCount == 0; } public int size() { return keyCount; } public boolean has(Object key) { if (key == null) { key = UniqueTag.NULL_VALUE; } return 0 <= findIndex(key); } /** * Get integer value assigned with key. * @return key integer value or defaultValue if key is absent */ public int get(Object key, int defaultValue) { if (key == null) { key = UniqueTag.NULL_VALUE; } int index = findIndex(key); if (0 <= index) { return values[index]; } return defaultValue; } /** * Get integer value assigned with key. * @return key integer value * @throws RuntimeException if key does not exist */ public int getExisting(Object key) { if (key == null) { key = UniqueTag.NULL_VALUE; } int index = findIndex(key); if (0 <= index) { return values[index]; } // Key must exist Kit.codeBug(); return 0; } public void put(Object key, int value) { if (key == null) { key = UniqueTag.NULL_VALUE; } int index = ensureIndex(key); values[index] = value; } /** * If table already contains a key that equals to keyArg, return that key * while setting its value to zero, otherwise add keyArg with 0 value to * the table and return it. */ public Object intern(Object keyArg) { boolean nullKey = false; if (keyArg == null) { nullKey = true; keyArg = UniqueTag.NULL_VALUE; } int index = ensureIndex(keyArg); values[index] = 0; return (nullKey) ? null : keys[index]; } public void remove(Object key) { if (key == null) { key = UniqueTag.NULL_VALUE; } int index = findIndex(key); if (0 <= index) { keys[index] = DELETED; --keyCount; } } public void clear() { int i = keys.length; while (i != 0) { keys[--i] = null; } keyCount = 0; occupiedCount = 0; } public Iterator newIterator() { return new Iterator(this); } // The sole purpose of the method is to avoid accessing private fields // from the Iterator inner class to workaround JDK 1.1 compiler bug which // generates code triggering VerifierError on recent JVMs final void initIterator(Iterator i) { i.init(keys, values, keyCount); } /** Return array of present keys */ public Object[] getKeys() { Object[] array = new Object[keyCount]; getKeys(array, 0); return array; } public void getKeys(Object[] array, int offset) { int count = keyCount; for (int i = 0; count != 0; ++i) { Object key = keys[i]; if (key != null && key != DELETED) { if (key == UniqueTag.NULL_VALUE) { key = null; } array[offset] = key; ++offset; --count; } } } private static int tableLookupStep(int fraction, int mask, int power) { int shift = 32 - 2 * power; if (shift >= 0) { return ((fraction >>> shift) & mask) | 1; } else { return (fraction & (mask >>> -shift)) | 1; } } private int findIndex(Object key) { if (keys != null) { int hash = key.hashCode(); int fraction = hash * A; int index = fraction >>> (32 - power); Object test = keys[index]; if (test != null) { int N = 1 << power; if (test == key || (values[N + index] == hash && test.equals(key))) { return index; } // Search in table after first failed attempt int mask = N - 1; int step = tableLookupStep(fraction, mask, power); int n = 0; for (;;) { if (check) { if (n >= occupiedCount) Kit.codeBug(); ++n; } index = (index + step) & mask; test = keys[index]; if (test == null) { break; } if (test == key || (values[N + index] == hash && test.equals(key))) { return index; } } } } return -1; } // Insert key that is not present to table without deleted entries // and enough free space private int insertNewKey(Object key, int hash) { if (check && occupiedCount != keyCount) Kit.codeBug(); if (check && keyCount == 1 << power) Kit.codeBug(); int fraction = hash * A; int index = fraction >>> (32 - power); int N = 1 << power; if (keys[index] != null) { int mask = N - 1; int step = tableLookupStep(fraction, mask, power); int firstIndex = index; do { if (check && keys[index] == DELETED) Kit.codeBug(); index = (index + step) & mask; if (check && firstIndex == index) Kit.codeBug(); } while (keys[index] != null); } keys[index] = key; values[N + index] = hash; ++occupiedCount; ++keyCount; return index; } private void rehashTable() { if (keys == null) { if (check && keyCount != 0) Kit.codeBug(); if (check && occupiedCount != 0) Kit.codeBug(); int N = 1 << power; keys = new Object[N]; values = new int[2 * N]; } else { // Check if removing deleted entries would free enough space if (keyCount * 2 >= occupiedCount) { // Need to grow: less then half of deleted entries ++power; } int N = 1 << power; Object[] oldKeys = keys; int[] oldValues = values; int oldN = oldKeys.length; keys = new Object[N]; values = new int[2 * N]; int remaining = keyCount; occupiedCount = keyCount = 0; for (int i = 0; remaining != 0; ++i) { Object key = oldKeys[i]; if (key != null && key != DELETED) { int keyHash = oldValues[oldN + i]; int index = insertNewKey(key, keyHash); values[index] = oldValues[i]; --remaining; } } } } // Ensure key index creating one if necessary private int ensureIndex(Object key) { int hash = key.hashCode(); int index = -1; int firstDeleted = -1; if (keys != null) { int fraction = hash * A; index = fraction >>> (32 - power); Object test = keys[index]; if (test != null) { int N = 1 << power; if (test == key || (values[N + index] == hash && test.equals(key))) { return index; } if (test == DELETED) { firstDeleted = index; } // Search in table after first failed attempt int mask = N - 1; int step = tableLookupStep(fraction, mask, power); int n = 0; for (;;) { if (check) { if (n >= occupiedCount) Kit.codeBug(); ++n; } index = (index + step) & mask; test = keys[index]; if (test == null) { break; } if (test == key || (values[N + index] == hash && test.equals(key))) { return index; } if (test == DELETED && firstDeleted < 0) { firstDeleted = index; } } } } // Inserting of new key if (check && keys != null && keys[index] != null) Kit.codeBug(); if (firstDeleted >= 0) { index = firstDeleted; } else { // Need to consume empty entry: check occupation level if (keys == null || occupiedCount * 4 >= (1 << power) * 3) { // Too litle unused entries: rehash rehashTable(); return insertNewKey(key, hash); } ++occupiedCount; } keys[index] = key; values[(1 << power) + index] = hash; ++keyCount; return index; } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); int count = keyCount; for (int i = 0; count != 0; ++i) { Object key = keys[i]; if (key != null && key != DELETED) { --count; out.writeObject(key); out.writeInt(values[i]); } } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); int writtenKeyCount = keyCount; if (writtenKeyCount != 0) { keyCount = 0; int N = 1 << power; keys = new Object[N]; values = new int[2 * N]; for (int i = 0; i != writtenKeyCount; ++i) { Object key = in.readObject(); int hash = key.hashCode(); int index = insertNewKey(key, hash); values[index] = in.readInt(); } } } // A == golden_ratio * (1 << 32) = ((sqrt(5) - 1) / 2) * (1 << 32) // See Knuth etc. private static final int A = 0x9e3779b9; private static final Object DELETED = new Object(); // Structure of kyes and values arrays (N == 1 << power): // keys[0 <= i < N]: key value or null or DELETED mark // values[0 <= i < N]: value of key at keys[i] // values[N <= i < 2*N]: hash code of key at keys[i-N] private transient Object[] keys; private transient int[] values; private int power; private int keyCount; private transient int occupiedCount; // == keyCount + deleted_count // If true, enables consitency checks private static final boolean check = false; /* TEST START public static void main(String[] args) { if (!check) { System.err.println("Set check to true and re-run"); throw new RuntimeException("Set check to true and re-run"); } ObjToIntMap map; map = new ObjToIntMap(0); testHash(map, 3); map = new ObjToIntMap(0); testHash(map, 10 * 1000); map = new ObjToIntMap(); testHash(map, 10 * 1000); map = new ObjToIntMap(30 * 1000); testHash(map, 10 * 100); map.clear(); testHash(map, 4); map = new ObjToIntMap(0); testHash(map, 10 * 100); } private static void testHash(ObjToIntMap map, int N) { System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(i); check(-1 == map.get(key, -1)); map.put(key, i); check(i == map.get(key, -1)); } System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(i); map.put(key, i); check(i == map.get(key, -1)); } check(map.size() == N); System.out.print("."); System.out.flush(); Object[] keys = map.getKeys(); check(keys.length == N); for (int i = 0; i != N; ++i) { Object key = keys[i]; check(map.has(key)); } System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(i); check(i == map.get(key, -1)); } int Nsqrt = -1; for (int i = 0; ; ++i) { if (i * i >= N) { Nsqrt = i; break; } } System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(i * i); map.put(key, i); check(i == map.get(key, -1)); } check(map.size() == 2 * N - Nsqrt); System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(i * i); check(i == map.get(key, -1)); } System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(-1 - i * i); map.put(key, i); check(i == map.get(key, -1)); } check(map.size() == 3 * N - Nsqrt); System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(-1 - i * i); map.remove(key); check(!map.has(key)); } check(map.size() == 2 * N - Nsqrt); System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(i * i); check(i == map.get(key, -1)); } System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(i); int j = intSqrt(i); if (j * j == i) { check(j == map.get(key, -1)); }else { check(i == map.get(key, -1)); } } System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(i * i); map.remove(key); check(-2 == map.get(key, -2)); } System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(i); map.put(key, i); check(i == map.get(key, -2)); } check(map.size() == N); System.out.print("."); System.out.flush(); for (int i = 0; i != N; ++i) { Object key = testKey(i); check(i == map.get(key, -1)); } System.out.print("."); System.out.flush(); ObjToIntMap copy = (ObjToIntMap)writeAndRead(map); check(copy.size() == N); for (int i = 0; i != N; ++i) { Object key = testKey(i); check(i == copy.get(key, -1)); } System.out.print("."); System.out.flush(); checkSameMaps(copy, map); System.out.println(); System.out.flush(); } private static void checkSameMaps(ObjToIntMap map1, ObjToIntMap map2) { check(map1.size() == map2.size()); Object[] keys = map1.getKeys(); check(keys.length == map1.size()); for (int i = 0; i != keys.length; ++i) { check(map1.get(keys[i], -1) == map2.get(keys[i], -1)); } } private static void check(boolean condition) { if (!condition) Kit.codeBug(); } private static Object[] testPool; private static Object testKey(int i) { int MAX_POOL = 100; if (0 <= i && i < MAX_POOL) { if (testPool != null && testPool[i] != null) { return testPool[i]; } } Object x = new Double(i + 0.5); if (0 <= i && i < MAX_POOL) { if (testPool == null) { testPool = new Object[MAX_POOL]; } testPool[i] = x; } return x; } private static int intSqrt(int i) { int approx = (int)Math.sqrt(i) + 1; while (approx * approx > i) { --approx; } return approx; } private static Object writeAndRead(Object obj) { try { java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(bos); out.writeObject(obj); out.close(); byte[] data = bos.toByteArray(); java.io.ByteArrayInputStream bis = new java.io.ByteArrayInputStream(data); java.io.ObjectInputStream in = new java.io.ObjectInputStream(bis); Object result = in.readObject(); in.close(); return result; }catch (Exception ex) { throw new RuntimeException("Unexpected"); } } // TEST END */ } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/FunctionObject.java0000644000175000017500000005234711314263504033675 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * David C. Navas * Ted Neward * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; import java.lang.reflect.*; import java.io.*; public class FunctionObject extends BaseFunction { static final long serialVersionUID = -5332312783643935019L; /** * Create a JavaScript function object from a Java method. * *

The member argument must be either a java.lang.reflect.Method * or a java.lang.reflect.Constructor and must match one of two forms.

* * The first form is a member with zero or more parameters * of the following types: Object, String, boolean, Scriptable, * int, or double. The Long type is not supported * because the double representation of a long (which is the * EMCA-mandated storage type for Numbers) may lose precision. * If the member is a Method, the return value must be void or one * of the types allowed for parameters.

* * The runtime will perform appropriate conversions based * upon the type of the parameter. A parameter type of * Object specifies that no conversions are to be done. A parameter * of type String will use Context.toString to convert arguments. * Similarly, parameters of type double, boolean, and Scriptable * will cause Context.toNumber, Context.toBoolean, and * Context.toObject, respectively, to be called.

* * If the method is not static, the Java 'this' value will * correspond to the JavaScript 'this' value. Any attempt * to call the function with a 'this' value that is not * of the right Java type will result in an error.

* * The second form is the variable arguments (or "varargs") * form. If the FunctionObject will be used as a constructor, * the member must have the following parameters *

     *      (Context cx, Object[] args, Function ctorObj,
     *       boolean inNewExpr)
* and if it is a Method, be static and return an Object result.

* * Otherwise, if the FunctionObject will not be used to define a * constructor, the member must be a static Method with parameters *

     *      (Context cx, Scriptable thisObj, Object[] args,
     *       Function funObj) 
* and an Object result.

* * When the function varargs form is called as part of a function call, * the args parameter contains the * arguments, with thisObj * set to the JavaScript 'this' value. funObj * is the function object for the invoked function.

* * When the constructor varargs form is called or invoked while evaluating * a new expression, args contains the * arguments, ctorObj refers to this FunctionObject, and * inNewExpr is true if and only if a new * expression caused the call. This supports defining a function that * has different behavior when called as a constructor than when * invoked as a normal function call. (For example, the Boolean * constructor, when called as a function, * will convert to boolean rather than creating a new object.)

* * @param name the name of the function * @param methodOrConstructor a java.lang.reflect.Method or a java.lang.reflect.Constructor * that defines the object * @param scope enclosing scope of function * @see org.mozilla.javascript.Scriptable */ public FunctionObject(String name, Member methodOrConstructor, Scriptable scope) { if (methodOrConstructor instanceof Constructor) { member = new MemberBox((Constructor) methodOrConstructor); isStatic = true; // well, doesn't take a 'this' } else { member = new MemberBox((Method) methodOrConstructor); isStatic = member.isStatic(); } String methodName = member.getName(); this.functionName = name; Class[] types = member.argTypes; int arity = types.length; if (arity == 4 && (types[1].isArray() || types[2].isArray())) { // Either variable args or an error. if (types[1].isArray()) { if (!isStatic || types[0] != ScriptRuntime.ContextClass || types[1].getComponentType() != ScriptRuntime.ObjectClass || types[2] != ScriptRuntime.FunctionClass || types[3] != Boolean.TYPE) { throw Context.reportRuntimeError1( "msg.varargs.ctor", methodName); } parmsLength = VARARGS_CTOR; } else { if (!isStatic || types[0] != ScriptRuntime.ContextClass || types[1] != ScriptRuntime.ScriptableClass || types[2].getComponentType() != ScriptRuntime.ObjectClass || types[3] != ScriptRuntime.FunctionClass) { throw Context.reportRuntimeError1( "msg.varargs.fun", methodName); } parmsLength = VARARGS_METHOD; } } else { parmsLength = arity; if (arity > 0) { typeTags = new byte[arity]; for (int i = 0; i != arity; ++i) { int tag = getTypeTag(types[i]); if (tag == JAVA_UNSUPPORTED_TYPE) { throw Context.reportRuntimeError2( "msg.bad.parms", types[i].getName(), methodName); } typeTags[i] = (byte)tag; } } } if (member.isMethod()) { Method method = member.method(); Class returnType = method.getReturnType(); if (returnType == Void.TYPE) { hasVoidReturn = true; } else { returnTypeTag = getTypeTag(returnType); } } else { Class ctorType = member.getDeclaringClass(); if (!ScriptRuntime.ScriptableClass.isAssignableFrom(ctorType)) { throw Context.reportRuntimeError1( "msg.bad.ctor.return", ctorType.getName()); } } ScriptRuntime.setFunctionProtoAndParent(this, scope); } /** * @return One of JAVA_*_TYPE constants to indicate desired type * or {@link #JAVA_UNSUPPORTED_TYPE} if the convertion is not * possible */ public static int getTypeTag(Class type) { if (type == ScriptRuntime.StringClass) return JAVA_STRING_TYPE; if (type == ScriptRuntime.IntegerClass || type == Integer.TYPE) return JAVA_INT_TYPE; if (type == ScriptRuntime.BooleanClass || type == Boolean.TYPE) return JAVA_BOOLEAN_TYPE; if (type == ScriptRuntime.DoubleClass || type == Double.TYPE) return JAVA_DOUBLE_TYPE; if (ScriptRuntime.ScriptableClass.isAssignableFrom(type)) return JAVA_SCRIPTABLE_TYPE; if (type == ScriptRuntime.ObjectClass) return JAVA_OBJECT_TYPE; // Note that the long type is not supported; see the javadoc for // the constructor for this class return JAVA_UNSUPPORTED_TYPE; } public static Object convertArg(Context cx, Scriptable scope, Object arg, int typeTag) { switch (typeTag) { case JAVA_STRING_TYPE: if (arg instanceof String) return arg; return ScriptRuntime.toString(arg); case JAVA_INT_TYPE: if (arg instanceof Integer) return arg; return Integer.valueOf(ScriptRuntime.toInt32(arg)); case JAVA_BOOLEAN_TYPE: if (arg instanceof Boolean) return arg; return ScriptRuntime.toBoolean(arg) ? Boolean.TRUE : Boolean.FALSE; case JAVA_DOUBLE_TYPE: if (arg instanceof Double) return arg; return new Double(ScriptRuntime.toNumber(arg)); case JAVA_SCRIPTABLE_TYPE: return ScriptRuntime.toObjectOrNull(cx, arg, scope); case JAVA_OBJECT_TYPE: return arg; default: throw new IllegalArgumentException(); } } /** * Return the value defined by the method used to construct the object * (number of parameters of the method, or 1 if the method is a "varargs" * form). */ @Override public int getArity() { return parmsLength < 0 ? 1 : parmsLength; } /** * Return the same value as {@link #getArity()}. */ @Override public int getLength() { return getArity(); } @Override public String getFunctionName() { return (functionName == null) ? "" : functionName; } /** * Get Java method or constructor this function represent. */ public Member getMethodOrConstructor() { if (member.isMethod()) { return member.method(); } else { return member.ctor(); } } static Method findSingleMethod(Method[] methods, String name) { Method found = null; for (int i = 0, N = methods.length; i != N; ++i) { Method method = methods[i]; if (method != null && name.equals(method.getName())) { if (found != null) { throw Context.reportRuntimeError2( "msg.no.overload", name, method.getDeclaringClass().getName()); } found = method; } } return found; } /** * Returns all public methods declared by the specified class. This excludes * inherited methods. * * @param clazz the class from which to pull public declared methods * @return the public methods declared in the specified class * @see Class#getDeclaredMethods() */ static Method[] getMethodList(Class clazz) { Method[] methods = null; try { // getDeclaredMethods may be rejected by the security manager // but getMethods is more expensive if (!sawSecurityException) methods = clazz.getDeclaredMethods(); } catch (SecurityException e) { // If we get an exception once, give up on getDeclaredMethods sawSecurityException = true; } if (methods == null) { methods = clazz.getMethods(); } int count = 0; for (int i=0; i < methods.length; i++) { if (sawSecurityException ? methods[i].getDeclaringClass() != clazz : !Modifier.isPublic(methods[i].getModifiers())) { methods[i] = null; } else { count++; } } Method[] result = new Method[count]; int j=0; for (int i=0; i < methods.length; i++) { if (methods[i] != null) result[j++] = methods[i]; } return result; } /** * Define this function as a JavaScript constructor. *

* Sets up the "prototype" and "constructor" properties. Also * calls setParent and setPrototype with appropriate values. * Then adds the function object as a property of the given scope, using * prototype.getClassName() * as the name of the property. * * @param scope the scope in which to define the constructor (typically * the global object) * @param prototype the prototype object * @see org.mozilla.javascript.Scriptable#setParentScope * @see org.mozilla.javascript.Scriptable#setPrototype * @see org.mozilla.javascript.Scriptable#getClassName */ public void addAsConstructor(Scriptable scope, Scriptable prototype) { initAsConstructor(scope, prototype); defineProperty(scope, prototype.getClassName(), this, ScriptableObject.DONTENUM); } void initAsConstructor(Scriptable scope, Scriptable prototype) { ScriptRuntime.setFunctionProtoAndParent(this, scope); setImmunePrototypeProperty(prototype); prototype.setParentScope(this); defineProperty(prototype, "constructor", this, ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY); setParentScope(scope); } /** * @deprecated Use {@link #getTypeTag(Class)} * and {@link #convertArg(Context, Scriptable, Object, int)} * for type conversion. */ public static Object convertArg(Context cx, Scriptable scope, Object arg, Class desired) { int tag = getTypeTag(desired); if (tag == JAVA_UNSUPPORTED_TYPE) { throw Context.reportRuntimeError1 ("msg.cant.convert", desired.getName()); } return convertArg(cx, scope, arg, tag); } /** * Performs conversions on argument types if needed and * invokes the underlying Java method or constructor. *

* Implements Function.call. * * @see org.mozilla.javascript.Function#call( * Context, Scriptable, Scriptable, Object[]) */ @Override public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { Object result; boolean checkMethodResult = false; if (parmsLength < 0) { if (parmsLength == VARARGS_METHOD) { Object[] invokeArgs = { cx, thisObj, args, this }; result = member.invoke(null, invokeArgs); checkMethodResult = true; } else { boolean inNewExpr = (thisObj == null); Boolean b = inNewExpr ? Boolean.TRUE : Boolean.FALSE; Object[] invokeArgs = { cx, args, this, b }; result = (member.isCtor()) ? member.newInstance(invokeArgs) : member.invoke(null, invokeArgs); } } else { if (!isStatic) { Class clazz = member.getDeclaringClass(); if (!clazz.isInstance(thisObj)) { boolean compatible = false; if (thisObj == scope) { Scriptable parentScope = getParentScope(); if (scope != parentScope) { // Call with dynamic scope for standalone function, // use parentScope as thisObj compatible = clazz.isInstance(parentScope); if (compatible) { thisObj = parentScope; } } } if (!compatible) { // Couldn't find an object to call this on. throw ScriptRuntime.typeError1("msg.incompat.call", functionName); } } } Object[] invokeArgs; if (parmsLength == args.length) { // Do not allocate new argument array if java arguments are // the same as the original js ones. invokeArgs = args; for (int i = 0; i != parmsLength; ++i) { Object arg = args[i]; Object converted = convertArg(cx, scope, arg, typeTags[i]); if (arg != converted) { if (invokeArgs == args) { invokeArgs = args.clone(); } invokeArgs[i] = converted; } } } else if (parmsLength == 0) { invokeArgs = ScriptRuntime.emptyArgs; } else { invokeArgs = new Object[parmsLength]; for (int i = 0; i != parmsLength; ++i) { Object arg = (i < args.length) ? args[i] : Undefined.instance; invokeArgs[i] = convertArg(cx, scope, arg, typeTags[i]); } } if (member.isMethod()) { result = member.invoke(thisObj, invokeArgs); checkMethodResult = true; } else { result = member.newInstance(invokeArgs); } } if (checkMethodResult) { if (hasVoidReturn) { result = Undefined.instance; } else if (returnTypeTag == JAVA_UNSUPPORTED_TYPE) { result = cx.getWrapFactory().wrap(cx, scope, result, null); } // XXX: the code assumes that if returnTypeTag == JAVA_OBJECT_TYPE // then the Java method did a proper job of converting the // result to JS primitive or Scriptable to avoid // potentially costly Context.javaToJS call. } return result; } /** * Return new {@link Scriptable} instance using the default * constructor for the class of the underlying Java method. * Return null to indicate that the call method should be used to create * new objects. */ @Override public Scriptable createObject(Context cx, Scriptable scope) { if (member.isCtor() || parmsLength == VARARGS_CTOR) { return null; } Scriptable result; try { result = (Scriptable) member.getDeclaringClass().newInstance(); } catch (Exception ex) { throw Context.throwAsScriptRuntimeEx(ex); } result.setPrototype(getClassPrototype()); result.setParentScope(getParentScope()); return result; } boolean isVarArgsMethod() { return parmsLength == VARARGS_METHOD; } boolean isVarArgsConstructor() { return parmsLength == VARARGS_CTOR; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (parmsLength > 0) { Class[] types = member.argTypes; typeTags = new byte[parmsLength]; for (int i = 0; i != parmsLength; ++i) { typeTags[i] = (byte)getTypeTag(types[i]); } } if (member.isMethod()) { Method method = member.method(); Class returnType = method.getReturnType(); if (returnType == Void.TYPE) { hasVoidReturn = true; } else { returnTypeTag = getTypeTag(returnType); } } } private static final short VARARGS_METHOD = -1; private static final short VARARGS_CTOR = -2; private static boolean sawSecurityException; public static final int JAVA_UNSUPPORTED_TYPE = 0; public static final int JAVA_STRING_TYPE = 1; public static final int JAVA_INT_TYPE = 2; public static final int JAVA_BOOLEAN_TYPE = 3; public static final int JAVA_DOUBLE_TYPE = 4; public static final int JAVA_SCRIPTABLE_TYPE = 5; public static final int JAVA_OBJECT_TYPE = 6; MemberBox member; private String functionName; private transient byte[] typeTags; private int parmsLength; private transient boolean hasVoidReturn; private transient int returnTypeTag; private boolean isStatic; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/Function.java0000644000175000017500000000624011314263504032535 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; /** * This is interface that all functions in JavaScript must implement. * The interface provides for calling functions and constructors. * * @see org.mozilla.javascript.Scriptable * @author Norris Boyd */ public interface Function extends Scriptable, Callable { /** * Call the function. * * Note that the array of arguments is not guaranteed to have * length greater than 0. * * @param cx the current Context for this thread * @param scope the scope to execute the function relative to. This is * set to the value returned by getParentScope() except * when the function is called from a closure. * @param thisObj the JavaScript this object * @param args the array of arguments * @return the result of the call */ public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args); /** * Call the function as a constructor. * * This method is invoked by the runtime in order to satisfy a use * of the JavaScript new operator. This method is * expected to create a new object and return it. * * @param cx the current Context for this thread * @param scope an enclosing scope of the caller except * when the function is called from a closure. * @param args the array of arguments * @return the allocated object */ public Scriptable construct(Context cx, Scriptable scope, Object[] args); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/EvaluatorException.java0000644000175000017500000000765511314263504034604 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; /** * The class of exceptions thrown by the JavaScript engine. */ public class EvaluatorException extends RhinoException { static final long serialVersionUID = -8743165779676009808L; public EvaluatorException(String detail) { super(detail); } /** * Create an exception with the specified detail message. * * Errors internal to the JavaScript engine will simply throw a * RuntimeException. * * @param detail the error message * @param sourceName the name of the source reponsible for the error * @param lineNumber the line number of the source */ public EvaluatorException(String detail, String sourceName, int lineNumber) { this(detail, sourceName, lineNumber, null, 0); } /** * Create an exception with the specified detail message. * * Errors internal to the JavaScript engine will simply throw a * RuntimeException. * * @param detail the error message * @param sourceName the name of the source responsible for the error * @param lineNumber the line number of the source * @param columnNumber the columnNumber of the source (may be zero if * unknown) * @param lineSource the source of the line containing the error (may be * null if unknown) */ public EvaluatorException(String detail, String sourceName, int lineNumber, String lineSource, int columnNumber) { super(detail); recordErrorOrigin(sourceName, lineNumber, lineSource, columnNumber); } /** * @deprecated Use {@link RhinoException#sourceName()} from the super class. */ public String getSourceName() { return sourceName(); } /** * @deprecated Use {@link RhinoException#lineNumber()} from the super class. */ public int getLineNumber() { return lineNumber(); } /** * @deprecated Use {@link RhinoException#columnNumber()} from the super class. */ public int getColumnNumber() { return columnNumber(); } /** * @deprecated Use {@link RhinoException#lineSource()} from the super class. */ public String getLineSource() { return lineSource(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ImporterTopLevel.java0000644000175000017500000002515711314263504034234 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Matthias Radestock * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; /** * Class ImporterTopLevel * * This class defines a ScriptableObject that can be instantiated * as a top-level ("global") object to provide functionality similar * to Java's "import" statement. *

* This class can be used to create a top-level scope using the following code: *

 *  Scriptable scope = new ImporterTopLevel(cx);
 * 
* Then JavaScript code will have access to the following methods: *
    *
  • importClass - will "import" a class by making its unqualified name * available as a property of the top-level scope *
  • importPackage - will "import" all the classes of the package by * searching for unqualified names as classes qualified * by the given package. *
* The following code from the shell illustrates this use: *
 * js> importClass(java.io.File)
 * js> f = new File('help.txt')
 * help.txt
 * js> importPackage(java.util)
 * js> v = new Vector()
 * []
 *
 * @author Norris Boyd
 */
public class ImporterTopLevel extends IdScriptableObject
{
    static final long serialVersionUID = -9095380847465315412L;

    private static final Object IMPORTER_TAG = "Importer";

    public ImporterTopLevel() { }

    public ImporterTopLevel(Context cx) {
        this(cx, false);
    }

    public ImporterTopLevel(Context cx, boolean sealed)
    {
        initStandardObjects(cx, sealed);
    }

    @Override
    public String getClassName()
    {
        return (topScopeFlag) ? "global" : "JavaImporter";
    }

    public static void init(Context cx, Scriptable scope, boolean sealed)
    {
        ImporterTopLevel obj = new ImporterTopLevel();
        obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed);
    }

    public void initStandardObjects(Context cx, boolean sealed)
    {
        // Assume that Context.initStandardObjects initialize JavaImporter
        // property lazily so the above init call is not yet called
        cx.initStandardObjects(this, sealed);
        topScopeFlag = true;
        // If seal is true then exportAsJSClass(cx, seal) would seal
        // this obj. Since this is scope as well, it would not allow
        // to add variables.
        IdFunctionObject ctor = exportAsJSClass(MAX_PROTOTYPE_ID, this, false);
        if (sealed) {
            ctor.sealObject();
        }
        // delete "constructor" defined by exportAsJSClass so "constructor"
        // name would refer to Object.constructor
        // and not to JavaImporter.prototype.constructor.
        delete("constructor");
    }

    @Override
    public boolean has(String name, Scriptable start) {
        return super.has(name, start)
               || getPackageProperty(name, start) != NOT_FOUND;
    }

    @Override
    public Object get(String name, Scriptable start) {
        Object result = super.get(name, start);
        if (result != NOT_FOUND)
            return result;
        result = getPackageProperty(name, start);
        return result;
    }

    private Object getPackageProperty(String name, Scriptable start) {
        Object result = NOT_FOUND;
        Object[] elements;
        synchronized (importedPackages) {
            elements = importedPackages.toArray();
        }
        for (int i=0; i < elements.length; i++) {
            NativeJavaPackage p = (NativeJavaPackage) elements[i];
            Object v = p.getPkgProperty(name, start, false);
            if (v != null && !(v instanceof NativeJavaPackage)) {
                if (result == NOT_FOUND) {
                    result = v;
                } else {
                    throw Context.reportRuntimeError2(
                        "msg.ambig.import", result.toString(), v.toString());
                }
            }
        }
        return result;
    }

    /**
     * @deprecated Kept only for compatibility.
     */
    public void importPackage(Context cx, Scriptable thisObj, Object[] args,
                              Function funObj)
    {
        js_importPackage(args);
    }

    private Object js_construct(Scriptable scope, Object[] args)
    {
        ImporterTopLevel result = new ImporterTopLevel();
        for (int i = 0; i != args.length; ++i) {
            Object arg = args[i];
            if (arg instanceof NativeJavaClass) {
                result.importClass((NativeJavaClass)arg);
            } else if (arg instanceof NativeJavaPackage) {
                result.importPackage((NativeJavaPackage)arg);
            } else {
                throw Context.reportRuntimeError1(
                    "msg.not.class.not.pkg", Context.toString(arg));
            }
        }
        // set explicitly prototype and scope
        // as otherwise in top scope mode BaseFunction.construct
        // would keep them set to null. It also allow to use
        // JavaImporter without new and still get properly
        // initialized object.
        result.setParentScope(scope);
        result.setPrototype(this);
        return result;
    }

    private Object js_importClass(Object[] args)
    {
        for (int i = 0; i != args.length; i++) {
            Object arg = args[i];
            if (!(arg instanceof NativeJavaClass)) {
                throw Context.reportRuntimeError1(
                    "msg.not.class", Context.toString(arg));
            }
            importClass((NativeJavaClass)arg);
        }
        return Undefined.instance;
    }

    private Object js_importPackage(Object[] args)
    {
        for (int i = 0; i != args.length; i++) {
            Object arg = args[i];
            if (!(arg instanceof NativeJavaPackage)) {
                throw Context.reportRuntimeError1(
                    "msg.not.pkg", Context.toString(arg));
            }
            importPackage((NativeJavaPackage)arg);
        }
        return Undefined.instance;
    }

    private void importPackage(NativeJavaPackage pkg)
    {
        if(pkg == null) {
            return;
        }
        synchronized (importedPackages) {
            for (int j = 0; j != importedPackages.size(); j++) {
                if (pkg.equals(importedPackages.get(j))) {
                    return;
                }
            }
            importedPackages.add(pkg);
        }
    }

    private void importClass(NativeJavaClass cl)
    {
        String s = cl.getClassObject().getName();
        String n = s.substring(s.lastIndexOf('.')+1);
        Object val = get(n, this);
        if (val != NOT_FOUND && val != cl) {
            throw Context.reportRuntimeError1("msg.prop.defined", n);
        }
        //defineProperty(n, cl, DONTENUM);
        put(n, this, cl);
    }

    @Override
    protected void initPrototypeId(int id)
    {
        String s;
        int arity;
        switch (id) {
          case Id_constructor:   arity=0; s="constructor";   break;
          case Id_importClass:   arity=1; s="importClass";   break;
          case Id_importPackage: arity=1; s="importPackage"; break;
          default: throw new IllegalArgumentException(String.valueOf(id));
        }
        initPrototypeMethod(IMPORTER_TAG, id, s, arity);
    }

    @Override
    public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
                             Scriptable thisObj, Object[] args)
    {
        if (!f.hasTag(IMPORTER_TAG)) {
            return super.execIdCall(f, cx, scope, thisObj, args);
        }
        int id = f.methodId();
        switch (id) {
          case Id_constructor:
            return js_construct(scope, args);

          case Id_importClass:
            return realThis(thisObj, f).js_importClass(args);

          case Id_importPackage:
            return realThis(thisObj, f).js_importPackage(args);
        }
        throw new IllegalArgumentException(String.valueOf(id));
    }

    private ImporterTopLevel realThis(Scriptable thisObj, IdFunctionObject f)
    {
        if (topScopeFlag) {
            // when used as top scope importPackage and importClass are global
            // function that ignore thisObj
            return this;
        }
        if (!(thisObj instanceof ImporterTopLevel))
            throw incompatibleCallError(f);
        return (ImporterTopLevel)thisObj;
    }

// #string_id_map#

    @Override
    protected int findPrototypeId(String s)
    {
        int id;
// #generated# Last update: 2007-05-09 08:15:24 EDT
        L0: { id = 0; String X = null; int c;
            int s_length = s.length();
            if (s_length==11) {
                c=s.charAt(0);
                if (c=='c') { X="constructor";id=Id_constructor; }
                else if (c=='i') { X="importClass";id=Id_importClass; }
            }
            else if (s_length==13) { X="importPackage";id=Id_importPackage; }
            if (X!=null && X!=s && !X.equals(s)) id = 0;
            break L0;
        }
// #/generated#
        return id;
    }

    private static final int
        Id_constructor          = 1,
        Id_importClass          = 2,
        Id_importPackage        = 3,
        MAX_PROTOTYPE_ID        = 3;

// #/string_id_map#

    private ObjArray importedPackages = new ObjArray();
    private boolean topScopeFlag;
}
jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/DefiningClassLoader.java0000644000175000017500000000570111314263504034611 0ustar  jamespagejamespage00000000000000/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Rhino code, released
 * May 6, 1999.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1997-1999
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Norris Boyd
 *   Roger Lawrence
 *   Patrick Beard
 *   Igor Bukanov
 *
 * Alternatively, the contents of this file may be used under the terms of
 * the GNU General Public License Version 2 or later (the "GPL"), in which
 * case the provisions of the GPL are applicable instead of those above. If
 * you wish to allow use of your version of this file only under the terms of
 * the GPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replacing
 * them with the notice and other provisions required by the GPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the GPL.
 *
 * ***** END LICENSE BLOCK ***** */

package org.mozilla.javascript;

/**
 * Load generated classes.
 *
 * @author Norris Boyd
 */
public class DefiningClassLoader extends ClassLoader
    implements GeneratedClassLoader
{
    public DefiningClassLoader() {
        this.parentLoader = getClass().getClassLoader();
    }

    public DefiningClassLoader(ClassLoader parentLoader) {
        this.parentLoader = parentLoader;
    }

    public Class defineClass(String name, byte[] data) {
        // Use our own protection domain for the generated classes.
        // TODO: we might want to use a separate protection domain for classes
        // compiled from scripts, based on where the script was loaded from.
        return super.defineClass(name, data, 0, data.length, 
                SecurityUtilities.getProtectionDomain(getClass()));
    }

    public void linkClass(Class cl) {
        resolveClass(cl);
    }

    @Override
    public Class loadClass(String name, boolean resolve)
        throws ClassNotFoundException
    {
        Class cl = findLoadedClass(name);
        if (cl == null) {
            if (parentLoader != null) {
                cl = parentLoader.loadClass(name);
            } else {
                cl = findSystemClass(name);
            }
        }
        if (resolve) {
            resolveClass(cl);
        }
        return cl;
    }

    private final ClassLoader parentLoader;
}
jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/NativeJavaMethod.java0000644000175000017500000005222311314263504034143 0ustar  jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Rhino code, released
 * May 6, 1999.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1997-1999
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Norris Boyd
 *   Frank Mitchell
 *   Mike Shaver
 *   Ulrike Mueller 
 *
 * Alternatively, the contents of this file may be used under the terms of
 * the GNU General Public License Version 2 or later (the "GPL"), in which
 * case the provisions of the GPL are applicable instead of those above. If
 * you wish to allow use of your version of this file only under the terms of
 * the GPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replacing
 * them with the notice and other provisions required by the GPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the GPL.
 *
 * ***** END LICENSE BLOCK ***** */

package org.mozilla.javascript;

import java.lang.reflect.*;

/**
 * This class reflects Java methods into the JavaScript environment and
 * handles overloading of methods.
 *
 * @author Mike Shaver
 * @see NativeJavaArray
 * @see NativeJavaPackage
 * @see NativeJavaClass
 */

public class NativeJavaMethod extends BaseFunction
{
    static final long serialVersionUID = -3440381785576412928L;

    NativeJavaMethod(MemberBox[] methods)
    {
        this.functionName = methods[0].getName();
        this.methods = methods;
    }

    NativeJavaMethod(MemberBox method, String name)
    {
        this.functionName = name;
        this.methods = new MemberBox[] { method };
    }

    public NativeJavaMethod(Method method, String name)
    {
        this(new MemberBox(method), name);
    }

    @Override
    public String getFunctionName()
    {
        return functionName;
    }

    static String scriptSignature(Object[] values)
    {
        StringBuffer sig = new StringBuffer();
        for (int i = 0; i != values.length; ++i) {
            Object value = values[i];

            String s;
            if (value == null) {
                s = "null";
            } else if (value instanceof Boolean) {
                s = "boolean";
            } else if (value instanceof String) {
                s = "string";
            } else if (value instanceof Number) {
                s = "number";
            } else if (value instanceof Scriptable) {
                if (value instanceof Undefined) {
                    s = "undefined";
                } else if (value instanceof Wrapper) {
                    Object wrapped = ((Wrapper)value).unwrap();
                    s = wrapped.getClass().getName();
                } else if (value instanceof Function) {
                    s = "function";
                } else {
                    s = "object";
                }
            } else {
                s = JavaMembers.javaSignature(value.getClass());
            }

            if (i != 0) {
                sig.append(',');
            }
            sig.append(s);
        }
        return sig.toString();
    }

    @Override
    String decompile(int indent, int flags)
    {
        StringBuffer sb = new StringBuffer();
        boolean justbody = (0 != (flags & Decompiler.ONLY_BODY_FLAG));
        if (!justbody) {
            sb.append("function ");
            sb.append(getFunctionName());
            sb.append("() {");
        }
        sb.append("/*\n");
        sb.append(toString());
        sb.append(justbody ? "*/\n" : "*/}\n");
        return sb.toString();
    }

    @Override
    public String toString()
    {
        StringBuffer sb = new StringBuffer();
        for (int i = 0, N = methods.length; i != N; ++i) {
            Method method = methods[i].method();
            sb.append(JavaMembers.javaSignature(method.getReturnType()));
            sb.append(' ');
            sb.append(method.getName());
            sb.append(JavaMembers.liveConnectSignature(methods[i].argTypes));
            sb.append('\n');
        }
        return sb.toString();
    }

    @Override
    public Object call(Context cx, Scriptable scope, Scriptable thisObj,
                       Object[] args)
    {
        // Find a method that matches the types given.
        if (methods.length == 0) {
            throw new RuntimeException("No methods defined for call");
        }

        int index = findFunction(cx, methods, args);
        if (index < 0) {
            Class c = methods[0].method().getDeclaringClass();
            String sig = c.getName() + '.' + getFunctionName() + '(' +
                         scriptSignature(args) + ')';
            throw Context.reportRuntimeError1("msg.java.no_such_method", sig);
        }

        MemberBox meth = methods[index];
        Class[] argTypes = meth.argTypes;
      
        if (meth.vararg) {
            // marshall the explicit parameters
            Object[] newArgs = new Object[argTypes.length];
            for (int i = 0; i < argTypes.length-1; i++) {
                newArgs[i] = Context.jsToJava(args[i], argTypes[i]);
            }
            
            Object varArgs;
            
            // Handle special situation where a single variable parameter
            // is given and it is a Java or ECMA array or is null.
            if (args.length == argTypes.length &&
                (args[args.length-1] == null ||
                 args[args.length-1] instanceof NativeArray ||
                 args[args.length-1] instanceof NativeJavaArray))
            {
                // convert the ECMA array into a native array
                varArgs = Context.jsToJava(args[args.length-1], 
                                           argTypes[argTypes.length - 1]);
            } else {            
                // marshall the variable parameters
                Class componentType = argTypes[argTypes.length - 1].
                                         getComponentType();
                varArgs = Array.newInstance(componentType, 
                                            args.length - argTypes.length + 1);            
                for (int i = 0; i < Array.getLength(varArgs); i++) {
                    Object value = Context.jsToJava(args[argTypes.length-1 + i], 
                                                    componentType);
                    Array.set(varArgs, i, value);
                }
            }
            
            // add varargs
            newArgs[argTypes.length-1] = varArgs;
            // replace the original args with the new one
            args = newArgs;
        } else {  
            // First, we marshall the args.
            Object[] origArgs = args;
            for (int i = 0; i < args.length; i++) {
                Object arg = args[i];
                Object coerced = Context.jsToJava(arg, argTypes[i]);
                if (coerced != arg) {
                    if (origArgs == args) {
                        args = args.clone();
                    }
                    args[i] = coerced;
                }
            }
        }
        Object javaObject;
        if (meth.isStatic()) {
            javaObject = null;  // don't need an object
        } else {
            Scriptable o = thisObj;
            Class c = meth.getDeclaringClass();
            for (;;) {
                if (o == null) {
                    throw Context.reportRuntimeError3(
                        "msg.nonjava.method", getFunctionName(),
                        ScriptRuntime.toString(thisObj), c.getName());
                }
                if (o instanceof Wrapper) {
                    javaObject = ((Wrapper)o).unwrap();
                    if (c.isInstance(javaObject)) {
                        break;
                    }
                }
                o = o.getPrototype();
            }
        }
        if (debug) {
            printDebug("Calling ", meth, args);
        }

        Object retval = meth.invoke(javaObject, args);
        Class staticType = meth.method().getReturnType();

        if (debug) {
            Class actualType = (retval == null) ? null
                                                : retval.getClass();
            System.err.println(" ----- Returned " + retval +
                               " actual = " + actualType +
                               " expect = " + staticType);
        }

        Object wrapped = cx.getWrapFactory().wrap(cx, scope,
                                                  retval, staticType);
        if (debug) {
            Class actualType = (wrapped == null) ? null
                                                 : wrapped.getClass();
            System.err.println(" ----- Wrapped as " + wrapped +
                               " class = " + actualType);
        }

        if (wrapped == null && staticType == Void.TYPE) {
            wrapped = Undefined.instance;
        }
        return wrapped;
    }

    /**
     * Find the index of the correct function to call given the set of methods
     * or constructors and the arguments.
     * If no function can be found to call, return -1.
     */
    static int findFunction(Context cx,
                            MemberBox[] methodsOrCtors, Object[] args)
    {
        if (methodsOrCtors.length == 0) {
            return -1;
        } else if (methodsOrCtors.length == 1) {
            MemberBox member = methodsOrCtors[0];
            Class[] argTypes = member.argTypes;
            int alength = argTypes.length;
            
            if (member.vararg) {
                alength--;
                if ( alength > args.length) {
                    return -1;
                }
            } else {
                if (alength != args.length) {
                    return -1;
                }
            }
            for (int j = 0; j != alength; ++j) {
                if (!NativeJavaObject.canConvert(args[j], argTypes[j])) {
                    if (debug) printDebug("Rejecting (args can't convert) ",
                                          member, args);
                    return -1;
                }
            }
            if (debug) printDebug("Found ", member, args);
            return 0;
        }

        int firstBestFit = -1;
        int[] extraBestFits = null;
        int extraBestFitsCount = 0;

      search:
        for (int i = 0; i < methodsOrCtors.length; i++) {
            MemberBox member = methodsOrCtors[i];
            Class[] argTypes = member.argTypes;
            int alength = argTypes.length;
            if (member.vararg) {
                alength--;
                if ( alength > args.length) {
                    continue search;
                }
            } else {
                if (alength != args.length) {
                    continue search;
                }
            }
            for (int j = 0; j < alength; j++) {
                if (!NativeJavaObject.canConvert(args[j], argTypes[j])) {
                    if (debug) printDebug("Rejecting (args can't convert) ",
                                          member, args);
                    continue search;
                }
            }
            if (firstBestFit < 0) {
                if (debug) printDebug("Found first applicable ", member, args);
                firstBestFit = i;
            } else {
                // Compare with all currently fit methods.
                // The loop starts from -1 denoting firstBestFit and proceed
                // until extraBestFitsCount to avoid extraBestFits allocation
                // in the most common case of no ambiguity
                int betterCount = 0; // number of times member was prefered over
                                     // best fits
                int worseCount = 0;  // number of times best fits were prefered
                                     // over member
                for (int j = -1; j != extraBestFitsCount; ++j) {
                    int bestFitIndex;
                    if (j == -1) {
                        bestFitIndex = firstBestFit;
                    } else {
                        bestFitIndex = extraBestFits[j];
                    }
                    MemberBox bestFit = methodsOrCtors[bestFitIndex];
                    if (cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS) &&
                        (bestFit.member().getModifiers() & Modifier.PUBLIC) !=
                            (member.member().getModifiers() & Modifier.PUBLIC))
                    {
                        // When FEATURE_ENHANCED_JAVA_ACCESS gives us access
                        // to non-public members, continue to prefer public
                        // methods in overloading
                        if ((bestFit.member().getModifiers() & Modifier.PUBLIC) == 0)
                            ++betterCount;
                        else
                            ++worseCount;
                    } else {
                        int preference = preferSignature(args, argTypes,
                                                         member.vararg,
                                                         bestFit.argTypes,
                                                         bestFit.vararg );
                        if (preference == PREFERENCE_AMBIGUOUS) {
                            break;
                        } else if (preference == PREFERENCE_FIRST_ARG) {
                            ++betterCount;
                        } else if (preference == PREFERENCE_SECOND_ARG) {
                            ++worseCount;
                        } else {
                            if (preference != PREFERENCE_EQUAL) Kit.codeBug();
                            // This should not happen in theory
                            // but on some JVMs, Class.getMethods will return all
                            // static methods of the class hierarchy, even if
                            // a derived class's parameters match exactly.
                            // We want to call the derived class's method.
                            if (bestFit.isStatic() &&
                                bestFit.getDeclaringClass().isAssignableFrom(
                                       member.getDeclaringClass()))
                            {
                                // On some JVMs, Class.getMethods will return all
                                // static methods of the class hierarchy, even if
                                // a derived class's parameters match exactly.
                                // We want to call the derived class's method.
                                if (debug) printDebug(
                                    "Substituting (overridden static)",
                                    member, args);
                                if (j == -1) {
                                    firstBestFit = i;
                                } else {
                                    extraBestFits[j] = i;
                                }
                            } else {
                                if (debug) printDebug(
                                    "Ignoring same signature member ",
                                    member, args);
                            }
                            continue search;
                        }
                    }
                }
                if (betterCount == 1 + extraBestFitsCount) {
                    // member was prefered over all best fits
                    if (debug) printDebug(
                        "New first applicable ", member, args);
                    firstBestFit = i;
                    extraBestFitsCount = 0;
                } else if (worseCount == 1 + extraBestFitsCount) {
                    // all best fits were prefered over member, ignore it
                    if (debug) printDebug(
                        "Rejecting (all current bests better) ", member, args);
                } else {
                    // some ambiguity was present, add member to best fit set
                    if (debug) printDebug(
                        "Added to best fit set ", member, args);
                    if (extraBestFits == null) {
                        // Allocate maximum possible array
                        extraBestFits = new int[methodsOrCtors.length - 1];
                    }
                    extraBestFits[extraBestFitsCount] = i;
                    ++extraBestFitsCount;
                }
            }
        }

        if (firstBestFit < 0) {
            // Nothing was found
            return -1;
        } else if (extraBestFitsCount == 0) {
            // single best fit
            return firstBestFit;
        }

        // report remaining ambiguity
        StringBuffer buf = new StringBuffer();
        for (int j = -1; j != extraBestFitsCount; ++j) {
            int bestFitIndex;
            if (j == -1) {
                bestFitIndex = firstBestFit;
            } else {
                bestFitIndex = extraBestFits[j];
            }
            buf.append("\n    ");
            buf.append(methodsOrCtors[bestFitIndex].toJavaDeclaration());
        }

        MemberBox firstFitMember = methodsOrCtors[firstBestFit];
        String memberName = firstFitMember.getName();
        String memberClass = firstFitMember.getDeclaringClass().getName();

        if (methodsOrCtors[0].isMethod()) {
            throw Context.reportRuntimeError3(
                "msg.constructor.ambiguous",
                memberName, scriptSignature(args), buf.toString());
        } else {
            throw Context.reportRuntimeError4(
                "msg.method.ambiguous", memberClass,
                memberName, scriptSignature(args), buf.toString());
        }
    }

    /** Types are equal */
    private static final int PREFERENCE_EQUAL      = 0;
    private static final int PREFERENCE_FIRST_ARG  = 1;
    private static final int PREFERENCE_SECOND_ARG = 2;
    /** No clear "easy" conversion */
    private static final int PREFERENCE_AMBIGUOUS  = 3;

    /**
     * Determine which of two signatures is the closer fit.
     * Returns one of PREFERENCE_EQUAL, PREFERENCE_FIRST_ARG,
     * PREFERENCE_SECOND_ARG, or PREFERENCE_AMBIGUOUS.
     */
    private static int preferSignature(Object[] args, 
                                       Class[] sig1,
                                       boolean vararg1,
                                       Class[] sig2,
                                       boolean vararg2 )
    {
        int totalPreference = 0;
        for (int j = 0; j < args.length; j++) {
            Class type1 = vararg1 && j >= sig1.length ? sig1[sig1.length-1] : sig1[j];
            Class type2 = vararg2 && j >= sig1.length ? sig2[sig1.length-1] : sig2[j];
            if (type1 == type2) {
                continue;
            }
            Object arg = args[j];

            // Determine which of type1, type2 is easier to convert from arg.

            int rank1 = NativeJavaObject.getConversionWeight(arg, type1);
            int rank2 = NativeJavaObject.getConversionWeight(arg, type2);

            int preference;
            if (rank1 < rank2) {
                preference = PREFERENCE_FIRST_ARG;
            } else if (rank1 > rank2) {
                preference = PREFERENCE_SECOND_ARG;
            } else {
                // Equal ranks
                if (rank1 == NativeJavaObject.CONVERSION_NONTRIVIAL) {
                    if (type1.isAssignableFrom(type2)) {
                        preference = PREFERENCE_SECOND_ARG;
                    } else if (type2.isAssignableFrom(type1)) {
                        preference = PREFERENCE_FIRST_ARG;
                    } else {
                        preference = PREFERENCE_AMBIGUOUS;
                    }
                } else {
                    preference = PREFERENCE_AMBIGUOUS;
                }
            }

            totalPreference |= preference;

            if (totalPreference == PREFERENCE_AMBIGUOUS) {
                break;
            }
        }
        return totalPreference;
    }


    private static final boolean debug = false;

    private static void printDebug(String msg, MemberBox member,
                                   Object[] args)
    {
        if (debug) {
            StringBuffer sb = new StringBuffer();
            sb.append(" ----- ");
            sb.append(msg);
            sb.append(member.getDeclaringClass().getName());
            sb.append('.');
            if (member.isMethod()) {
                sb.append(member.getName());
            }
            sb.append(JavaMembers.liveConnectSignature(member.argTypes));
            sb.append(" for arguments (");
            sb.append(scriptSignature(args));
            sb.append(')');
            System.out.println(sb);
        }
    }

    MemberBox[] methods;
    private String functionName;
}

jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/CompilerEnvirons.java0000644000175000017500000002377211314263504034257 0ustar  jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Rhino code, released
 * May 6, 1999.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1997-1999
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Igor Bukanov, igor@fastmail.fm
 *   Bob Jervis
 *   Steve Yegge
 *
 * Alternatively, the contents of this file may be used under the terms of
 * the GNU General Public License Version 2 or later (the "GPL"), in which
 * case the provisions of the GPL are applicable instead of those above. If
 * you wish to allow use of your version of this file only under the terms of
 * the GPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replacing
 * them with the notice and other provisions required by the GPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the GPL.
 *
 * ***** END LICENSE BLOCK ***** */

package org.mozilla.javascript;

import java.util.Set;

import org.mozilla.javascript.ast.ErrorCollector;

public class CompilerEnvirons
{
    public CompilerEnvirons()
    {
        errorReporter = DefaultErrorReporter.instance;
        languageVersion = Context.VERSION_DEFAULT;
        generateDebugInfo = true;
        useDynamicScope = false;
        reservedKeywordAsIdentifier = false;
        allowMemberExprAsFunctionName = false;
        xmlAvailable = true;
        optimizationLevel = 0;
        generatingSource = true;
        strictMode = false;
        warningAsError = false;
        generateObserverCount = false;
        allowSharpComments = false;
    }

    public void initFromContext(Context cx)
    {
        setErrorReporter(cx.getErrorReporter());
        this.languageVersion = cx.getLanguageVersion();
        useDynamicScope = cx.compileFunctionsWithDynamicScopeFlag;
        generateDebugInfo = (!cx.isGeneratingDebugChanged()
                             || cx.isGeneratingDebug());
        reservedKeywordAsIdentifier
            = cx.hasFeature(Context.FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER);
        allowMemberExprAsFunctionName
            = cx.hasFeature(Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME);
        strictMode
            = cx.hasFeature(Context.FEATURE_STRICT_MODE);
        warningAsError = cx.hasFeature(Context.FEATURE_WARNING_AS_ERROR);
        xmlAvailable
            = cx.hasFeature(Context.FEATURE_E4X);

        optimizationLevel = cx.getOptimizationLevel();

        generatingSource = cx.isGeneratingSource();
        activationNames = cx.activationNames;
        
        // Observer code generation in compiled code :
        generateObserverCount = cx.generateObserverCount;
    }

    public final ErrorReporter getErrorReporter()
    {
        return errorReporter;
    }

    public void setErrorReporter(ErrorReporter errorReporter)
    {
        if (errorReporter == null) throw new IllegalArgumentException();
        this.errorReporter = errorReporter;
    }

    public final int getLanguageVersion()
    {
        return languageVersion;
    }

    public void setLanguageVersion(int languageVersion)
    {
        Context.checkLanguageVersion(languageVersion);
        this.languageVersion = languageVersion;
    }

    public final boolean isGenerateDebugInfo()
    {
        return generateDebugInfo;
    }

    public void setGenerateDebugInfo(boolean flag)
    {
        this.generateDebugInfo = flag;
    }

    public final boolean isUseDynamicScope()
    {
        return useDynamicScope;
    }

    public final boolean isReservedKeywordAsIdentifier()
    {
        return reservedKeywordAsIdentifier;
    }

    public void setReservedKeywordAsIdentifier(boolean flag)
    {
        reservedKeywordAsIdentifier = flag;
    }

    /**
     * Extension to ECMA: if 'function <name>' is not followed
     * by '(', assume <name> starts a {@code memberExpr}
     */
    public final boolean isAllowMemberExprAsFunctionName()
    {
        return allowMemberExprAsFunctionName;
    }

    public void setAllowMemberExprAsFunctionName(boolean flag)
    {
        allowMemberExprAsFunctionName = flag;
    }

    public final boolean isXmlAvailable()
    {
        return xmlAvailable;
    }

    public void setXmlAvailable(boolean flag)
    {
        xmlAvailable = flag;
    }

    public final int getOptimizationLevel()
    {
        return optimizationLevel;
    }

    public void setOptimizationLevel(int level)
    {
        Context.checkOptimizationLevel(level);
        this.optimizationLevel = level;
    }

    public final boolean isGeneratingSource()
    {
        return generatingSource;
    }

    public boolean getWarnTrailingComma() {
        return warnTrailingComma;
    }

    public void setWarnTrailingComma(boolean warn) {
        warnTrailingComma = warn;
    }

    public final boolean isStrictMode()
    {
        return strictMode;
    }

    public void setStrictMode(boolean strict)
    {
        strictMode = strict;
    }

    public final boolean reportWarningAsError()
    {
        return warningAsError;
    }

    /**
     * Specify whether or not source information should be generated.
     * 

* Without source information, evaluating the "toString" method * on JavaScript functions produces only "[native code]" for * the body of the function. * Note that code generated without source is not fully ECMA * conformant. */ public void setGeneratingSource(boolean generatingSource) { this.generatingSource = generatingSource; } /** * @return true iff code will be generated with callbacks to enable * instruction thresholds */ public boolean isGenerateObserverCount() { return generateObserverCount; } /** * Turn on or off generation of code with callbacks to * track the count of executed instructions. * Currently only affects JVM byte code generation: this slows down the * generated code, but code generated without the callbacks will not * be counted toward instruction thresholds. Rhino's interpretive * mode does instruction counting without inserting callbacks, so * there is no requirement to compile code differently. * @param generateObserverCount if true, generated code will contain * calls to accumulate an estimate of the instructions executed. */ public void setGenerateObserverCount(boolean generateObserverCount) { this.generateObserverCount = generateObserverCount; } public boolean isRecordingComments() { return recordingComments; } public void setRecordingComments(boolean record) { recordingComments = record; } public boolean isRecordingLocalJsDocComments() { return recordingLocalJsDocComments; } public void setRecordingLocalJsDocComments(boolean record) { recordingLocalJsDocComments = record; } /** * Turn on or off full error recovery. In this mode, parse errors do not * throw an exception, and the parser attempts to build a full syntax tree * from the input. Useful for IDEs and other frontends. */ public void setRecoverFromErrors(boolean recover) { recoverFromErrors = recover; } public boolean recoverFromErrors() { return recoverFromErrors; } /** * Puts the parser in "IDE" mode. This enables some slightly more expensive * computations, such as figuring out helpful error bounds. */ public void setIdeMode(boolean ide) { ideMode = ide; } public boolean isIdeMode() { return ideMode; } public Set getActivationNames() { return activationNames; } public void setActivationNames(Set activationNames) { this.activationNames = activationNames; } /** * Mozilla sources use the C preprocessor. */ public void setAllowSharpComments(boolean allow) { allowSharpComments = allow; } public boolean getAllowSharpComments() { return allowSharpComments; } /** * Returns a {@code CompilerEnvirons} suitable for using Rhino * in an IDE environment. Most features are enabled by default. * The {@link ErrorReporter} is set to an {@link ErrorCollector}. */ public static CompilerEnvirons ideEnvirons() { CompilerEnvirons env = new CompilerEnvirons(); env.setRecoverFromErrors(true); env.setRecordingComments(true); env.setStrictMode(true); env.setWarnTrailingComma(true); env.setLanguageVersion(170); env.setReservedKeywordAsIdentifier(true); env.setIdeMode(true); env.setErrorReporter(new ErrorCollector()); return env; } private ErrorReporter errorReporter; private int languageVersion; private boolean generateDebugInfo; private boolean useDynamicScope; private boolean reservedKeywordAsIdentifier; private boolean allowMemberExprAsFunctionName; private boolean xmlAvailable; private int optimizationLevel; private boolean generatingSource; private boolean strictMode; private boolean warningAsError; private boolean generateObserverCount; private boolean recordingComments; private boolean recordingLocalJsDocComments; private boolean recoverFromErrors; private boolean warnTrailingComma; private boolean ideMode; private boolean allowSharpComments; Set activationNames; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/NativeIterator.java0000644000175000017500000002277211314263504033720 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.util.Iterator; /** * This class implements iterator objects. See * http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7#Iterators * * @author Norris Boyd */ public final class NativeIterator extends IdScriptableObject { private static final long serialVersionUID = -4136968203581667681L; private static final Object ITERATOR_TAG = "Iterator"; static void init(ScriptableObject scope, boolean sealed) { // Iterator NativeIterator iterator = new NativeIterator(); iterator.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed); // Generator NativeGenerator.init(scope, sealed); // StopIteration NativeObject obj = new StopIteration(); obj.setPrototype(getObjectPrototype(scope)); obj.setParentScope(scope); if (sealed) { obj.sealObject(); } ScriptableObject.defineProperty(scope, STOP_ITERATION, obj, ScriptableObject.DONTENUM); // Use "associateValue" so that generators can continue to // throw StopIteration even if the property of the global // scope is replaced or deleted. scope.associateValue(ITERATOR_TAG, obj); } /** * Only for constructing the prototype object. */ private NativeIterator() { } private NativeIterator(Object objectIterator) { this.objectIterator = objectIterator; } /** * Get the value of the "StopIteration" object. Note that this value * is stored in the top-level scope using "associateValue" so the * value can still be found even if a script overwrites or deletes * the global "StopIteration" property. * @param scope a scope whose parent chain reaches a top-level scope * @return the StopIteration object */ public static Object getStopIterationObject(Scriptable scope) { Scriptable top = ScriptableObject.getTopLevelScope(scope); return ScriptableObject.getTopScopeValue(top, ITERATOR_TAG); } private static final String STOP_ITERATION = "StopIteration"; public static final String ITERATOR_PROPERTY_NAME = "__iterator__"; static class StopIteration extends NativeObject { private static final long serialVersionUID = 2485151085722377663L; @Override public String getClassName() { return STOP_ITERATION; } /* StopIteration has custom instanceof behavior since it * doesn't have a constructor. */ @Override public boolean hasInstance(Scriptable instance) { return instance instanceof StopIteration; } } @Override public String getClassName() { return "Iterator"; } @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=2; s="constructor"; break; case Id_next: arity=0; s="next"; break; case Id___iterator__: arity=1; s=ITERATOR_PROPERTY_NAME; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(ITERATOR_TAG, id, s, arity); } @Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(ITERATOR_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); if (id == Id_constructor) { return jsConstructor(cx, scope, thisObj, args); } if (!(thisObj instanceof NativeIterator)) throw incompatibleCallError(f); NativeIterator iterator = (NativeIterator) thisObj; switch (id) { case Id_next: return iterator.next(cx, scope); case Id___iterator__: /// XXX: what about argument? SpiderMonkey apparently ignores it return thisObj; default: throw new IllegalArgumentException(String.valueOf(id)); } } /* The JavaScript constructor */ private static Object jsConstructor(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (args.length == 0 || args[0] == null || args[0] == Undefined.instance) { throw ScriptRuntime.typeError1("msg.no.properties", ScriptRuntime.toString(args[0])); } Scriptable obj = ScriptRuntime.toObject(scope, args[0]); boolean keyOnly = args.length > 1 && ScriptRuntime.toBoolean(args[1]); if (thisObj != null) { // Called as a function. Convert to iterator if possible. // For objects that implement java.lang.Iterable or // java.util.Iterator, have JavaScript Iterator call the underlying // iteration methods Iterator iterator = VMBridge.instance.getJavaIterator(cx, scope, obj); if (iterator != null) { scope = ScriptableObject.getTopLevelScope(scope); return cx.getWrapFactory().wrap(cx, scope, new WrappedJavaIterator(iterator, scope), WrappedJavaIterator.class); } // Otherwise, just call the runtime routine Scriptable jsIterator = ScriptRuntime.toIterator(cx, scope, obj, keyOnly); if (jsIterator != null) { return jsIterator; } } // Otherwise, just set up to iterate over the properties of the object. // Do not call __iterator__ method. Object objectIterator = ScriptRuntime.enumInit(obj, cx, keyOnly ? ScriptRuntime.ENUMERATE_KEYS_NO_ITERATOR : ScriptRuntime.ENUMERATE_ARRAY_NO_ITERATOR); ScriptRuntime.setEnumNumbers(objectIterator, true); NativeIterator result = new NativeIterator(objectIterator); result.setPrototype(ScriptableObject.getClassPrototype(scope, result.getClassName())); result.setParentScope(scope); return result; } private Object next(Context cx, Scriptable scope) { Boolean b = ScriptRuntime.enumNext(this.objectIterator); if (!b.booleanValue()) { // Out of values. Throw StopIteration. throw new JavaScriptException( NativeIterator.getStopIterationObject(scope), null, 0); } return ScriptRuntime.enumId(this.objectIterator, cx); } static public class WrappedJavaIterator { WrappedJavaIterator(Iterator iterator, Scriptable scope) { this.iterator = iterator; this.scope = scope; } public Object next() { if (!iterator.hasNext()) { // Out of values. Throw StopIteration. throw new JavaScriptException( NativeIterator.getStopIterationObject(scope), null, 0); } return iterator.next(); } public Object __iterator__(boolean b) { return this; } private Iterator iterator; private Scriptable scope; } // #string_id_map# @Override protected int findPrototypeId(String s) { int id; // #generated# Last update: 2007-06-11 09:43:19 EDT L0: { id = 0; String X = null; int s_length = s.length(); if (s_length==4) { X="next";id=Id_next; } else if (s_length==11) { X="constructor";id=Id_constructor; } else if (s_length==12) { X="__iterator__";id=Id___iterator__; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# return id; } private static final int Id_constructor = 1, Id_next = 2, Id___iterator__ = 3, MAX_PROTOTYPE_ID = 3; // #/string_id_map# private Object objectIterator; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/PolicySecurityController.java0000644000175000017500000002104211314263504036000 0ustar jamespagejamespage00000000000000/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.lang.ref.SoftReference; import java.lang.reflect.UndeclaredThrowableException; import java.security.AccessController; import java.security.CodeSource; import java.security.Policy; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.SecureClassLoader; import java.util.Map; import java.util.WeakHashMap; import org.mozilla.classfile.ByteCode; import org.mozilla.classfile.ClassFileWriter; /** * A security controller relying on Java {@link Policy} in effect. When you use * this security controller, your securityDomain objects must be instances of * {@link CodeSource} representing the location from where you load your * scripts. Any Java policy "grant" statements matching the URL and certificate * in code sources will apply to the scripts. If you specify any certificates * within your {@link CodeSource} objects, it is your responsibility to verify * (or not) that the script source files are signed in whatever * implementation-specific way you're using. * @author Attila Szegedi */ public class PolicySecurityController extends SecurityController { private static final byte[] secureCallerImplBytecode = loadBytecode(); // We're storing a CodeSource -> (ClassLoader -> SecureRenderer), since we // need to have one renderer per class loader. We're using weak hash maps // and soft references all the way, since we don't want to interfere with // cleanup of either CodeSource or ClassLoader objects. private static final Map>> callers = new WeakHashMap>>(); @Override public Class getStaticSecurityDomainClassInternal() { return CodeSource.class; } private static class Loader extends SecureClassLoader implements GeneratedClassLoader { private final CodeSource codeSource; Loader(ClassLoader parent, CodeSource codeSource) { super(parent); this.codeSource = codeSource; } public Class defineClass(String name, byte[] data) { return defineClass(name, data, 0, data.length, codeSource); } public void linkClass(Class cl) { resolveClass(cl); } } @Override public GeneratedClassLoader createClassLoader(final ClassLoader parent, final Object securityDomain) { return (Loader)AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return new Loader(parent, (CodeSource)securityDomain); } }); } @Override public Object getDynamicSecurityDomain(Object securityDomain) { // No separate notion of dynamic security domain - just return what was // passed in. return securityDomain; } @Override public Object callWithDomain(final Object securityDomain, final Context cx, Callable callable, Scriptable scope, Scriptable thisObj, Object[] args) { // Run in doPrivileged as we might be checked for "getClassLoader" // runtime permission final ClassLoader classLoader = (ClassLoader)AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return cx.getApplicationClassLoader(); } }); final CodeSource codeSource = (CodeSource)securityDomain; Map> classLoaderMap; synchronized (callers) { classLoaderMap = callers.get(codeSource); if(classLoaderMap == null) { classLoaderMap = new WeakHashMap>(); callers.put(codeSource, classLoaderMap); } } SecureCaller caller; synchronized (classLoaderMap) { SoftReference ref = classLoaderMap.get(classLoader); if (ref != null) { caller = ref.get(); } else { caller = null; } if (caller == null) { try { // Run in doPrivileged as we'll be checked for // "createClassLoader" runtime permission caller = (SecureCaller)AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws Exception { Loader loader = new Loader(classLoader, codeSource); Class c = loader.defineClass( SecureCaller.class.getName() + "Impl", secureCallerImplBytecode); return c.newInstance(); } }); classLoaderMap.put(classLoader, new SoftReference(caller)); } catch(PrivilegedActionException ex) { throw new UndeclaredThrowableException(ex.getCause()); } } } return caller.call(callable, cx, scope, thisObj, args); } public abstract static class SecureCaller { public abstract Object call(Callable callable, Context cx, Scriptable scope, Scriptable thisObj, Object[] args); } private static byte[] loadBytecode() { String secureCallerClassName = SecureCaller.class.getName(); ClassFileWriter cfw = new ClassFileWriter( secureCallerClassName + "Impl", secureCallerClassName, ""); cfw.startMethod("", "()V", ClassFileWriter.ACC_PUBLIC); cfw.addALoad(0); cfw.addInvoke(ByteCode.INVOKESPECIAL, secureCallerClassName, "", "()V"); cfw.add(ByteCode.RETURN); cfw.stopMethod((short)1); String callableCallSig = "Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "Lorg/mozilla/javascript/Scriptable;" + "[Ljava/lang/Object;)Ljava/lang/Object;"; cfw.startMethod("call", "(Lorg/mozilla/javascript/Callable;" + callableCallSig, (short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); for(int i = 1; i < 6; ++i) { cfw.addALoad(i); } cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/Callable", "call", "(" + callableCallSig); cfw.add(ByteCode.ARETURN); cfw.stopMethod((short)6); return cfw.toByteArray(); } }jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/EcmaError.java0000644000175000017500000001146511314263504032634 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Roger Lawrence * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; /** * The class of exceptions raised by the engine as described in * ECMA edition 3. See section 15.11.6 in particular. */ public class EcmaError extends RhinoException { static final long serialVersionUID = -6261226256957286699L; private String errorName; private String errorMessage; /** * Create an exception with the specified detail message. * * Errors internal to the JavaScript engine will simply throw a * RuntimeException. * * @param sourceName the name of the source responsible for the error * @param lineNumber the line number of the source * @param columnNumber the columnNumber of the source (may be zero if * unknown) * @param lineSource the source of the line containing the error (may be * null if unknown) */ EcmaError(String errorName, String errorMessage, String sourceName, int lineNumber, String lineSource, int columnNumber) { recordErrorOrigin(sourceName, lineNumber, lineSource, columnNumber); this.errorName = errorName; this.errorMessage = errorMessage; } /** * @deprecated EcmaError error instances should not be constructed * explicitly since they are generated by the engine. */ public EcmaError(Scriptable nativeError, String sourceName, int lineNumber, int columnNumber, String lineSource) { this("InternalError", ScriptRuntime.toString(nativeError), sourceName, lineNumber, lineSource, columnNumber); } @Override public String details() { return errorName+": "+errorMessage; } /** * Gets the name of the error. * * ECMA edition 3 defines the following * errors: EvalError, RangeError, ReferenceError, * SyntaxError, TypeError, and URIError. Additional error names * may be added in the future. * * See ECMA edition 3, 15.11.7.9. * * @return the name of the error. */ public String getName() { return errorName; } /** * Gets the message corresponding to the error. * * See ECMA edition 3, 15.11.7.10. * * @return an implementation-defined string describing the error. */ public String getErrorMessage() { return errorMessage; } /** * @deprecated Use {@link RhinoException#sourceName()} from the super class. */ public String getSourceName() { return sourceName(); } /** * @deprecated Use {@link RhinoException#lineNumber()} from the super class. */ public int getLineNumber() { return lineNumber(); } /** * @deprecated * Use {@link RhinoException#columnNumber()} from the super class. */ public int getColumnNumber() { return columnNumber(); } /** * @deprecated Use {@link RhinoException#lineSource()} from the super class. */ public String getLineSource() { return lineSource(); } /** * @deprecated * Always returns null. */ public Scriptable getErrorObject() { return null; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/jdk15/0000755000175000017500000000000011537630013031021 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/jdk15/VMBridge_jdk15.java0000644000175000017500000000675511314263504034336 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.jdk15; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import java.util.Iterator; import org.mozilla.javascript.*; public class VMBridge_jdk15 extends org.mozilla.javascript.jdk13.VMBridge_jdk13 { public VMBridge_jdk15() throws SecurityException, InstantiationException { try { // Just try and see if we can access the isVarArgs method. // We want to fail loading if the method does not exist // so that we can load a bridge to an older JDK instead. Method.class.getMethod("isVarArgs", (Class[]) null); } catch (NoSuchMethodException e) { // Throw a fitting exception that is handled by // org.mozilla.javascript.Kit.newInstanceOrNull: throw new InstantiationException(e.getMessage()); } } @Override public boolean isVarArgs(Member member) { if (member instanceof Method) return ((Method) member).isVarArgs(); else if (member instanceof Constructor) return ((Constructor) member).isVarArgs(); else return false; } /** * If "obj" is a java.util.Iterator or a java.lang.Iterable, return a * wrapping as a JavaScript Iterator. Otherwise, return null. * This method is in VMBridge since Iterable is a JDK 1.5 addition. */ @Override public Iterator getJavaIterator(Context cx, Scriptable scope, Object obj) { if (obj instanceof Wrapper) { Object unwrapped = ((Wrapper) obj).unwrap(); Iterator iterator = null; if (unwrapped instanceof Iterator) iterator = (Iterator) unwrapped; if (unwrapped instanceof Iterable) iterator = ((Iterable)unwrapped).iterator(); return iterator; } return null; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/NativeDate.java0000644000175000017500000015555611314263504033013 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Peter Annema * Norris Boyd * Mike McCabe * Ilya Frank * * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.util.Date; import java.text.DateFormat; /** * This class implements the Date native object. * See ECMA 15.9. * @author Mike McCabe */ final class NativeDate extends IdScriptableObject { static final long serialVersionUID = -8307438915861678966L; private static final Object DATE_TAG = "Date"; private static final String js_NaN_date_str = "Invalid Date"; static void init(Scriptable scope, boolean sealed) { NativeDate obj = new NativeDate(); // Set the value of the prototype Date to NaN ('invalid date'); obj.date = ScriptRuntime.NaN; obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed); } private NativeDate() { if (thisTimeZone == null) { // j.u.TimeZone is synchronized, so setting class statics from it // should be OK. thisTimeZone = java.util.TimeZone.getDefault(); LocalTZA = thisTimeZone.getRawOffset(); } } @Override public String getClassName() { return "Date"; } @Override public Object getDefaultValue(Class typeHint) { if (typeHint == null) typeHint = ScriptRuntime.StringClass; return super.getDefaultValue(typeHint); } double getJSTimeValue() { return date; } @Override protected void fillConstructorProperties(IdFunctionObject ctor) { addIdFunctionProperty(ctor, DATE_TAG, ConstructorId_now, "now", 0); addIdFunctionProperty(ctor, DATE_TAG, ConstructorId_parse, "parse", 1); addIdFunctionProperty(ctor, DATE_TAG, ConstructorId_UTC, "UTC", 1); super.fillConstructorProperties(ctor); } @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=1; s="constructor"; break; case Id_toString: arity=0; s="toString"; break; case Id_toTimeString: arity=0; s="toTimeString"; break; case Id_toDateString: arity=0; s="toDateString"; break; case Id_toLocaleString: arity=0; s="toLocaleString"; break; case Id_toLocaleTimeString: arity=0; s="toLocaleTimeString"; break; case Id_toLocaleDateString: arity=0; s="toLocaleDateString"; break; case Id_toUTCString: arity=0; s="toUTCString"; break; case Id_toSource: arity=0; s="toSource"; break; case Id_valueOf: arity=0; s="valueOf"; break; case Id_getTime: arity=0; s="getTime"; break; case Id_getYear: arity=0; s="getYear"; break; case Id_getFullYear: arity=0; s="getFullYear"; break; case Id_getUTCFullYear: arity=0; s="getUTCFullYear"; break; case Id_getMonth: arity=0; s="getMonth"; break; case Id_getUTCMonth: arity=0; s="getUTCMonth"; break; case Id_getDate: arity=0; s="getDate"; break; case Id_getUTCDate: arity=0; s="getUTCDate"; break; case Id_getDay: arity=0; s="getDay"; break; case Id_getUTCDay: arity=0; s="getUTCDay"; break; case Id_getHours: arity=0; s="getHours"; break; case Id_getUTCHours: arity=0; s="getUTCHours"; break; case Id_getMinutes: arity=0; s="getMinutes"; break; case Id_getUTCMinutes: arity=0; s="getUTCMinutes"; break; case Id_getSeconds: arity=0; s="getSeconds"; break; case Id_getUTCSeconds: arity=0; s="getUTCSeconds"; break; case Id_getMilliseconds: arity=0; s="getMilliseconds"; break; case Id_getUTCMilliseconds: arity=0; s="getUTCMilliseconds"; break; case Id_getTimezoneOffset: arity=0; s="getTimezoneOffset"; break; case Id_setTime: arity=1; s="setTime"; break; case Id_setMilliseconds: arity=1; s="setMilliseconds"; break; case Id_setUTCMilliseconds: arity=1; s="setUTCMilliseconds"; break; case Id_setSeconds: arity=2; s="setSeconds"; break; case Id_setUTCSeconds: arity=2; s="setUTCSeconds"; break; case Id_setMinutes: arity=3; s="setMinutes"; break; case Id_setUTCMinutes: arity=3; s="setUTCMinutes"; break; case Id_setHours: arity=4; s="setHours"; break; case Id_setUTCHours: arity=4; s="setUTCHours"; break; case Id_setDate: arity=1; s="setDate"; break; case Id_setUTCDate: arity=1; s="setUTCDate"; break; case Id_setMonth: arity=2; s="setMonth"; break; case Id_setUTCMonth: arity=2; s="setUTCMonth"; break; case Id_setFullYear: arity=3; s="setFullYear"; break; case Id_setUTCFullYear: arity=3; s="setUTCFullYear"; break; case Id_setYear: arity=1; s="setYear"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(DATE_TAG, id, s, arity); } @Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(DATE_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); switch (id) { case ConstructorId_now: return ScriptRuntime.wrapNumber(now()); case ConstructorId_parse: { String dataStr = ScriptRuntime.toString(args, 0); return ScriptRuntime.wrapNumber(date_parseString(dataStr)); } case ConstructorId_UTC: return ScriptRuntime.wrapNumber(jsStaticFunction_UTC(args)); case Id_constructor: { // if called as a function, just return a string // representing the current time. if (thisObj != null) return date_format(now(), Id_toString); return jsConstructor(args); } } // The rest of Date.prototype methods require thisObj to be Date if (!(thisObj instanceof NativeDate)) throw incompatibleCallError(f); NativeDate realThis = (NativeDate)thisObj; double t = realThis.date; switch (id) { case Id_toString: case Id_toTimeString: case Id_toDateString: if (t == t) { return date_format(t, id); } return js_NaN_date_str; case Id_toLocaleString: case Id_toLocaleTimeString: case Id_toLocaleDateString: if (t == t) { return toLocale_helper(t, id); } return js_NaN_date_str; case Id_toUTCString: if (t == t) { return js_toUTCString(t); } return js_NaN_date_str; case Id_toSource: return "(new Date("+ScriptRuntime.toString(t)+"))"; case Id_valueOf: case Id_getTime: return ScriptRuntime.wrapNumber(t); case Id_getYear: case Id_getFullYear: case Id_getUTCFullYear: if (t == t) { if (id != Id_getUTCFullYear) t = LocalTime(t); t = YearFromTime(t); if (id == Id_getYear) { if (cx.hasFeature(Context.FEATURE_NON_ECMA_GET_YEAR)) { if (1900 <= t && t < 2000) { t -= 1900; } } else { t -= 1900; } } } return ScriptRuntime.wrapNumber(t); case Id_getMonth: case Id_getUTCMonth: if (t == t) { if (id == Id_getMonth) t = LocalTime(t); t = MonthFromTime(t); } return ScriptRuntime.wrapNumber(t); case Id_getDate: case Id_getUTCDate: if (t == t) { if (id == Id_getDate) t = LocalTime(t); t = DateFromTime(t); } return ScriptRuntime.wrapNumber(t); case Id_getDay: case Id_getUTCDay: if (t == t) { if (id == Id_getDay) t = LocalTime(t); t = WeekDay(t); } return ScriptRuntime.wrapNumber(t); case Id_getHours: case Id_getUTCHours: if (t == t) { if (id == Id_getHours) t = LocalTime(t); t = HourFromTime(t); } return ScriptRuntime.wrapNumber(t); case Id_getMinutes: case Id_getUTCMinutes: if (t == t) { if (id == Id_getMinutes) t = LocalTime(t); t = MinFromTime(t); } return ScriptRuntime.wrapNumber(t); case Id_getSeconds: case Id_getUTCSeconds: if (t == t) { if (id == Id_getSeconds) t = LocalTime(t); t = SecFromTime(t); } return ScriptRuntime.wrapNumber(t); case Id_getMilliseconds: case Id_getUTCMilliseconds: if (t == t) { if (id == Id_getMilliseconds) t = LocalTime(t); t = msFromTime(t); } return ScriptRuntime.wrapNumber(t); case Id_getTimezoneOffset: if (t == t) { t = (t - LocalTime(t)) / msPerMinute; } return ScriptRuntime.wrapNumber(t); case Id_setTime: t = TimeClip(ScriptRuntime.toNumber(args, 0)); realThis.date = t; return ScriptRuntime.wrapNumber(t); case Id_setMilliseconds: case Id_setUTCMilliseconds: case Id_setSeconds: case Id_setUTCSeconds: case Id_setMinutes: case Id_setUTCMinutes: case Id_setHours: case Id_setUTCHours: t = makeTime(t, args, id); realThis.date = t; return ScriptRuntime.wrapNumber(t); case Id_setDate: case Id_setUTCDate: case Id_setMonth: case Id_setUTCMonth: case Id_setFullYear: case Id_setUTCFullYear: t = makeDate(t, args, id); realThis.date = t; return ScriptRuntime.wrapNumber(t); case Id_setYear: { double year = ScriptRuntime.toNumber(args, 0); if (year != year || Double.isInfinite(year)) { t = ScriptRuntime.NaN; } else { if (t != t) { t = 0; } else { t = LocalTime(t); } if (year >= 0 && year <= 99) year += 1900; double day = MakeDay(year, MonthFromTime(t), DateFromTime(t)); t = MakeDate(day, TimeWithinDay(t)); t = internalUTC(t); t = TimeClip(t); } } realThis.date = t; return ScriptRuntime.wrapNumber(t); default: throw new IllegalArgumentException(String.valueOf(id)); } } /* ECMA helper functions */ private static final double HalfTimeDomain = 8.64e15; private static final double HoursPerDay = 24.0; private static final double MinutesPerHour = 60.0; private static final double SecondsPerMinute = 60.0; private static final double msPerSecond = 1000.0; private static final double MinutesPerDay = (HoursPerDay * MinutesPerHour); private static final double SecondsPerDay = (MinutesPerDay * SecondsPerMinute); private static final double SecondsPerHour = (MinutesPerHour * SecondsPerMinute); private static final double msPerDay = (SecondsPerDay * msPerSecond); private static final double msPerHour = (SecondsPerHour * msPerSecond); private static final double msPerMinute = (SecondsPerMinute * msPerSecond); private static double Day(double t) { return Math.floor(t / msPerDay); } private static double TimeWithinDay(double t) { double result; result = t % msPerDay; if (result < 0) result += msPerDay; return result; } private static boolean IsLeapYear(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } /* math here has to be f.p, because we need * floor((1968 - 1969) / 4) == -1 */ private static double DayFromYear(double y) { return ((365 * ((y)-1970) + Math.floor(((y)-1969)/4.0) - Math.floor(((y)-1901)/100.0) + Math.floor(((y)-1601)/400.0))); } private static double TimeFromYear(double y) { return DayFromYear(y) * msPerDay; } private static int YearFromTime(double t) { int lo = (int) Math.floor((t / msPerDay) / 366) + 1970; int hi = (int) Math.floor((t / msPerDay) / 365) + 1970; int mid; /* above doesn't work for negative dates... */ if (hi < lo) { int temp = lo; lo = hi; hi = temp; } /* Use a simple binary search algorithm to find the right year. This seems like brute force... but the computation of hi and lo years above lands within one year of the correct answer for years within a thousand years of 1970; the loop below only requires six iterations for year 270000. */ while (hi > lo) { mid = (hi + lo) / 2; if (TimeFromYear(mid) > t) { hi = mid - 1; } else { lo = mid + 1; if (TimeFromYear(lo) > t) { return mid; } } } return lo; } private static double DayFromMonth(int m, int year) { int day = m * 30; if (m >= 7) { day += m / 2 - 1; } else if (m >= 2) { day += (m - 1) / 2 - 1; } else { day += m; } if (m >= 2 && IsLeapYear(year)) { ++day; } return day; } private static int MonthFromTime(double t) { int year = YearFromTime(t); int d = (int)(Day(t) - DayFromYear(year)); d -= 31 + 28; if (d < 0) { return (d < -28) ? 0 : 1; } if (IsLeapYear(year)) { if (d == 0) return 1; // 29 February --d; } // d: date count from 1 March int estimate = d / 30; // approx number of month since March int mstart; switch (estimate) { case 0: return 2; case 1: mstart = 31; break; case 2: mstart = 31+30; break; case 3: mstart = 31+30+31; break; case 4: mstart = 31+30+31+30; break; case 5: mstart = 31+30+31+30+31; break; case 6: mstart = 31+30+31+30+31+31; break; case 7: mstart = 31+30+31+30+31+31+30; break; case 8: mstart = 31+30+31+30+31+31+30+31; break; case 9: mstart = 31+30+31+30+31+31+30+31+30; break; case 10: return 11; //Late december default: throw Kit.codeBug(); } // if d < mstart then real month since March == estimate - 1 return (d >= mstart) ? estimate + 2 : estimate + 1; } private static int DateFromTime(double t) { int year = YearFromTime(t); int d = (int)(Day(t) - DayFromYear(year)); d -= 31 + 28; if (d < 0) { return (d < -28) ? d + 31 + 28 + 1 : d + 28 + 1; } if (IsLeapYear(year)) { if (d == 0) return 29; // 29 February --d; } // d: date count from 1 March int mdays, mstart; switch (d / 30) { // approx number of month since March case 0: return d + 1; case 1: mdays = 31; mstart = 31; break; case 2: mdays = 30; mstart = 31+30; break; case 3: mdays = 31; mstart = 31+30+31; break; case 4: mdays = 30; mstart = 31+30+31+30; break; case 5: mdays = 31; mstart = 31+30+31+30+31; break; case 6: mdays = 31; mstart = 31+30+31+30+31+31; break; case 7: mdays = 30; mstart = 31+30+31+30+31+31+30; break; case 8: mdays = 31; mstart = 31+30+31+30+31+31+30+31; break; case 9: mdays = 30; mstart = 31+30+31+30+31+31+30+31+30; break; case 10: return d - (31+30+31+30+31+31+30+31+30) + 1; //Late december default: throw Kit.codeBug(); } d -= mstart; if (d < 0) { // wrong estimate: sfhift to previous month d += mdays; } return d + 1; } private static int WeekDay(double t) { double result; result = Day(t) + 4; result = result % 7; if (result < 0) result += 7; return (int) result; } private static double now() { return System.currentTimeMillis(); } /* Should be possible to determine the need for this dynamically * if we go with the workaround... I'm not using it now, because I * can't think of any clean way to make toLocaleString() and the * time zone (comment) in toString match the generated string * values. Currently it's wrong-but-consistent in all but the * most recent betas of the JRE - seems to work in 1.1.7. */ private final static boolean TZO_WORKAROUND = false; private static double DaylightSavingTA(double t) { // Another workaround! The JRE doesn't seem to know about DST // before year 1 AD, so we map to equivalent dates for the // purposes of finding dst. To be safe, we do this for years // outside 1970-2038. if (t < 0.0 || t > 2145916800000.0) { int year = EquivalentYear(YearFromTime(t)); double day = MakeDay(year, MonthFromTime(t), DateFromTime(t)); t = MakeDate(day, TimeWithinDay(t)); } if (!TZO_WORKAROUND) { Date date = new Date((long) t); if (thisTimeZone.inDaylightTime(date)) return msPerHour; else return 0; } else { /* Use getOffset if inDaylightTime() is broken, because it * seems to work acceptably. We don't switch over to it * entirely, because it requires (expensive) exploded date arguments, * and the api makes it impossible to handle dst * changeovers cleanly. */ // Hardcode the assumption that the changeover always // happens at 2:00 AM: t += LocalTZA + (HourFromTime(t) <= 2 ? msPerHour : 0); int year = YearFromTime(t); double offset = thisTimeZone.getOffset(year > 0 ? 1 : 0, year, MonthFromTime(t), DateFromTime(t), WeekDay(t), (int)TimeWithinDay(t)); if ((offset - LocalTZA) != 0) return msPerHour; else return 0; // return offset - LocalTZA; } } /* * Find a year for which any given date will fall on the same weekday. * * This function should be used with caution when used other than * for determining DST; it hasn't been proven not to produce an * incorrect year for times near year boundaries. */ private static int EquivalentYear(int year) { int day = (int) DayFromYear(year) + 4; day = day % 7; if (day < 0) day += 7; // Years and leap years on which Jan 1 is a Sunday, Monday, etc. if (IsLeapYear(year)) { switch (day) { case 0: return 1984; case 1: return 1996; case 2: return 1980; case 3: return 1992; case 4: return 1976; case 5: return 1988; case 6: return 1972; } } else { switch (day) { case 0: return 1978; case 1: return 1973; case 2: return 1974; case 3: return 1975; case 4: return 1981; case 5: return 1971; case 6: return 1977; } } // Unreachable throw Kit.codeBug(); } private static double LocalTime(double t) { return t + LocalTZA + DaylightSavingTA(t); } private static double internalUTC(double t) { return t - LocalTZA - DaylightSavingTA(t - LocalTZA); } private static int HourFromTime(double t) { double result; result = Math.floor(t / msPerHour) % HoursPerDay; if (result < 0) result += HoursPerDay; return (int) result; } private static int MinFromTime(double t) { double result; result = Math.floor(t / msPerMinute) % MinutesPerHour; if (result < 0) result += MinutesPerHour; return (int) result; } private static int SecFromTime(double t) { double result; result = Math.floor(t / msPerSecond) % SecondsPerMinute; if (result < 0) result += SecondsPerMinute; return (int) result; } private static int msFromTime(double t) { double result; result = t % msPerSecond; if (result < 0) result += msPerSecond; return (int) result; } private static double MakeTime(double hour, double min, double sec, double ms) { return ((hour * MinutesPerHour + min) * SecondsPerMinute + sec) * msPerSecond + ms; } private static double MakeDay(double year, double month, double date) { year += Math.floor(month / 12); month = month % 12; if (month < 0) month += 12; double yearday = Math.floor(TimeFromYear(year) / msPerDay); double monthday = DayFromMonth((int)month, (int)year); return yearday + monthday + date - 1; } private static double MakeDate(double day, double time) { return day * msPerDay + time; } private static double TimeClip(double d) { if (d != d || d == Double.POSITIVE_INFINITY || d == Double.NEGATIVE_INFINITY || Math.abs(d) > HalfTimeDomain) { return ScriptRuntime.NaN; } if (d > 0.0) return Math.floor(d + 0.); else return Math.ceil(d + 0.); } /* end of ECMA helper functions */ /* find UTC time from given date... no 1900 correction! */ private static double date_msecFromDate(double year, double mon, double mday, double hour, double min, double sec, double msec) { double day; double time; double result; day = MakeDay(year, mon, mday); time = MakeTime(hour, min, sec, msec); result = MakeDate(day, time); return result; } /* compute the time in msec (unclipped) from the given args */ private static final int MAXARGS = 7; private static double date_msecFromArgs(Object[] args) { double array[] = new double[MAXARGS]; int loop; double d; for (loop = 0; loop < MAXARGS; loop++) { if (loop < args.length) { d = ScriptRuntime.toNumber(args[loop]); if (d != d || Double.isInfinite(d)) { return ScriptRuntime.NaN; } array[loop] = ScriptRuntime.toInteger(args[loop]); } else { if (loop == 2) { array[loop] = 1; /* Default the date argument to 1. */ } else { array[loop] = 0; } } } /* adjust 2-digit years into the 20th century */ if (array[0] >= 0 && array[0] <= 99) array[0] += 1900; return date_msecFromDate(array[0], array[1], array[2], array[3], array[4], array[5], array[6]); } private static double jsStaticFunction_UTC(Object[] args) { return TimeClip(date_msecFromArgs(args)); } private static double date_parseString(String s) { int year = -1; int mon = -1; int mday = -1; int hour = -1; int min = -1; int sec = -1; char c = 0; char si = 0; int i = 0; int n = -1; double tzoffset = -1; char prevc = 0; int limit = 0; boolean seenplusminus = false; limit = s.length(); while (i < limit) { c = s.charAt(i); i++; if (c <= ' ' || c == ',' || c == '-') { if (i < limit) { si = s.charAt(i); if (c == '-' && '0' <= si && si <= '9') { prevc = c; } } continue; } if (c == '(') { /* comments) */ int depth = 1; while (i < limit) { c = s.charAt(i); i++; if (c == '(') depth++; else if (c == ')') if (--depth <= 0) break; } continue; } if ('0' <= c && c <= '9') { n = c - '0'; while (i < limit && '0' <= (c = s.charAt(i)) && c <= '9') { n = n * 10 + c - '0'; i++; } /* allow TZA before the year, so * 'Wed Nov 05 21:49:11 GMT-0800 1997' * works */ /* uses of seenplusminus allow : in TZA, so Java * no-timezone style of GMT+4:30 works */ if ((prevc == '+' || prevc == '-')/* && year>=0 */) { /* make ':' case below change tzoffset */ seenplusminus = true; /* offset */ if (n < 24) n = n * 60; /* EG. "GMT-3" */ else n = n % 100 + n / 100 * 60; /* eg "GMT-0430" */ if (prevc == '+') /* plus means east of GMT */ n = -n; if (tzoffset != 0 && tzoffset != -1) return ScriptRuntime.NaN; tzoffset = n; } else if (n >= 70 || (prevc == '/' && mon >= 0 && mday >= 0 && year < 0)) { if (year >= 0) return ScriptRuntime.NaN; else if (c <= ' ' || c == ',' || c == '/' || i >= limit) year = n < 100 ? n + 1900 : n; else return ScriptRuntime.NaN; } else if (c == ':') { if (hour < 0) hour = /*byte*/ n; else if (min < 0) min = /*byte*/ n; else return ScriptRuntime.NaN; } else if (c == '/') { if (mon < 0) mon = /*byte*/ n-1; else if (mday < 0) mday = /*byte*/ n; else return ScriptRuntime.NaN; } else if (i < limit && c != ',' && c > ' ' && c != '-') { return ScriptRuntime.NaN; } else if (seenplusminus && n < 60) { /* handle GMT-3:30 */ if (tzoffset < 0) tzoffset -= n; else tzoffset += n; } else if (hour >= 0 && min < 0) { min = /*byte*/ n; } else if (min >= 0 && sec < 0) { sec = /*byte*/ n; } else if (mday < 0) { mday = /*byte*/ n; } else { return ScriptRuntime.NaN; } prevc = 0; } else if (c == '/' || c == ':' || c == '+' || c == '-') { prevc = c; } else { int st = i - 1; while (i < limit) { c = s.charAt(i); if (!(('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))) break; i++; } int letterCount = i - st; if (letterCount < 2) return ScriptRuntime.NaN; /* * Use ported code from jsdate.c rather than the locale-specific * date-parsing code from Java, to keep js and rhino consistent. * Is this the right strategy? */ String wtb = "am;pm;" +"monday;tuesday;wednesday;thursday;friday;" +"saturday;sunday;" +"january;february;march;april;may;june;" +"july;august;september;october;november;december;" +"gmt;ut;utc;est;edt;cst;cdt;mst;mdt;pst;pdt;"; int index = 0; for (int wtbOffset = 0; ;) { int wtbNext = wtb.indexOf(';', wtbOffset); if (wtbNext < 0) return ScriptRuntime.NaN; if (wtb.regionMatches(true, wtbOffset, s, st, letterCount)) break; wtbOffset = wtbNext + 1; ++index; } if (index < 2) { /* * AM/PM. Count 12:30 AM as 00:30, 12:30 PM as * 12:30, instead of blindly adding 12 if PM. */ if (hour > 12 || hour < 0) { return ScriptRuntime.NaN; } else if (index == 0) { // AM if (hour == 12) hour = 0; } else { // PM if (hour != 12) hour += 12; } } else if ((index -= 2) < 7) { // ignore week days } else if ((index -= 7) < 12) { // month if (mon < 0) { mon = index; } else { return ScriptRuntime.NaN; } } else { index -= 12; // timezones switch (index) { case 0 /* gmt */: tzoffset = 0; break; case 1 /* ut */: tzoffset = 0; break; case 2 /* utc */: tzoffset = 0; break; case 3 /* est */: tzoffset = 5 * 60; break; case 4 /* edt */: tzoffset = 4 * 60; break; case 5 /* cst */: tzoffset = 6 * 60; break; case 6 /* cdt */: tzoffset = 5 * 60; break; case 7 /* mst */: tzoffset = 7 * 60; break; case 8 /* mdt */: tzoffset = 6 * 60; break; case 9 /* pst */: tzoffset = 8 * 60; break; case 10 /* pdt */:tzoffset = 7 * 60; break; default: Kit.codeBug(); } } } } if (year < 0 || mon < 0 || mday < 0) return ScriptRuntime.NaN; if (sec < 0) sec = 0; if (min < 0) min = 0; if (hour < 0) hour = 0; double msec = date_msecFromDate(year, mon, mday, hour, min, sec, 0); if (tzoffset == -1) { /* no time zone specified, have to use local */ return internalUTC(msec); } else { return msec + tzoffset * msPerMinute; } } private static String date_format(double t, int methodId) { StringBuffer result = new StringBuffer(60); double local = LocalTime(t); /* Tue Oct 31 09:41:40 GMT-0800 (PST) 2000 */ /* Tue Oct 31 2000 */ /* 09:41:40 GMT-0800 (PST) */ if (methodId != Id_toTimeString) { appendWeekDayName(result, WeekDay(local)); result.append(' '); appendMonthName(result, MonthFromTime(local)); result.append(' '); append0PaddedUint(result, DateFromTime(local), 2); result.append(' '); int year = YearFromTime(local); if (year < 0) { result.append('-'); year = -year; } append0PaddedUint(result, year, 4); if (methodId != Id_toDateString) result.append(' '); } if (methodId != Id_toDateString) { append0PaddedUint(result, HourFromTime(local), 2); result.append(':'); append0PaddedUint(result, MinFromTime(local), 2); result.append(':'); append0PaddedUint(result, SecFromTime(local), 2); // offset from GMT in minutes. The offset includes daylight // savings, if it applies. int minutes = (int) Math.floor((LocalTZA + DaylightSavingTA(t)) / msPerMinute); // map 510 minutes to 0830 hours int offset = (minutes / 60) * 100 + minutes % 60; if (offset > 0) { result.append(" GMT+"); } else { result.append(" GMT-"); offset = -offset; } append0PaddedUint(result, offset, 4); if (timeZoneFormatter == null) timeZoneFormatter = new java.text.SimpleDateFormat("zzz"); // Find an equivalent year before getting the timezone // comment. See DaylightSavingTA. if (t < 0.0 || t > 2145916800000.0) { int equiv = EquivalentYear(YearFromTime(local)); double day = MakeDay(equiv, MonthFromTime(t), DateFromTime(t)); t = MakeDate(day, TimeWithinDay(t)); } result.append(" ("); java.util.Date date = new Date((long) t); synchronized (timeZoneFormatter) { result.append(timeZoneFormatter.format(date)); } result.append(')'); } return result.toString(); } /* the javascript constructor */ private static Object jsConstructor(Object[] args) { NativeDate obj = new NativeDate(); // if called as a constructor with no args, // return a new Date with the current time. if (args.length == 0) { obj.date = now(); return obj; } // if called with just one arg - if (args.length == 1) { Object arg0 = args[0]; if (arg0 instanceof Scriptable) arg0 = ((Scriptable) arg0).getDefaultValue(null); double date; if (arg0 instanceof String) { // it's a string; parse it. date = date_parseString((String)arg0); } else { // if it's not a string, use it as a millisecond date date = ScriptRuntime.toNumber(arg0); } obj.date = TimeClip(date); return obj; } double time = date_msecFromArgs(args); if (!Double.isNaN(time) && !Double.isInfinite(time)) time = TimeClip(internalUTC(time)); obj.date = time; return obj; } private static String toLocale_helper(double t, int methodId) { java.text.DateFormat formatter; switch (methodId) { case Id_toLocaleString: if (localeDateTimeFormatter == null) { localeDateTimeFormatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); } formatter = localeDateTimeFormatter; break; case Id_toLocaleTimeString: if (localeTimeFormatter == null) { localeTimeFormatter = DateFormat.getTimeInstance(DateFormat.LONG); } formatter = localeTimeFormatter; break; case Id_toLocaleDateString: if (localeDateFormatter == null) { localeDateFormatter = DateFormat.getDateInstance(DateFormat.LONG); } formatter = localeDateFormatter; break; default: throw new AssertionError(); // unreachable } synchronized (formatter) { return formatter.format(new Date((long) t)); } } private static String js_toUTCString(double date) { StringBuffer result = new StringBuffer(60); appendWeekDayName(result, WeekDay(date)); result.append(", "); append0PaddedUint(result, DateFromTime(date), 2); result.append(' '); appendMonthName(result, MonthFromTime(date)); result.append(' '); int year = YearFromTime(date); if (year < 0) { result.append('-'); year = -year; } append0PaddedUint(result, year, 4); result.append(' '); append0PaddedUint(result, HourFromTime(date), 2); result.append(':'); append0PaddedUint(result, MinFromTime(date), 2); result.append(':'); append0PaddedUint(result, SecFromTime(date), 2); result.append(" GMT"); return result.toString(); } private static void append0PaddedUint(StringBuffer sb, int i, int minWidth) { if (i < 0) Kit.codeBug(); int scale = 1; --minWidth; if (i >= 10) { if (i < 1000 * 1000 * 1000) { for (;;) { int newScale = scale * 10; if (i < newScale) { break; } --minWidth; scale = newScale; } } else { // Separated case not to check against 10 * 10^9 overflow minWidth -= 9; scale = 1000 * 1000 * 1000; } } while (minWidth > 0) { sb.append('0'); --minWidth; } while (scale != 1) { sb.append((char)('0' + (i / scale))); i %= scale; scale /= 10; } sb.append((char)('0' + i)); } private static void appendMonthName(StringBuffer sb, int index) { // Take advantage of the fact that all month abbreviations // have the same length to minimize amount of strings runtime has // to keep in memory String months = "Jan"+"Feb"+"Mar"+"Apr"+"May"+"Jun" +"Jul"+"Aug"+"Sep"+"Oct"+"Nov"+"Dec"; index *= 3; for (int i = 0; i != 3; ++i) { sb.append(months.charAt(index + i)); } } private static void appendWeekDayName(StringBuffer sb, int index) { String days = "Sun"+"Mon"+"Tue"+"Wed"+"Thu"+"Fri"+"Sat"; index *= 3; for (int i = 0; i != 3; ++i) { sb.append(days.charAt(index + i)); } } private static double makeTime(double date, Object[] args, int methodId) { int maxargs; boolean local = true; switch (methodId) { case Id_setUTCMilliseconds: local = false; // fallthrough case Id_setMilliseconds: maxargs = 1; break; case Id_setUTCSeconds: local = false; // fallthrough case Id_setSeconds: maxargs = 2; break; case Id_setUTCMinutes: local = false; // fallthrough case Id_setMinutes: maxargs = 3; break; case Id_setUTCHours: local = false; // fallthrough case Id_setHours: maxargs = 4; break; default: Kit.codeBug(); maxargs = 0; } int i; double conv[] = new double[4]; double hour, min, sec, msec; double lorutime; /* Local or UTC version of date */ double time; double result; /* just return NaN if the date is already NaN */ if (date != date) return date; /* Satisfy the ECMA rule that if a function is called with * fewer arguments than the specified formal arguments, the * remaining arguments are set to undefined. Seems like all * the Date.setWhatever functions in ECMA are only varargs * beyond the first argument; this should be set to undefined * if it's not given. This means that "d = new Date(); * d.setMilliseconds()" returns NaN. Blech. */ if (args.length == 0) args = ScriptRuntime.padArguments(args, 1); for (i = 0; i < args.length && i < maxargs; i++) { conv[i] = ScriptRuntime.toNumber(args[i]); // limit checks that happen in MakeTime in ECMA. if (conv[i] != conv[i] || Double.isInfinite(conv[i])) { return ScriptRuntime.NaN; } conv[i] = ScriptRuntime.toInteger(conv[i]); } if (local) lorutime = LocalTime(date); else lorutime = date; i = 0; int stop = args.length; if (maxargs >= 4 && i < stop) hour = conv[i++]; else hour = HourFromTime(lorutime); if (maxargs >= 3 && i < stop) min = conv[i++]; else min = MinFromTime(lorutime); if (maxargs >= 2 && i < stop) sec = conv[i++]; else sec = SecFromTime(lorutime); if (maxargs >= 1 && i < stop) msec = conv[i++]; else msec = msFromTime(lorutime); time = MakeTime(hour, min, sec, msec); result = MakeDate(Day(lorutime), time); if (local) result = internalUTC(result); date = TimeClip(result); return date; } private static double makeDate(double date, Object[] args, int methodId) { int maxargs; boolean local = true; switch (methodId) { case Id_setUTCDate: local = false; // fallthrough case Id_setDate: maxargs = 1; break; case Id_setUTCMonth: local = false; // fallthrough case Id_setMonth: maxargs = 2; break; case Id_setUTCFullYear: local = false; // fallthrough case Id_setFullYear: maxargs = 3; break; default: Kit.codeBug(); maxargs = 0; } int i; double conv[] = new double[3]; double year, month, day; double lorutime; /* local or UTC version of date */ double result; /* See arg padding comment in makeTime.*/ if (args.length == 0) args = ScriptRuntime.padArguments(args, 1); for (i = 0; i < args.length && i < maxargs; i++) { conv[i] = ScriptRuntime.toNumber(args[i]); // limit checks that happen in MakeDate in ECMA. if (conv[i] != conv[i] || Double.isInfinite(conv[i])) { return ScriptRuntime.NaN; } conv[i] = ScriptRuntime.toInteger(conv[i]); } /* return NaN if date is NaN and we're not setting the year, * If we are, use 0 as the time. */ if (date != date) { if (args.length < 3) { return ScriptRuntime.NaN; } else { lorutime = 0; } } else { if (local) lorutime = LocalTime(date); else lorutime = date; } i = 0; int stop = args.length; if (maxargs >= 3 && i < stop) year = conv[i++]; else year = YearFromTime(lorutime); if (maxargs >= 2 && i < stop) month = conv[i++]; else month = MonthFromTime(lorutime); if (maxargs >= 1 && i < stop) day = conv[i++]; else day = DateFromTime(lorutime); day = MakeDay(year, month, day); /* day within year */ result = MakeDate(day, TimeWithinDay(lorutime)); if (local) result = internalUTC(result); date = TimeClip(result); return date; } // #string_id_map# @Override protected int findPrototypeId(String s) { int id; // #generated# Last update: 2007-05-09 08:15:38 EDT L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 6: X="getDay";id=Id_getDay; break L; case 7: switch (s.charAt(3)) { case 'D': c=s.charAt(0); if (c=='g') { X="getDate";id=Id_getDate; } else if (c=='s') { X="setDate";id=Id_setDate; } break L; case 'T': c=s.charAt(0); if (c=='g') { X="getTime";id=Id_getTime; } else if (c=='s') { X="setTime";id=Id_setTime; } break L; case 'Y': c=s.charAt(0); if (c=='g') { X="getYear";id=Id_getYear; } else if (c=='s') { X="setYear";id=Id_setYear; } break L; case 'u': X="valueOf";id=Id_valueOf; break L; } break L; case 8: switch (s.charAt(3)) { case 'H': c=s.charAt(0); if (c=='g') { X="getHours";id=Id_getHours; } else if (c=='s') { X="setHours";id=Id_setHours; } break L; case 'M': c=s.charAt(0); if (c=='g') { X="getMonth";id=Id_getMonth; } else if (c=='s') { X="setMonth";id=Id_setMonth; } break L; case 'o': X="toSource";id=Id_toSource; break L; case 't': X="toString";id=Id_toString; break L; } break L; case 9: X="getUTCDay";id=Id_getUTCDay; break L; case 10: c=s.charAt(3); if (c=='M') { c=s.charAt(0); if (c=='g') { X="getMinutes";id=Id_getMinutes; } else if (c=='s') { X="setMinutes";id=Id_setMinutes; } } else if (c=='S') { c=s.charAt(0); if (c=='g') { X="getSeconds";id=Id_getSeconds; } else if (c=='s') { X="setSeconds";id=Id_setSeconds; } } else if (c=='U') { c=s.charAt(0); if (c=='g') { X="getUTCDate";id=Id_getUTCDate; } else if (c=='s') { X="setUTCDate";id=Id_setUTCDate; } } break L; case 11: switch (s.charAt(3)) { case 'F': c=s.charAt(0); if (c=='g') { X="getFullYear";id=Id_getFullYear; } else if (c=='s') { X="setFullYear";id=Id_setFullYear; } break L; case 'M': X="toGMTString";id=Id_toGMTString; break L; case 'T': X="toUTCString";id=Id_toUTCString; break L; case 'U': c=s.charAt(0); if (c=='g') { c=s.charAt(9); if (c=='r') { X="getUTCHours";id=Id_getUTCHours; } else if (c=='t') { X="getUTCMonth";id=Id_getUTCMonth; } } else if (c=='s') { c=s.charAt(9); if (c=='r') { X="setUTCHours";id=Id_setUTCHours; } else if (c=='t') { X="setUTCMonth";id=Id_setUTCMonth; } } break L; case 's': X="constructor";id=Id_constructor; break L; } break L; case 12: c=s.charAt(2); if (c=='D') { X="toDateString";id=Id_toDateString; } else if (c=='T') { X="toTimeString";id=Id_toTimeString; } break L; case 13: c=s.charAt(0); if (c=='g') { c=s.charAt(6); if (c=='M') { X="getUTCMinutes";id=Id_getUTCMinutes; } else if (c=='S') { X="getUTCSeconds";id=Id_getUTCSeconds; } } else if (c=='s') { c=s.charAt(6); if (c=='M') { X="setUTCMinutes";id=Id_setUTCMinutes; } else if (c=='S') { X="setUTCSeconds";id=Id_setUTCSeconds; } } break L; case 14: c=s.charAt(0); if (c=='g') { X="getUTCFullYear";id=Id_getUTCFullYear; } else if (c=='s') { X="setUTCFullYear";id=Id_setUTCFullYear; } else if (c=='t') { X="toLocaleString";id=Id_toLocaleString; } break L; case 15: c=s.charAt(0); if (c=='g') { X="getMilliseconds";id=Id_getMilliseconds; } else if (c=='s') { X="setMilliseconds";id=Id_setMilliseconds; } break L; case 17: X="getTimezoneOffset";id=Id_getTimezoneOffset; break L; case 18: c=s.charAt(0); if (c=='g') { X="getUTCMilliseconds";id=Id_getUTCMilliseconds; } else if (c=='s') { X="setUTCMilliseconds";id=Id_setUTCMilliseconds; } else if (c=='t') { c=s.charAt(8); if (c=='D') { X="toLocaleDateString";id=Id_toLocaleDateString; } else if (c=='T') { X="toLocaleTimeString";id=Id_toLocaleTimeString; } } break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# return id; } private static final int ConstructorId_now = -3, ConstructorId_parse = -2, ConstructorId_UTC = -1, Id_constructor = 1, Id_toString = 2, Id_toTimeString = 3, Id_toDateString = 4, Id_toLocaleString = 5, Id_toLocaleTimeString = 6, Id_toLocaleDateString = 7, Id_toUTCString = 8, Id_toSource = 9, Id_valueOf = 10, Id_getTime = 11, Id_getYear = 12, Id_getFullYear = 13, Id_getUTCFullYear = 14, Id_getMonth = 15, Id_getUTCMonth = 16, Id_getDate = 17, Id_getUTCDate = 18, Id_getDay = 19, Id_getUTCDay = 20, Id_getHours = 21, Id_getUTCHours = 22, Id_getMinutes = 23, Id_getUTCMinutes = 24, Id_getSeconds = 25, Id_getUTCSeconds = 26, Id_getMilliseconds = 27, Id_getUTCMilliseconds = 28, Id_getTimezoneOffset = 29, Id_setTime = 30, Id_setMilliseconds = 31, Id_setUTCMilliseconds = 32, Id_setSeconds = 33, Id_setUTCSeconds = 34, Id_setMinutes = 35, Id_setUTCMinutes = 36, Id_setHours = 37, Id_setUTCHours = 38, Id_setDate = 39, Id_setUTCDate = 40, Id_setMonth = 41, Id_setUTCMonth = 42, Id_setFullYear = 43, Id_setUTCFullYear = 44, Id_setYear = 45, MAX_PROTOTYPE_ID = 45; private static final int Id_toGMTString = Id_toUTCString; // Alias, see Ecma B.2.6 // #/string_id_map# /* cached values */ private static java.util.TimeZone thisTimeZone; private static double LocalTZA; private static java.text.DateFormat timeZoneFormatter; private static java.text.DateFormat localeDateTimeFormatter; private static java.text.DateFormat localeDateFormatter; private static java.text.DateFormat localeTimeFormatter; private double date; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/NativeGlobal.java0000644000175000017500000006714311314263504033330 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Mike McCabe * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.io.Serializable; import org.mozilla.javascript.xml.XMLLib; /** * This class implements the global native object (function and value * properties only). * * See ECMA 15.1.[12]. * * @author Mike Shaver */ public class NativeGlobal implements Serializable, IdFunctionCall { static final long serialVersionUID = 6080442165748707530L; public static void init(Context cx, Scriptable scope, boolean sealed) { NativeGlobal obj = new NativeGlobal(); for (int id = 1; id <= LAST_SCOPE_FUNCTION_ID; ++id) { String name; int arity = 1; switch (id) { case Id_decodeURI: name = "decodeURI"; break; case Id_decodeURIComponent: name = "decodeURIComponent"; break; case Id_encodeURI: name = "encodeURI"; break; case Id_encodeURIComponent: name = "encodeURIComponent"; break; case Id_escape: name = "escape"; break; case Id_eval: name = "eval"; break; case Id_isFinite: name = "isFinite"; break; case Id_isNaN: name = "isNaN"; break; case Id_isXMLName: name = "isXMLName"; break; case Id_parseFloat: name = "parseFloat"; break; case Id_parseInt: name = "parseInt"; arity = 2; break; case Id_unescape: name = "unescape"; break; case Id_uneval: name = "uneval"; break; default: throw Kit.codeBug(); } IdFunctionObject f = new IdFunctionObject(obj, FTAG, id, name, arity, scope); if (sealed) { f.sealObject(); } f.exportAsScopeProperty(); } ScriptableObject.defineProperty( scope, "NaN", ScriptRuntime.NaNobj, ScriptableObject.DONTENUM); ScriptableObject.defineProperty( scope, "Infinity", ScriptRuntime.wrapNumber(Double.POSITIVE_INFINITY), ScriptableObject.DONTENUM); ScriptableObject.defineProperty( scope, "undefined", Undefined.instance, ScriptableObject.DONTENUM); String[] errorMethods = { "ConversionError", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "InternalError", "JavaException" }; /* Each error constructor gets its own Error object as a prototype, with the 'name' property set to the name of the error. */ for (int i = 0; i < errorMethods.length; i++) { String name = errorMethods[i]; Scriptable errorProto = ScriptRuntime. newObject(cx, scope, "Error", ScriptRuntime.emptyArgs); errorProto.put("name", errorProto, name); if (sealed) { if (errorProto instanceof ScriptableObject) { ((ScriptableObject)errorProto).sealObject(); } } IdFunctionObject ctor = new IdFunctionObject(obj, FTAG, Id_new_CommonError, name, 1, scope); ctor.markAsConstructor(errorProto); if (sealed) { ctor.sealObject(); } ctor.exportAsScopeProperty(); } } public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (f.hasTag(FTAG)) { int methodId = f.methodId(); switch (methodId) { case Id_decodeURI: case Id_decodeURIComponent: { String str = ScriptRuntime.toString(args, 0); return decode(str, methodId == Id_decodeURI); } case Id_encodeURI: case Id_encodeURIComponent: { String str = ScriptRuntime.toString(args, 0); return encode(str, methodId == Id_encodeURI); } case Id_escape: return js_escape(args); case Id_eval: return js_eval(cx, scope, thisObj, args); case Id_isFinite: { boolean result; if (args.length < 1) { result = false; } else { double d = ScriptRuntime.toNumber(args[0]); result = (d == d && d != Double.POSITIVE_INFINITY && d != Double.NEGATIVE_INFINITY); } return ScriptRuntime.wrapBoolean(result); } case Id_isNaN: { // The global method isNaN, as per ECMA-262 15.1.2.6. boolean result; if (args.length < 1) { result = true; } else { double d = ScriptRuntime.toNumber(args[0]); result = (d != d); } return ScriptRuntime.wrapBoolean(result); } case Id_isXMLName: { Object name = (args.length == 0) ? Undefined.instance : args[0]; XMLLib xmlLib = XMLLib.extractFromScope(scope); return ScriptRuntime.wrapBoolean( xmlLib.isXMLName(cx, name)); } case Id_parseFloat: return js_parseFloat(args); case Id_parseInt: return js_parseInt(args); case Id_unescape: return js_unescape(args); case Id_uneval: { Object value = (args.length != 0) ? args[0] : Undefined.instance; return ScriptRuntime.uneval(cx, scope, value); } case Id_new_CommonError: // The implementation of all the ECMA error constructors // (SyntaxError, TypeError, etc.) return NativeError.make(cx, scope, f, args); } } throw f.unknown(); } /** * The global method parseInt, as per ECMA-262 15.1.2.2. */ private Object js_parseInt(Object[] args) { String s = ScriptRuntime.toString(args, 0); int radix = ScriptRuntime.toInt32(args, 1); int len = s.length(); if (len == 0) return ScriptRuntime.NaNobj; boolean negative = false; int start = 0; char c; do { c = s.charAt(start); if (!isStrWhiteSpaceChar(c)) break; start++; } while (start < len); if (c == '+' || (negative = (c == '-'))) start++; final int NO_RADIX = -1; if (radix == 0) { radix = NO_RADIX; } else if (radix < 2 || radix > 36) { return ScriptRuntime.NaNobj; } else if (radix == 16 && len - start > 1 && s.charAt(start) == '0') { c = s.charAt(start+1); if (c == 'x' || c == 'X') start += 2; } if (radix == NO_RADIX) { radix = 10; if (len - start > 1 && s.charAt(start) == '0') { c = s.charAt(start+1); if (c == 'x' || c == 'X') { radix = 16; start += 2; } else if ('0' <= c && c <= '9') { radix = 8; start++; } } } double d = ScriptRuntime.stringToNumber(s, start, radix); return ScriptRuntime.wrapNumber(negative ? -d : d); } /** * Indicates if the character is a Str whitespace char according to ECMA spec: * StrWhiteSpaceChar ::: */ static boolean isStrWhiteSpaceChar(char c) { switch (c) { case '\t': // case ' ': // case '\u00A0': // case '\u000C': // case '\u000B': // case '\r': // case '\n': // case '\u2028': // case '\u2029': // return true; default: return Character.getType(c) == Character.SPACE_SEPARATOR; } } /** * The global method parseFloat, as per ECMA-262 15.1.2.3. * * @param args the arguments to parseFloat, ignoring args[>=1] */ private Object js_parseFloat(Object[] args) { if (args.length < 1) return ScriptRuntime.NaNobj; String s = ScriptRuntime.toString(args[0]); int len = s.length(); int start = 0; // Scan forward to skip whitespace char c; for (;;) { if (start == len) { return ScriptRuntime.NaNobj; } c = s.charAt(start); if (!isStrWhiteSpaceChar(c)) { break; } ++start; } int i = start; if (c == '+' || c == '-') { ++i; if (i == len) { return ScriptRuntime.NaNobj; } c = s.charAt(i); } if (c == 'I') { // check for "Infinity" if (i+8 <= len && s.regionMatches(i, "Infinity", 0, 8)) { double d; if (s.charAt(start) == '-') { d = Double.NEGATIVE_INFINITY; } else { d = Double.POSITIVE_INFINITY; } return ScriptRuntime.wrapNumber(d); } return ScriptRuntime.NaNobj; } // Find the end of the legal bit int decimal = -1; int exponent = -1; for (; i < len; i++) { switch (s.charAt(i)) { case '.': if (decimal != -1) // Only allow a single decimal point. break; decimal = i; continue; case 'e': case 'E': if (exponent != -1) break; exponent = i; continue; case '+': case '-': // Only allow '+' or '-' after 'e' or 'E' if (exponent != i-1) break; continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': continue; default: break; } break; } s = s.substring(start, i); try { return Double.valueOf(s); } catch (NumberFormatException ex) { return ScriptRuntime.NaNobj; } } /** * The global method escape, as per ECMA-262 15.1.2.4. * Includes code for the 'mask' argument supported by the C escape * method, which used to be part of the browser imbedding. Blame * for the strange constant names should be directed there. */ private Object js_escape(Object[] args) { final int URL_XALPHAS = 1, URL_XPALPHAS = 2, URL_PATH = 4; String s = ScriptRuntime.toString(args, 0); int mask = URL_XALPHAS | URL_XPALPHAS | URL_PATH; if (args.length > 1) { // the 'mask' argument. Non-ECMA. double d = ScriptRuntime.toNumber(args[1]); if (d != d || ((mask = (int) d) != d) || 0 != (mask & ~(URL_XALPHAS | URL_XPALPHAS | URL_PATH))) { throw Context.reportRuntimeError0("msg.bad.esc.mask"); } } StringBuffer sb = null; for (int k = 0, L = s.length(); k != L; ++k) { int c = s.charAt(k); if (mask != 0 && ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '@' || c == '*' || c == '_' || c == '-' || c == '.' || (0 != (mask & URL_PATH) && (c == '/' || c == '+')))) { if (sb != null) { sb.append((char)c); } } else { if (sb == null) { sb = new StringBuffer(L + 3); sb.append(s); sb.setLength(k); } int hexSize; if (c < 256) { if (c == ' ' && mask == URL_XPALPHAS) { sb.append('+'); continue; } sb.append('%'); hexSize = 2; } else { sb.append('%'); sb.append('u'); hexSize = 4; } // append hexadecimal form of c left-padded with 0 for (int shift = (hexSize - 1) * 4; shift >= 0; shift -= 4) { int digit = 0xf & (c >> shift); int hc = (digit < 10) ? '0' + digit : 'A' - 10 + digit; sb.append((char)hc); } } } return (sb == null) ? s : sb.toString(); } /** * The global unescape method, as per ECMA-262 15.1.2.5. */ private Object js_unescape(Object[] args) { String s = ScriptRuntime.toString(args, 0); int firstEscapePos = s.indexOf('%'); if (firstEscapePos >= 0) { int L = s.length(); char[] buf = s.toCharArray(); int destination = firstEscapePos; for (int k = firstEscapePos; k != L;) { char c = buf[k]; ++k; if (c == '%' && k != L) { int end, start; if (buf[k] == 'u') { start = k + 1; end = k + 5; } else { start = k; end = k + 2; } if (end <= L) { int x = 0; for (int i = start; i != end; ++i) { x = Kit.xDigitToInt(buf[i], x); } if (x >= 0) { c = (char)x; k = end; } } } buf[destination] = c; ++destination; } s = new String(buf, 0, destination); } return s; } private Object js_eval(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (thisObj.getParentScope() == null) { // We allow indirect calls to eval as long as the script will execute in // the global scope. return ScriptRuntime.evalSpecial(cx, scope, thisObj, args, "eval code", 1); } String m = ScriptRuntime.getMessage1("msg.cant.call.indirect", "eval"); throw NativeGlobal.constructError(cx, "EvalError", m, scope); } static boolean isEvalFunction(Object functionObj) { if (functionObj instanceof IdFunctionObject) { IdFunctionObject function = (IdFunctionObject)functionObj; if (function.hasTag(FTAG) && function.methodId() == Id_eval) { return true; } } return false; } /** * @deprecated Use {@link ScriptRuntime#constructError(String,String)} * instead. */ public static EcmaError constructError(Context cx, String error, String message, Scriptable scope) { return ScriptRuntime.constructError(error, message); } /** * @deprecated Use * {@link ScriptRuntime#constructError(String,String,String,int,String,int)} * instead. */ public static EcmaError constructError(Context cx, String error, String message, Scriptable scope, String sourceName, int lineNumber, int columnNumber, String lineSource) { return ScriptRuntime.constructError(error, message, sourceName, lineNumber, lineSource, columnNumber); } /* * ECMA 3, 15.1.3 URI Handling Function Properties * * The following are implementations of the algorithms * given in the ECMA specification for the hidden functions * 'Encode' and 'Decode'. */ private static String encode(String str, boolean fullUri) { byte[] utf8buf = null; StringBuffer sb = null; for (int k = 0, length = str.length(); k != length; ++k) { char C = str.charAt(k); if (encodeUnescaped(C, fullUri)) { if (sb != null) { sb.append(C); } } else { if (sb == null) { sb = new StringBuffer(length + 3); sb.append(str); sb.setLength(k); utf8buf = new byte[6]; } if (0xDC00 <= C && C <= 0xDFFF) { throw Context.reportRuntimeError0("msg.bad.uri"); } int V; if (C < 0xD800 || 0xDBFF < C) { V = C; } else { k++; if (k == length) { throw Context.reportRuntimeError0("msg.bad.uri"); } char C2 = str.charAt(k); if (!(0xDC00 <= C2 && C2 <= 0xDFFF)) { throw Context.reportRuntimeError0("msg.bad.uri"); } V = ((C - 0xD800) << 10) + (C2 - 0xDC00) + 0x10000; } int L = oneUcs4ToUtf8Char(utf8buf, V); for (int j = 0; j < L; j++) { int d = 0xff & utf8buf[j]; sb.append('%'); sb.append(toHexChar(d >>> 4)); sb.append(toHexChar(d & 0xf)); } } } return (sb == null) ? str : sb.toString(); } private static char toHexChar(int i) { if (i >> 4 != 0) Kit.codeBug(); return (char)((i < 10) ? i + '0' : i - 10 + 'A'); } private static int unHex(char c) { if ('A' <= c && c <= 'F') { return c - 'A' + 10; } else if ('a' <= c && c <= 'f') { return c - 'a' + 10; } else if ('0' <= c && c <= '9') { return c - '0'; } else { return -1; } } private static int unHex(char c1, char c2) { int i1 = unHex(c1); int i2 = unHex(c2); if (i1 >= 0 && i2 >= 0) { return (i1 << 4) | i2; } return -1; } private static String decode(String str, boolean fullUri) { char[] buf = null; int bufTop = 0; for (int k = 0, length = str.length(); k != length;) { char C = str.charAt(k); if (C != '%') { if (buf != null) { buf[bufTop++] = C; } ++k; } else { if (buf == null) { // decode always compress so result can not be bigger then // str.length() buf = new char[length]; str.getChars(0, k, buf, 0); bufTop = k; } int start = k; if (k + 3 > length) throw Context.reportRuntimeError0("msg.bad.uri"); int B = unHex(str.charAt(k + 1), str.charAt(k + 2)); if (B < 0) throw Context.reportRuntimeError0("msg.bad.uri"); k += 3; if ((B & 0x80) == 0) { C = (char)B; } else { // Decode UTF-8 sequence into ucs4Char and encode it into // UTF-16 int utf8Tail, ucs4Char, minUcs4Char; if ((B & 0xC0) == 0x80) { // First UTF-8 should be ouside 0x80..0xBF throw Context.reportRuntimeError0("msg.bad.uri"); } else if ((B & 0x20) == 0) { utf8Tail = 1; ucs4Char = B & 0x1F; minUcs4Char = 0x80; } else if ((B & 0x10) == 0) { utf8Tail = 2; ucs4Char = B & 0x0F; minUcs4Char = 0x800; } else if ((B & 0x08) == 0) { utf8Tail = 3; ucs4Char = B & 0x07; minUcs4Char = 0x10000; } else if ((B & 0x04) == 0) { utf8Tail = 4; ucs4Char = B & 0x03; minUcs4Char = 0x200000; } else if ((B & 0x02) == 0) { utf8Tail = 5; ucs4Char = B & 0x01; minUcs4Char = 0x4000000; } else { // First UTF-8 can not be 0xFF or 0xFE throw Context.reportRuntimeError0("msg.bad.uri"); } if (k + 3 * utf8Tail > length) throw Context.reportRuntimeError0("msg.bad.uri"); for (int j = 0; j != utf8Tail; j++) { if (str.charAt(k) != '%') throw Context.reportRuntimeError0("msg.bad.uri"); B = unHex(str.charAt(k + 1), str.charAt(k + 2)); if (B < 0 || (B & 0xC0) != 0x80) throw Context.reportRuntimeError0("msg.bad.uri"); ucs4Char = (ucs4Char << 6) | (B & 0x3F); k += 3; } // Check for overlongs and other should-not-present codes if (ucs4Char < minUcs4Char || ucs4Char == 0xFFFE || ucs4Char == 0xFFFF) { ucs4Char = 0xFFFD; } if (ucs4Char >= 0x10000) { ucs4Char -= 0x10000; if (ucs4Char > 0xFFFFF) throw Context.reportRuntimeError0("msg.bad.uri"); char H = (char)((ucs4Char >>> 10) + 0xD800); C = (char)((ucs4Char & 0x3FF) + 0xDC00); buf[bufTop++] = H; } else { C = (char)ucs4Char; } } if (fullUri && URI_DECODE_RESERVED.indexOf(C) >= 0) { for (int x = start; x != k; x++) { buf[bufTop++] = str.charAt(x); } } else { buf[bufTop++] = C; } } } return (buf == null) ? str : new String(buf, 0, bufTop); } private static boolean encodeUnescaped(char c, boolean fullUri) { if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9')) { return true; } if ("-_.!~*'()".indexOf(c) >= 0) return true; if (fullUri) { return URI_DECODE_RESERVED.indexOf(c) >= 0; } return false; } private static final String URI_DECODE_RESERVED = ";/?:@&=+$,#"; /* Convert one UCS-4 char and write it into a UTF-8 buffer, which must be * at least 6 bytes long. Return the number of UTF-8 bytes of data written. */ private static int oneUcs4ToUtf8Char(byte[] utf8Buffer, int ucs4Char) { int utf8Length = 1; //JS_ASSERT(ucs4Char <= 0x7FFFFFFF); if ((ucs4Char & ~0x7F) == 0) utf8Buffer[0] = (byte)ucs4Char; else { int i; int a = ucs4Char >>> 11; utf8Length = 2; while (a != 0) { a >>>= 5; utf8Length++; } i = utf8Length; while (--i > 0) { utf8Buffer[i] = (byte)((ucs4Char & 0x3F) | 0x80); ucs4Char >>>= 6; } utf8Buffer[0] = (byte)(0x100 - (1 << (8-utf8Length)) + ucs4Char); } return utf8Length; } private static final Object FTAG = "Global"; private static final int Id_decodeURI = 1, Id_decodeURIComponent = 2, Id_encodeURI = 3, Id_encodeURIComponent = 4, Id_escape = 5, Id_eval = 6, Id_isFinite = 7, Id_isNaN = 8, Id_isXMLName = 9, Id_parseFloat = 10, Id_parseInt = 11, Id_unescape = 12, Id_uneval = 13, LAST_SCOPE_FUNCTION_ID = 13, Id_new_CommonError = 14; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/NativeNumber.java0000644000175000017500000002331011314263504033344 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Mike McCabe * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; /** * This class implements the Number native object. * * See ECMA 15.7. * * @author Norris Boyd */ final class NativeNumber extends IdScriptableObject { static final long serialVersionUID = 3504516769741512101L; private static final Object NUMBER_TAG = "Number"; private static final int MAX_PRECISION = 100; static void init(Scriptable scope, boolean sealed) { NativeNumber obj = new NativeNumber(0.0); obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed); } private NativeNumber(double number) { doubleValue = number; } @Override public String getClassName() { return "Number"; } @Override protected void fillConstructorProperties(IdFunctionObject ctor) { final int attr = ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY; ctor.defineProperty("NaN", ScriptRuntime.NaNobj, attr); ctor.defineProperty("POSITIVE_INFINITY", ScriptRuntime.wrapNumber(Double.POSITIVE_INFINITY), attr); ctor.defineProperty("NEGATIVE_INFINITY", ScriptRuntime.wrapNumber(Double.NEGATIVE_INFINITY), attr); ctor.defineProperty("MAX_VALUE", ScriptRuntime.wrapNumber(Double.MAX_VALUE), attr); ctor.defineProperty("MIN_VALUE", ScriptRuntime.wrapNumber(Double.MIN_VALUE), attr); super.fillConstructorProperties(ctor); } @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=1; s="constructor"; break; case Id_toString: arity=1; s="toString"; break; case Id_toLocaleString: arity=1; s="toLocaleString"; break; case Id_toSource: arity=0; s="toSource"; break; case Id_valueOf: arity=0; s="valueOf"; break; case Id_toFixed: arity=1; s="toFixed"; break; case Id_toExponential: arity=1; s="toExponential"; break; case Id_toPrecision: arity=1; s="toPrecision"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(NUMBER_TAG, id, s, arity); } @Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(NUMBER_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); if (id == Id_constructor) { double val = (args.length >= 1) ? ScriptRuntime.toNumber(args[0]) : 0.0; if (thisObj == null) { // new Number(val) creates a new Number object. return new NativeNumber(val); } // Number(val) converts val to a number value. return ScriptRuntime.wrapNumber(val); } // The rest of Number.prototype methods require thisObj to be Number if (!(thisObj instanceof NativeNumber)) throw incompatibleCallError(f); double value = ((NativeNumber)thisObj).doubleValue; switch (id) { case Id_toString: case Id_toLocaleString: { // toLocaleString is just an alias for toString for now int base = (args.length == 0) ? 10 : ScriptRuntime.toInt32(args[0]); return ScriptRuntime.numberToString(value, base); } case Id_toSource: return "(new Number("+ScriptRuntime.toString(value)+"))"; case Id_valueOf: return ScriptRuntime.wrapNumber(value); case Id_toFixed: return num_to(value, args, DToA.DTOSTR_FIXED, DToA.DTOSTR_FIXED, -20, 0); case Id_toExponential: { // Handle special values before range check if(Double.isNaN(value)) { return "NaN"; } if(Double.isInfinite(value)) { if(value >= 0) { return "Infinity"; } else { return "-Infinity"; } } // General case return num_to(value, args, DToA.DTOSTR_STANDARD_EXPONENTIAL, DToA.DTOSTR_EXPONENTIAL, 0, 1); } case Id_toPrecision: { // Undefined precision, fall back to ToString() if(args.length == 0 || args[0] == Undefined.instance) { return ScriptRuntime.numberToString(value, 10); } // Handle special values before range check if(Double.isNaN(value)) { return "NaN"; } if(Double.isInfinite(value)) { if(value >= 0) { return "Infinity"; } else { return "-Infinity"; } } return num_to(value, args, DToA.DTOSTR_STANDARD, DToA.DTOSTR_PRECISION, 1, 0); } default: throw new IllegalArgumentException(String.valueOf(id)); } } @Override public String toString() { return ScriptRuntime.numberToString(doubleValue, 10); } private static String num_to(double val, Object[] args, int zeroArgMode, int oneArgMode, int precisionMin, int precisionOffset) { int precision; if (args.length == 0) { precision = 0; oneArgMode = zeroArgMode; } else { /* We allow a larger range of precision than ECMA requires; this is permitted by ECMA. */ precision = ScriptRuntime.toInt32(args[0]); if (precision < precisionMin || precision > MAX_PRECISION) { String msg = ScriptRuntime.getMessage1( "msg.bad.precision", ScriptRuntime.toString(args[0])); throw ScriptRuntime.constructError("RangeError", msg); } } StringBuffer sb = new StringBuffer(); DToA.JS_dtostr(sb, oneArgMode, precision + precisionOffset, val); return sb.toString(); } // #string_id_map# @Override protected int findPrototypeId(String s) { int id; // #generated# Last update: 2007-05-09 08:15:50 EDT L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 7: c=s.charAt(0); if (c=='t') { X="toFixed";id=Id_toFixed; } else if (c=='v') { X="valueOf";id=Id_valueOf; } break L; case 8: c=s.charAt(3); if (c=='o') { X="toSource";id=Id_toSource; } else if (c=='t') { X="toString";id=Id_toString; } break L; case 11: c=s.charAt(0); if (c=='c') { X="constructor";id=Id_constructor; } else if (c=='t') { X="toPrecision";id=Id_toPrecision; } break L; case 13: X="toExponential";id=Id_toExponential; break L; case 14: X="toLocaleString";id=Id_toLocaleString; break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# return id; } private static final int Id_constructor = 1, Id_toString = 2, Id_toLocaleString = 3, Id_toSource = 4, Id_valueOf = 5, Id_toFixed = 6, Id_toExponential = 7, Id_toPrecision = 8, MAX_PROTOTYPE_ID = 8; // #/string_id_map# private double doubleValue; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/jdk13/0000755000175000017500000000000011537630013031017 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/jdk13/VMBridge_jdk13.java0000644000175000017500000001341011314263504034314 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.jdk13; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Member; import java.lang.reflect.Proxy; import org.mozilla.javascript.*; public class VMBridge_jdk13 extends VMBridge { private ThreadLocal contextLocal = new ThreadLocal(); @Override protected Object getThreadContextHelper() { // To make subsequent batch calls to getContext/setContext faster // associate permanently one element array with contextLocal // so getContext/setContext would need just to read/write the first // array element. // Note that it is necessary to use Object[], not Context[] to allow // garbage collection of Rhino classes. For details see comments // by Attila Szegedi in // https://bugzilla.mozilla.org/show_bug.cgi?id=281067#c5 Object[] storage = contextLocal.get(); if (storage == null) { storage = new Object[1]; contextLocal.set(storage); } return storage; } @Override protected Context getContext(Object contextHelper) { Object[] storage = (Object[])contextHelper; return (Context)storage[0]; } @Override protected void setContext(Object contextHelper, Context cx) { Object[] storage = (Object[])contextHelper; storage[0] = cx; } @Override protected ClassLoader getCurrentThreadClassLoader() { return Thread.currentThread().getContextClassLoader(); } @Override protected boolean tryToMakeAccessible(Object accessibleObject) { if (!(accessibleObject instanceof AccessibleObject)) { return false; } AccessibleObject accessible = (AccessibleObject)accessibleObject; if (accessible.isAccessible()) { return true; } try { accessible.setAccessible(true); } catch (Exception ex) { } return accessible.isAccessible(); } @Override protected Object getInterfaceProxyHelper(ContextFactory cf, Class[] interfaces) { // XXX: How to handle interfaces array withclasses from different // class loaders? Using cf.getApplicationClassLoader() ? ClassLoader loader = interfaces[0].getClassLoader(); Class cl = Proxy.getProxyClass(loader, interfaces); Constructor c; try { c = cl.getConstructor(new Class[] { InvocationHandler.class }); } catch (NoSuchMethodException ex) { // Should not happen throw Kit.initCause(new IllegalStateException(), ex); } return c; } @Override protected Object newInterfaceProxy(Object proxyHelper, final ContextFactory cf, final InterfaceAdapter adapter, final Object target, final Scriptable topScope) { Constructor c = (Constructor)proxyHelper; InvocationHandler handler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) { return adapter.invoke(cf, target, topScope, method, args); } }; Object proxy; try { proxy = c.newInstance(new Object[] { handler }); } catch (InvocationTargetException ex) { throw Context.throwAsScriptRuntimeEx(ex); } catch (IllegalAccessException ex) { // Shouls not happen throw Kit.initCause(new IllegalStateException(), ex); } catch (InstantiationException ex) { // Shouls not happen throw Kit.initCause(new IllegalStateException(), ex); } return proxy; } @Override protected boolean isVarArgs(Member member) { return false; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ConstProperties.java0000644000175000017500000001152611314263504034116 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Bob Jervis * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; public interface ConstProperties { /** * Sets a named const property in this object. *

* The property is specified by a string name * as defined for Scriptable.get. *

* The possible values that may be passed in are as defined for * Scriptable.get. A class that implements this method may choose * to ignore calls to set certain properties, in which case those * properties are effectively read-only.

* For properties defined in a prototype chain, * use putProperty in ScriptableObject.

* Note that if a property a is defined in the prototype p * of an object o, then evaluating o.a = 23 will cause * set to be called on the prototype p with * o as the start parameter. * To preserve JavaScript semantics, it is the Scriptable * object's responsibility to modify o.

* This design allows properties to be defined in prototypes and implemented * in terms of getters and setters of Java values without consuming slots * in each instance.

*

* The values that may be set are limited to the following: *

    *
  • java.lang.Boolean objects
  • *
  • java.lang.String objects
  • *
  • java.lang.Number objects
  • *
  • org.mozilla.javascript.Scriptable objects
  • *
  • null
  • *
  • The value returned by Context.getUndefinedValue()
  • *

* Arbitrary Java objects may be wrapped in a Scriptable by first calling * Context.toObject. This allows the property of a JavaScript * object to contain an arbitrary Java object as a value.

* Note that has will be called by the runtime first before * set is called to determine in which object the * property is defined. * Note that this method is not expected to traverse the prototype chain, * which is different from the ECMA [[Put]] operation. * @param name the name of the property * @param start the object whose property is being set * @param value value to set the property to * @see org.mozilla.javascript.Scriptable#has(String, Scriptable) * @see org.mozilla.javascript.Scriptable#get(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#putProperty(Scriptable, String, Object) * @see org.mozilla.javascript.Context#toObject(Object, Scriptable) */ public void putConst(String name, Scriptable start, Object value); /** * Reserves a definition spot for a const. This will set up a definition * of the const property, but set its value to undefined. The semantics of * the start parameter is the same as for putConst. * @param name The name of the property. * @param start The object whose property is being reserved. */ public void defineConst(String name, Scriptable start); /** * Returns true if the named property is defined as a const on this object. * @param name * @return true if the named property is defined as a const, false * otherwise. */ public boolean isConst(String name); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/GeneratedClassLoader.java0000644000175000017500000000445011314263504034764 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; /** * Interface to define classes from generated byte code. */ public interface GeneratedClassLoader { /** * Define a new Java class. * Classes created via this method should have the same class loader. * * @param name fully qualified class name * @param data class byte code * @return new class object */ public Class defineClass(String name, byte[] data); /** * Link the given class. * * @param cl Class instance returned from the previous call to * {@link #defineClass(String, byte[])} * @see java.lang.ClassLoader */ public void linkClass(Class cl); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/serialize/0000755000175000017500000000000011537630013032072 5ustar jamespagejamespage00000000000000././@LongLink0000000000000000000000000000015500000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/serialize/ScriptableOutputStream.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/serialize/ScriptableOutputStr0000644000175000017500000001743711314263504036033 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino serialization code, released * Sept. 25, 2001. * * The Initial Developer of the Original Code is * Norris Boyd. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Attila Szegedi * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.serialize; import java.util.Map; import java.util.HashMap; import java.util.StringTokenizer; import java.io.*; import org.mozilla.javascript.*; /** * Class ScriptableOutputStream is an ObjectOutputStream used * to serialize JavaScript objects and functions. Note that * compiled functions currently cannot be serialized, only * interpreted functions. The top-level scope containing the * object is not written out, but is instead replaced with * another top-level object when the ScriptableInputStream * reads in this object. Also, object corresponding to names * added to the exclude list are not written out but instead * are looked up during deserialization. This approach avoids * the creation of duplicate copies of standard objects * during deserialization. * * @author Norris Boyd */ // API class public class ScriptableOutputStream extends ObjectOutputStream { /** * ScriptableOutputStream constructor. * Creates a ScriptableOutputStream for use in serializing * JavaScript objects. Calls excludeStandardObjectNames. * * @param out the OutputStream to write to. * @param scope the scope containing the object. */ public ScriptableOutputStream(OutputStream out, Scriptable scope) throws IOException { super(out); this.scope = scope; table = new HashMap(); table.put(scope, ""); enableReplaceObject(true); excludeStandardObjectNames(); // XXX } public void excludeAllIds(Object[] ids) { for (Object id: ids) { if (id instanceof String && (scope.get((String) id, scope) instanceof Scriptable)) { this.addExcludedName((String)id); } } } /** * Adds a qualified name to the list of object to be excluded from * serialization. Names excluded from serialization are looked up * in the new scope and replaced upon deserialization. * @param name a fully qualified name (of the form "a.b.c", where * "a" must be a property of the top-level object). The object * need not exist, in which case the name is ignored. * @throws IllegalArgumentException if the object is not a * {@link Scriptable}. */ public void addOptionalExcludedName(String name) { Object obj = lookupQualifiedName(scope, name); if(obj != null && obj != UniqueTag.NOT_FOUND) { if (!(obj instanceof Scriptable)) { throw new IllegalArgumentException( "Object for excluded name " + name + " is not a Scriptable, it is " + obj.getClass().getName()); } table.put(obj, name); } } /** * Adds a qualified name to the list of objects to be excluded from * serialization. Names excluded from serialization are looked up * in the new scope and replaced upon deserialization. * @param name a fully qualified name (of the form "a.b.c", where * "a" must be a property of the top-level object) * @throws IllegalArgumentException if the object is not found or is not * a {@link Scriptable}. */ public void addExcludedName(String name) { Object obj = lookupQualifiedName(scope, name); if (!(obj instanceof Scriptable)) { throw new IllegalArgumentException("Object for excluded name " + name + " not found."); } table.put(obj, name); } /** * Returns true if the name is excluded from serialization. */ public boolean hasExcludedName(String name) { return table.get(name) != null; } /** * Removes a name from the list of names to exclude. */ public void removeExcludedName(String name) { table.remove(name); } /** * Adds the names of the standard objects and their * prototypes to the list of excluded names. */ public void excludeStandardObjectNames() { String[] names = { "Object", "Object.prototype", "Function", "Function.prototype", "String", "String.prototype", "Math", // no Math.prototype "Array", "Array.prototype", "Error", "Error.prototype", "Number", "Number.prototype", "Date", "Date.prototype", "RegExp", "RegExp.prototype", "Script", "Script.prototype", "Continuation", "Continuation.prototype", }; for (int i=0; i < names.length; i++) { addExcludedName(names[i]); } String[] optionalNames = { "XML", "XML.prototype", "XMLList", "XMLList.prototype", }; for (int i=0; i < optionalNames.length; i++) { addOptionalExcludedName(optionalNames[i]); } } static Object lookupQualifiedName(Scriptable scope, String qualifiedName) { StringTokenizer st = new StringTokenizer(qualifiedName, "."); Object result = scope; while (st.hasMoreTokens()) { String s = st.nextToken(); result = ScriptableObject.getProperty((Scriptable)result, s); if (result == null || !(result instanceof Scriptable)) break; } return result; } static class PendingLookup implements Serializable { static final long serialVersionUID = -2692990309789917727L; PendingLookup(String name) { this.name = name; } String getName() { return name; } private String name; } @Override protected Object replaceObject(Object obj) throws IOException { if (false) throw new IOException(); // suppress warning String name = table.get(obj); if (name == null) return obj; return new PendingLookup(name); } private Scriptable scope; private Map table; } ././@LongLink0000000000000000000000000000015400000000000011215 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/serialize/ScriptableInputStream.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/serialize/ScriptableInputStre0000644000175000017500000000753711314263504035777 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino serialization code, released * Sept. 25, 2001. * * The Initial Developer of the Original Code is * Norris Boyd. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Attila Szegedi * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript.serialize; import java.io.*; import org.mozilla.javascript.*; /** * Class ScriptableInputStream is used to read in a JavaScript * object or function previously serialized with a ScriptableOutputStream. * References to names in the exclusion list * replaced with references to the top-level scope specified during * creation of the ScriptableInputStream. * * @author Norris Boyd */ public class ScriptableInputStream extends ObjectInputStream { /** * Create a ScriptableInputStream. * @param in the InputStream to read from. * @param scope the top-level scope to create the object in. */ public ScriptableInputStream(InputStream in, Scriptable scope) throws IOException { super(in); this.scope = scope; enableResolveObject(true); Context cx = Context.getCurrentContext(); if (cx != null) { this.classLoader = cx.getApplicationClassLoader(); } } @Override protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String name = desc.getName(); if (classLoader != null) { try { return classLoader.loadClass(name); } catch (ClassNotFoundException ex) { // fall through to default loading } } return super.resolveClass(desc); } @Override protected Object resolveObject(Object obj) throws IOException { if (obj instanceof ScriptableOutputStream.PendingLookup) { String name = ((ScriptableOutputStream.PendingLookup)obj).getName(); obj = ScriptableOutputStream.lookupQualifiedName(scope, name); if (obj == Scriptable.NOT_FOUND) { throw new IOException("Object " + name + " not found upon " + "deserialization."); } }else if (obj instanceof UniqueTag) { obj = ((UniqueTag)obj).readResolve(); }else if (obj instanceof Undefined) { obj = ((Undefined)obj).readResolve(); } return obj; } private Scriptable scope; private ClassLoader classLoader; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ContextListener.java0000644000175000017500000000414211314263504034101 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; /** * @deprecated Embeddings that wish to customize newly created * {@link Context} instances should implement * {@link ContextFactory.Listener}. */ public interface ContextListener extends ContextFactory.Listener { /** * @deprecated Rhino runtime never calls the method. */ public void contextEntered(Context cx); /** * @deprecated Rhino runtime never calls the method. */ public void contextExited(Context cx); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/InterpretedFunction.java0000644000175000017500000001647011314263504034751 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Bob Jervis * Roger Lawrence * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import org.mozilla.javascript.debug.DebuggableScript; final class InterpretedFunction extends NativeFunction implements Script { static final long serialVersionUID = 541475680333911468L; InterpreterData idata; SecurityController securityController; Object securityDomain; Scriptable[] functionRegExps; private InterpretedFunction(InterpreterData idata, Object staticSecurityDomain) { this.idata = idata; // Always get Context from the current thread to // avoid security breaches via passing mangled Context instances // with bogus SecurityController Context cx = Context.getContext(); SecurityController sc = cx.getSecurityController(); Object dynamicDomain; if (sc != null) { dynamicDomain = sc.getDynamicSecurityDomain(staticSecurityDomain); } else { if (staticSecurityDomain != null) { throw new IllegalArgumentException(); } dynamicDomain = null; } this.securityController = sc; this.securityDomain = dynamicDomain; } private InterpretedFunction(InterpretedFunction parent, int index) { this.idata = parent.idata.itsNestedFunctions[index]; this.securityController = parent.securityController; this.securityDomain = parent.securityDomain; } /** * Create script from compiled bytecode. */ static InterpretedFunction createScript(InterpreterData idata, Object staticSecurityDomain) { InterpretedFunction f; f = new InterpretedFunction(idata, staticSecurityDomain); return f; } /** * Create function compiled from Function(...) constructor. */ static InterpretedFunction createFunction(Context cx,Scriptable scope, InterpreterData idata, Object staticSecurityDomain) { InterpretedFunction f; f = new InterpretedFunction(idata, staticSecurityDomain); f.initInterpretedFunction(cx, scope); return f; } /** * Create function embedded in script or another function. */ static InterpretedFunction createFunction(Context cx, Scriptable scope, InterpretedFunction parent, int index) { InterpretedFunction f = new InterpretedFunction(parent, index); f.initInterpretedFunction(cx, scope); return f; } Scriptable[] createRegExpWraps(Context cx, Scriptable scope) { if (idata.itsRegExpLiterals == null) Kit.codeBug(); RegExpProxy rep = ScriptRuntime.checkRegExpProxy(cx); int N = idata.itsRegExpLiterals.length; Scriptable[] array = new Scriptable[N]; for (int i = 0; i != N; ++i) { array[i] = rep.wrapRegExp(cx, scope, idata.itsRegExpLiterals[i]); } return array; } private void initInterpretedFunction(Context cx, Scriptable scope) { initScriptFunction(cx, scope); if (idata.itsRegExpLiterals != null) { functionRegExps = createRegExpWraps(cx, scope); } } @Override public String getFunctionName() { return (idata.itsName == null) ? "" : idata.itsName; } /** * Calls the function. * @param cx the current context * @param scope the scope used for the call * @param thisObj the value of "this" * @param args function arguments. Must not be null. You can use * {@link ScriptRuntime#emptyArgs} to pass empty arguments. * @return the result of the function call. */ @Override public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!ScriptRuntime.hasTopCall(cx)) { return ScriptRuntime.doTopCall(this, cx, scope, thisObj, args); } return Interpreter.interpret(this, cx, scope, thisObj, args); } public Object exec(Context cx, Scriptable scope) { if (!isScript()) { // Can only be applied to scripts throw new IllegalStateException(); } if (!ScriptRuntime.hasTopCall(cx)) { // It will go through "call" path. but they are equivalent return ScriptRuntime.doTopCall( this, cx, scope, scope, ScriptRuntime.emptyArgs); } return Interpreter.interpret( this, cx, scope, scope, ScriptRuntime.emptyArgs); } public boolean isScript() { return idata.itsFunctionType == 0; } @Override public String getEncodedSource() { return Interpreter.getEncodedSource(idata); } @Override public DebuggableScript getDebuggableView() { return idata; } @Override public Object resumeGenerator(Context cx, Scriptable scope, int operation, Object state, Object value) { return Interpreter.resumeGenerator(cx, scope, operation, state, value); } @Override protected int getLanguageVersion() { return idata.languageVersion; } @Override protected int getParamCount() { return idata.argCount; } @Override protected int getParamAndVarCount() { return idata.argNames.length; } @Override protected String getParamOrVarName(int index) { return idata.argNames[index]; } @Override protected boolean getParamOrVarConst(int index) { return idata.argIsConst[index]; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ContinuationPending.java0000644000175000017500000000754011314263504034733 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; /** * Exception thrown by * {@link org.mozilla.javascript.Context#executeScriptWithContinuations(Script, Scriptable)} * and {@link org.mozilla.javascript.Context#callFunctionWithContinuations(Callable, Scriptable, Object[])} * when execution encounters a continuation captured by * {@link org.mozilla.javascript.Context#captureContinuation()}. * Exception will contain the captured state needed to restart the continuation * with {@link org.mozilla.javascript.Context#resumeContinuation(Object, Scriptable, Object)}. * @author Norris Boyd */ public class ContinuationPending extends RuntimeException { private static final long serialVersionUID = 4956008116771118856L; private NativeContinuation continuationState; private Object applicationState; /** * Construct a ContinuationPending exception. Internal call only; * users of the API should get continuations created on their behalf by * calling {@link org.mozilla.javascript.Context#executeScriptWithContinuations(Script, Scriptable)} * and {@link org.mozilla.javascript.Context#callFunctionWithContinuations(Callable, Scriptable, Object[])} * @param continuationState Internal Continuation object */ ContinuationPending(NativeContinuation continuationState) { this.continuationState = continuationState; } /** * Get continuation object. The only * use for this object is to be passed to * {@link org.mozilla.javascript.Context#resumeContinuation(Object, Scriptable, Object)}. * @return continuation object */ public Object getContinuation() { return continuationState; } /** * @return internal continuation state */ NativeContinuation getContinuationState() { return continuationState; } /** * Store an arbitrary object that applications can use to associate * their state with the continuation. * @param applicationState arbitrary application state */ public void setApplicationState(Object applicationState) { this.applicationState = applicationState; } /** * @return arbitrary application state */ public Object getApplicationState() { return applicationState; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/0000755000175000017500000000000011537630013030672 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/Loop.java0000644000175000017500000000603311314263504032450 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; /** * Abstract base type for loops. */ public abstract class Loop extends Scope { protected AstNode body; protected int lp = -1; protected int rp = -1; public Loop() { } public Loop(int pos) { super(pos); } public Loop(int pos, int len) { super(pos, len); } /** * Returns loop body */ public AstNode getBody() { return body; } /** * Sets loop body. Sets the parent of the body to this loop node, * and updates its offset to be relative. Extends the length of this * node to include the body. */ public void setBody(AstNode body) { this.body = body; int end = body.getPosition() + body.getLength(); this.setLength(end - this.getPosition()); body.setParent(this); } /** * Returns left paren position, -1 if missing */ public int getLp() { return lp; } /** * Sets left paren position */ public void setLp(int lp) { this.lp = lp; } /** * Returns right paren position, -1 if missing */ public int getRp() { return rp; } /** * Sets right paren position */ public void setRp(int rp) { this.rp = rp; } /** * Sets both paren positions */ public void setParens(int lp, int rp) { this.lp = lp; this.rp = rp; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/IfStatement.java0000644000175000017500000001305211314263504033761 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * If-else statement. Node type is {@link Token#IF}.

* *

IfStatement :
 *       if ( Expression ) Statement else Statement
 *       if ( Expression ) Statement
*/ public class IfStatement extends AstNode { private AstNode condition; private AstNode thenPart; private int elsePosition = -1; private AstNode elsePart; private int lp = -1; private int rp = -1; { type = Token.IF; } public IfStatement() { } public IfStatement(int pos) { super(pos); } public IfStatement(int pos, int len) { super(pos, len); } /** * Returns if condition */ public AstNode getCondition() { return condition; } /** * Sets if condition. * @throws IllegalArgumentException if {@code condition} is {@code null}. */ public void setCondition(AstNode condition) { assertNotNull(condition); this.condition = condition; condition.setParent(this); } /** * Returns statement to execute if condition is true */ public AstNode getThenPart() { return thenPart; } /** * Sets statement to execute if condition is true * @throws IllegalArgumentException if thenPart is {@code null} */ public void setThenPart(AstNode thenPart) { assertNotNull(thenPart); this.thenPart = thenPart; thenPart.setParent(this); } /** * Returns statement to execute if condition is false */ public AstNode getElsePart() { return elsePart; } /** * Sets statement to execute if condition is false * @param elsePart statement to execute if condition is false. * Can be {@code null}. */ public void setElsePart(AstNode elsePart) { this.elsePart = elsePart; if (elsePart != null) elsePart.setParent(this); } /** * Returns position of "else" keyword, or -1 */ public int getElsePosition() { return elsePosition; } /** * Sets position of "else" keyword, -1 if not present */ public void setElsePosition(int elsePosition) { this.elsePosition = elsePosition; } /** * Returns left paren offset */ public int getLp() { return lp; } /** * Sets left paren offset */ public void setLp(int lp) { this.lp = lp; } /** * Returns right paren position, -1 if missing */ public int getRp() { return rp; } /** * Sets right paren position, -1 if missing */ public void setRp(int rp) { this.rp = rp; } /** * Sets both paren positions */ public void setParens(int lp, int rp) { this.lp = lp; this.rp = rp; } @Override public String toSource(int depth) { String pad = makeIndent(depth); StringBuilder sb = new StringBuilder(32); sb.append(pad); sb.append("if ("); sb.append(condition.toSource(0)); sb.append(") "); if (!(thenPart instanceof Block)) { sb.append("\n").append(makeIndent(depth)); } sb.append(thenPart.toSource(depth).trim()); if (elsePart instanceof IfStatement) { sb.append(" else "); sb.append(elsePart.toSource(depth).trim()); } else if (elsePart != null) { sb.append(" else "); sb.append(elsePart.toSource(depth).trim()); } sb.append("\n"); return sb.toString(); } /** * Visits this node, the condition, the then-part, and * if supplied, the else-part. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { condition.visit(v); thenPart.visit(v); if (elsePart != null) { elsePart.visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/Block.java0000644000175000017500000000564211314263504032576 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * Bob Jervis * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Node; import org.mozilla.javascript.Token; /** * A block statement delimited by curly braces. The node position is the * position of the open-curly, and the length extends to the position of * the close-curly. Node type is {@link Token#BLOCK}. * *
Block :
 *     { Statement* }
*/ public class Block extends AstNode { { this.type = Token.BLOCK; } public Block() { } public Block(int pos) { super(pos); } public Block(int pos, int len) { super(pos, len); } /** * Alias for {@link #addChild}. */ public void addStatement(AstNode statement) { addChild(statement); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("{\n"); for (Node kid : this) { sb.append(((AstNode)kid).toSource(depth+1)); } sb.append(makeIndent(depth)); sb.append("}\n"); return sb.toString(); } @Override public void visit(NodeVisitor v) { if (v.visit(this)) { for (Node kid : this) { ((AstNode)kid).visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ObjectLiteral.java0000644000175000017500000001234711314263504034267 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * AST node for an Object literal (also called an Object initialiser in * Ecma-262). The elements list will always be non-{@code null}, although * the list will have no elements if the Object literal is empty.

* * Node type is {@link Token#OBJECTLIT}.

* *

ObjectLiteral :
 *       {}
 *       { PropertyNameAndValueList }
 * PropertyNameAndValueList :
 *       PropertyName : AssignmentExpression
 *       PropertyNameAndValueList , PropertyName : AssignmentExpression
 * PropertyName :
 *       Identifier
 *       StringLiteral
 *       NumericLiteral
*/ public class ObjectLiteral extends AstNode implements DestructuringForm { private static final List NO_ELEMS = Collections.unmodifiableList(new ArrayList()); private List elements; boolean isDestructuring; { type = Token.OBJECTLIT; } public ObjectLiteral() { } public ObjectLiteral(int pos) { super(pos); } public ObjectLiteral(int pos, int len) { super(pos, len); } /** * Returns the element list. Returns an immutable empty list if there are * no elements. */ public List getElements() { return elements != null ? elements : NO_ELEMS; } /** * Sets the element list, and updates the parent of each element. * Replaces any existing elements. * @param elements the element list. Can be {@code null}. */ public void setElements(List elements) { if (elements == null) { this.elements = null; } else { if (this.elements != null) this.elements.clear(); for (ObjectProperty o : elements) addElement(o); } } /** * Adds an element to the list, and sets its parent to this node. * @param element the property node to append to the end of the list * @throws IllegalArgumentException} if element is {@code null} */ public void addElement(ObjectProperty element) { assertNotNull(element); if (elements == null) { elements = new ArrayList(); } elements.add(element); element.setParent(this); } /** * Marks this node as being a destructuring form - that is, appearing * in a context such as {@code for ([a, b] in ...)} where it's the * target of a destructuring assignment. */ public void setIsDestructuring(boolean destructuring) { isDestructuring = destructuring; } /** * Returns true if this node is in a destructuring position: * a function parameter, the target of a variable initializer, the * iterator of a for..in loop, etc. */ public boolean isDestructuring() { return isDestructuring; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("{"); if (elements != null) { printList(elements, sb); } sb.append("}"); return sb.toString(); } /** * Visits this node, then visits each child property node, in lexical * (source) order. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { for (ObjectProperty prop : getElements()) { prop.visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ContinueStatement.java0000644000175000017500000001031211314263504035203 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * A continue statement. * Node type is {@link Token#CONTINUE}.

* *

ContinueStatement :
 *   continue [no LineTerminator here] [Identifier] ;
*/ public class ContinueStatement extends Jump { private Name label; private Loop target; { type = Token.CONTINUE; } public ContinueStatement() { } public ContinueStatement(int pos) { this(pos, -1); } public ContinueStatement(int pos, int len) { // can't call super (Jump) for historical reasons position = pos; length = len; } public ContinueStatement(Name label) { setLabel(label); } public ContinueStatement(int pos, Name label) { this(pos); setLabel(label); } public ContinueStatement(int pos, int len, Name label) { this(pos, len); setLabel(label); } /** * Returns continue target */ public Loop getTarget() { return target; } /** * Sets continue target. Does NOT set the parent of the target node: * the target node is an ancestor of this node. * @param target continue target * @throws IllegalArgumentException if target is {@code null} */ public void setTarget(Loop target) { assertNotNull(target); this.target = target; setJumpStatement(target); } /** * Returns the intended label of this continue statement * @return the continue label. Will be {@code null} if the statement * consisted only of the keyword "continue". */ public Name getLabel() { return label; } /** * Sets the intended label of this continue statement. * Only applies if the statement was of the form "continue <label>". * @param label the continue label, or {@code null} if not present. */ public void setLabel(Name label) { this.label = label; if (label != null) label.setParent(this); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("continue"); if (label != null) { sb.append(" "); sb.append(label.toSource(0)); } sb.append(";\n"); return sb.toString(); } /** * Visits this node, then visits the label if non-{@code null}. */ @Override public void visit(NodeVisitor v) { if (v.visit(this) && label != null) { label.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/XmlExpression.java0000644000175000017500000000660111314263504034360 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for an embedded JavaScript expression within an E4X XML literal. * Node type, like {@link XmlLiteral}, is {@link Token#XML}. The node length * includes the curly braces. */ public class XmlExpression extends XmlFragment { private AstNode expression; private boolean isXmlAttribute; public XmlExpression() { } public XmlExpression(int pos) { super(pos); } public XmlExpression(int pos, int len) { super(pos, len); } public XmlExpression(int pos, AstNode expr) { super(pos); setExpression(expr); } /** * Returns the expression embedded in {} */ public AstNode getExpression() { return expression; } /** * Sets the expression embedded in {}, and sets its parent to this node. * @throws IllegalArgumentException if {@code expression} is {@code null} */ public void setExpression(AstNode expression) { assertNotNull(expression); this.expression = expression; expression.setParent(this); } /** * Returns whether this is part of an xml attribute value */ public boolean isXmlAttribute() { return isXmlAttribute; } /** * Sets whether this is part of an xml attribute value */ public void setIsXmlAttribute(boolean isXmlAttribute) { this.isXmlAttribute = isXmlAttribute; } @Override public String toSource(int depth) { return makeIndent(depth) + "{" + expression.toSource(depth) + "}"; } /** * Visits this node, then the child expression. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { expression.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ObjectProperty.java0000644000175000017500000001040011314263504034503 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for a single name:value entry in an Object literal. * For simple entries, the node type is {@link Token#COLON}, and * the name (left side expression) is either a {@link Name}, a * {@link StringLiteral} or a {@link NumberLiteral}.

* * This node type is also used for getter/setter properties in object * literals. In this case the node bounds include the "get" or "set" * keyword. The left-hand expression in this case is always a * {@link Name}, and the overall node type is {@link Token#GET} or * {@link Token#SET}, as appropriate.

* * The {@code operatorPosition} field is meaningless if the node is * a getter or setter.

* *

ObjectProperty :
 *       PropertyName : AssignmentExpression
 * PropertyName :
 *       Identifier
 *       StringLiteral
 *       NumberLiteral
*/ public class ObjectProperty extends InfixExpression { { type = Token.COLON; } /** * Sets the node type. Must be one of * {@link Token#COLON}, {@link Token#GET}, or {@link Token#SET}. * @throws IllegalArgumentException if {@code nodeType} is invalid */ public void setNodeType(int nodeType) { if (nodeType != Token.COLON && nodeType != Token.GET && nodeType != Token.SET) throw new IllegalArgumentException("invalid node type: " + nodeType); setType(nodeType); } public ObjectProperty() { } public ObjectProperty(int pos) { super(pos); } public ObjectProperty(int pos, int len) { super(pos, len); } /** * Marks this node as a "getter" property. */ public void setIsGetter() { type = Token.GET; } /** * Returns true if this is a getter function. */ public boolean isGetter() { return type == Token.GET; } /** * Marks this node as a "setter" property. */ public void setIsSetter() { type = Token.SET; } /** * Returns true if this is a setter function. */ public boolean isSetter() { return type == Token.SET; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); if (isGetter()) { sb.append("get "); } else if (isSetter()) { sb.append("set "); } sb.append(left.toSource(0)); if (type == Token.COLON) { sb.append(": "); } sb.append(right.toSource(0)); return sb.toString(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ExpressionStatement.java0000644000175000017500000001161411314263504035564 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node representing an expression in a statement context. The node type is * {@link Token#EXPR_VOID} if inside a function, or else * {@link Token#EXPR_RESULT} if inside a script. */ public class ExpressionStatement extends AstNode { private AstNode expr; { type = Token.EXPR_VOID; } /** * Called by the parser to set node type to EXPR_RESULT * if this node is not within a Function. */ public void setHasResult() { type = Token.EXPR_RESULT; } public ExpressionStatement() { } /** * Constructs a new {@code ExpressionStatement} wrapping * the specified expression. Sets this node's position to the * position of the wrapped node, and sets the wrapped node's * position to zero. Sets this node's length to the length of * the wrapped node. * @param expr the wrapped expression * @param hasResult {@code true} if this expression has side * effects. If true, sets node type to EXPR_RESULT, else to EXPR_VOID. */ public ExpressionStatement(AstNode expr, boolean hasResult) { this(expr); if (hasResult) setHasResult(); } /** * Constructs a new {@code ExpressionStatement} wrapping * the specified expression. Sets this node's position to the * position of the wrapped node, and sets the wrapped node's * position to zero. Sets this node's length to the length of * the wrapped node. * @param expr the wrapped expression */ public ExpressionStatement(AstNode expr) { this(expr.getPosition(), expr.getLength(), expr); } public ExpressionStatement(int pos, int len) { super(pos, len); } /** * Constructs a new {@code ExpressionStatement} * @param expr the wrapped {@link AstNode}. * The {@code ExpressionStatement}'s bounds are set to those of expr, * and expr's parent is set to this node. * @throws IllegalArgumentException if {@code expr} is null */ public ExpressionStatement(int pos, int len, AstNode expr) { super(pos, len); setExpression(expr); } /** * Returns the wrapped expression */ public AstNode getExpression() { return expr; } /** * Sets the wrapped expression, and sets its parent to this node. * @throws IllegalArgumentException} if expression is {@code null} */ public void setExpression(AstNode expression) { assertNotNull(expression); expr = expression; expression.setParent(this); setLineno(expression.getLineno()); } /** * Returns true if this node has side effects * @throws IllegalStateException if expression has not yet * been set. */ @Override public boolean hasSideEffects() { return type == Token.EXPR_RESULT || expr.hasSideEffects(); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(expr.toSource(depth)); sb.append(";\n"); return sb.toString(); } /** * Visits this node, then the wrapped statement. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { expr.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/SwitchCase.java0000644000175000017500000001311411314263504033572 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.List; /** * Switch-case AST node type. The switch case is always part of a * switch statement. * Node type is {@link Token#CASE}.

* *

CaseBlock :
 *        { [CaseClauses] }
 *        { [CaseClauses] DefaultClause [CaseClauses] }
 * CaseClauses :
 *        CaseClause
 *        CaseClauses CaseClause
 * CaseClause :
 *        case Expression : [StatementList]
 * DefaultClause :
 *        default : [StatementList]
*/ public class SwitchCase extends AstNode { private AstNode expression; private List statements; { type = Token.CASE; } public SwitchCase() { } public SwitchCase(int pos) { super(pos); } public SwitchCase(int pos, int len) { super(pos, len); } /** * Returns the case expression, {@code null} for default case */ public AstNode getExpression() { return expression; } /** * Sets the case expression, {@code null} for default case. * Note that for empty fall-through cases, they still have * a case expression. In {@code case 0: case 1: break;} the * first case has an {@code expression} that is a * {@link NumberLiteral} with value {@code 0}. */ public void setExpression(AstNode expression) { this.expression = expression; if (expression != null) expression.setParent(this); } /** * Return true if this is a default case. * @return true if {@link #getExpression} would return {@code null} */ public boolean isDefault() { return expression == null; } /** * Returns statement list, which may be {@code null}. */ public List getStatements() { return statements; } /** * Sets statement list. May be {@code null}. Replaces any existing * statements. Each element in the list has its parent set to this node. */ public void setStatements(List statements) { if (this.statements != null) { this.statements.clear(); } for (AstNode s : statements) { addStatement(s); } } /** * Adds a statement to the end of the statement list. * Sets the parent of the new statement to this node, updates * its start offset to be relative to this node, and sets the * length of this node to include the new child. * * @param statement a child statement * @throws IllegalArgumentException} if statement is {@code null} */ public void addStatement(AstNode statement) { assertNotNull(statement); if (statements == null) { statements = new ArrayList(); } int end = statement.getPosition() + statement.getLength(); this.setLength(end - this.getPosition()); statements.add(statement); statement.setParent(this); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); if (expression == null) { sb.append("default:\n"); } else { sb.append("case "); sb.append(expression.toSource(0)); sb.append(":\n"); } if (statements != null) { for (AstNode s : statements) { sb.append(s.toSource(depth+1)); } } return sb.toString(); } /** * Visits this node, then the case expression if present, then * each statement (if any are specified). */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { if (expression != null) { expression.visit(v); } if (statements != null) { for (AstNode s : statements) { s.visit(v); } } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ForLoop.java0000644000175000017500000001231111314263504033113 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * C-style for-loop statement. * Node type is {@link Token#FOR}.

* *

for ( ExpressionNoInopt; Expressionopt ; Expressionopt ) Statement
*
for ( var VariableDeclarationListNoIn; Expressionopt ; Expressionopt ) Statement
*/ public class ForLoop extends Loop { private AstNode initializer; private AstNode condition; private AstNode increment; { type = Token.FOR; } public ForLoop() { } public ForLoop(int pos) { super(pos); } public ForLoop(int pos, int len) { super(pos, len); } /** * Returns loop initializer variable declaration list. * This is either a {@link VariableDeclaration}, an * {@link Assignment}, or an {@link InfixExpression} of * type COMMA that chains multiple variable assignments. */ public AstNode getInitializer() { return initializer; } /** * Sets loop initializer expression, and sets its parent * to this node. Virtually any expression can be in the initializer, * so no error-checking is done other than a {@code null}-check. * @param initializer loop initializer. Pass an * {@link EmptyExpression} if the initializer is not specified. * @throws IllegalArgumentException if condition is {@code null} */ public void setInitializer(AstNode initializer) { assertNotNull(initializer); this.initializer = initializer; initializer.setParent(this); } /** * Returns loop condition */ public AstNode getCondition() { return condition; } /** * Sets loop condition, and sets its parent to this node. * @param condition loop condition. Pass an {@link EmptyExpression} * if the condition is missing. * @throws IllegalArgumentException} if condition is {@code null} */ public void setCondition(AstNode condition) { assertNotNull(condition); this.condition = condition; condition.setParent(this); } /** * Returns loop increment expression */ public AstNode getIncrement() { return increment; } /** * Sets loop increment expression, and sets its parent to * this node. * @param increment loop increment expression. Pass an * {@link EmptyExpression} if increment is {@code null}. * @throws IllegalArgumentException} if increment is {@code null} */ public void setIncrement(AstNode increment) { assertNotNull(increment); this.increment = increment; increment.setParent(this); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("for ("); sb.append(initializer.toSource(0)); sb.append("; "); sb.append(condition.toSource(0)); sb.append("; "); sb.append(increment.toSource(0)); sb.append(") "); if (body instanceof Block) { sb.append(body.toSource(depth).trim()).append("\n"); } else { sb.append("\n").append(body.toSource(depth+1)); } return sb.toString(); } /** * Visits this node, the initializer expression, the loop condition * expression, the increment expression, and then the loop body. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { initializer.visit(v); condition.visit(v); increment.visit(v); body.visit(v); } } } ././@LongLink0000000000000000000000000000014700000000000011217 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ArrayComprehensionLoop.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ArrayComprehensionLoop.ja0000644000175000017500000000626611314263504035662 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for a single 'for (foo in bar)' loop construct in a JavaScript 1.7 * Array comprehension. This node type is almost equivalent to a * {@link ForInLoop}, except that it has no body statement. * Node type is {@link Token#FOR}.

*/ public class ArrayComprehensionLoop extends ForInLoop { public ArrayComprehensionLoop() { } public ArrayComprehensionLoop(int pos) { super(pos); } public ArrayComprehensionLoop(int pos, int len) { super(pos, len); } /** * Returns {@code null} for loop body * @return loop body (always {@code null} for this node type) */ public AstNode getBody() { return null; } /** * Throws an exception on attempts to set the loop body. * @param body loop body * @throws UnsupportedOperationException */ public void setBody(AstNode body) { throw new UnsupportedOperationException("this node type has no body"); } @Override public String toSource(int depth) { return makeIndent(depth) + " for (" + iterator.toSource(0) + " in " + iteratedObject.toSource(0) + ")"; } /** * Visits the iterator expression and the iterated object expression. * There is no body-expression for this loop type. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { iterator.visit(v); iteratedObject.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/KeywordLiteral.java0000644000175000017500000001004111314263504034472 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for keyword literals: currently, {@code this}, * {@code null}, {@code true}, {@code false}, and {@code debugger}. * Node type is one of * {@link Token#THIS}, * {@link Token#NULL}, * {@link Token#TRUE}, * {@link Token#FALSE}, or * {@link Token#DEBUGGER}. */ public class KeywordLiteral extends AstNode { public KeywordLiteral() { } public KeywordLiteral(int pos) { super(pos); } public KeywordLiteral(int pos, int len) { super(pos, len); } /** * Constructs a new KeywordLiteral * @param nodeType the token type */ public KeywordLiteral(int pos, int len, int nodeType) { super(pos, len); setType(nodeType); } /** * Sets node token type * @throws IllegalArgumentException if {@code nodeType} is unsupported */ @Override public KeywordLiteral setType(int nodeType) { if (!(nodeType == Token.THIS || nodeType == Token.NULL || nodeType == Token.TRUE || nodeType == Token.FALSE || nodeType == Token.DEBUGGER)) throw new IllegalArgumentException("Invalid node type: " + nodeType); type = nodeType; return this; } /** * Returns true if the token type is {@link Token#TRUE} or * {@link Token#FALSE}. */ public boolean isBooleanLiteral() { return type == Token.TRUE || type == Token.FALSE; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); switch (getType()) { case Token.THIS: sb.append("this"); break; case Token.NULL: sb.append("null"); break; case Token.TRUE: sb.append("true"); break; case Token.FALSE: sb.append("false"); break; case Token.DEBUGGER: sb.append("debugger"); break; default: throw new IllegalStateException("Invalid keyword literal type: " + getType()); } return sb.toString(); } /** * Visits this node. There are no children to visit. */ @Override public void visit(NodeVisitor v) { v.visit(this); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/VariableDeclaration.java0000644000175000017500000001177611314263504035444 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.List; /** * A list of one or more var, const or let declarations. * Node type is {@link Token#VAR}, {@link Token#CONST} or * {@link Token#LET}.

* * If the node is for {@code var} or {@code const}, the node position * is the beginning of the {@code var} or {@code const} keyword. * For {@code let} declarations, the node position coincides with the * first {@link VariableInitializer} child.

* * A standalone variable declaration in a statement context is wrapped with an * {@link ExpressionStatement}. */ public class VariableDeclaration extends AstNode { private List variables = new ArrayList(); { type = Token.VAR; } public VariableDeclaration() { } public VariableDeclaration(int pos) { super(pos); } public VariableDeclaration(int pos, int len) { super(pos, len); } /** * Returns variable list. Never {@code null}. */ public List getVariables() { return variables; } /** * Sets variable list * @throws IllegalArgumentException if variables list is {@code null} */ public void setVariables(List variables) { assertNotNull(variables); this.variables.clear(); for (VariableInitializer vi : variables) { addVariable(vi); } } /** * Adds a variable initializer node to the child list. * Sets initializer node's parent to this node. * @throws IllegalArgumentException if v is {@code null} */ public void addVariable(VariableInitializer v) { assertNotNull(v); variables.add(v); v.setParent(this); } /** * Sets the node type and returns this node. * @throws IllegalArgumentException if {@code declType} is invalid */ @Override public org.mozilla.javascript.Node setType(int type) { if (type != Token.VAR && type != Token.CONST && type != Token.LET) throw new IllegalArgumentException("invalid decl type: " + type); return super.setType(type); } /** * Returns true if this is a {@code var} (not * {@code const} or {@code let}) declaration. * @return true if {@code declType} is {@link Token#VAR} */ public boolean isVar() { return type == Token.VAR; } /** * Returns true if this is a {@link Token#CONST} declaration. */ public boolean isConst() { return type == Token.CONST; } /** * Returns true if this is a {@link Token#LET} declaration. */ public boolean isLet() { return type == Token.LET; } private String declTypeName() { return Token.typeToName(type).toLowerCase(); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(declTypeName()); sb.append(" "); printList(variables, sb); return sb.toString(); } /** * Visits this node, then each {@link VariableInitializer} child. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { for (AstNode var : variables) { var.visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/AstRoot.java0000644000175000017500000001317611314263504033140 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Node; import org.mozilla.javascript.Token; import java.util.SortedSet; import java.util.TreeSet; /** * Node for the root of a parse tree. It contains the statements and functions * in the script, and a list of {@link Comment} nodes associated with the script * as a whole. Node type is {@link Token#SCRIPT}.

* * Note that the tree itself does not store errors. To collect the parse errors * and warnings, pass an {@link org.mozilla.javascript.ErrorReporter} to the * {@link org.mozilla.javascript.Parser} via the * {@link org.mozilla.javascript.CompilerEnvirons}. */ public class AstRoot extends ScriptNode { private SortedSet comments; { type = Token.SCRIPT; } public AstRoot() { } public AstRoot(int pos) { super(pos); } /** * Returns comment set * @return comment set, sorted by start position. Can be {@code null}. */ public SortedSet getComments() { return comments; } /** * Sets comment list, and updates the parent of each entry to point * to this node. Replaces any existing comments. * @param comments comment list. can be {@code null}. */ public void setComments(SortedSet comments) { if (comments == null) { this.comments = null; } else { if (this.comments != null) this.comments.clear(); for (Comment c : comments) addComment(c); } } /** * Add a comment to the comment set. * @param comment the comment node. * @throws IllegalArgumentException if comment is {@code null} */ public void addComment(Comment comment) { assertNotNull(comment); if (comments == null) { comments = new TreeSet(new AstNode.PositionComparator()); } comments.add(comment); comment.setParent(this); } /** * Visits the comment nodes in the order they appear in the source code. * The comments are not visited by the {@link #visit} function - you must * use this function to visit them. * @param visitor the callback object. It is passed each comment node. * The return value is ignored. */ public void visitComments(NodeVisitor visitor) { if (comments != null) { for (Comment c : comments) { visitor.visit(c); } } } /** * Visits the AST nodes, then the comment nodes. * This method is equivalent to calling {@link #visit}, then * {@link #visitComments}. The return value * is ignored while visiting comment nodes. * @param visitor the callback object. */ public void visitAll(NodeVisitor visitor) { visit(visitor); visitComments(visitor); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); for (Node node : this) { sb.append(((AstNode)node).toSource(depth)); } return sb.toString(); } /** * A debug-printer that includes comments (at the end). */ @Override public String debugPrint() { DebugPrintVisitor dpv = new DebugPrintVisitor(new StringBuilder(1000)); visitAll(dpv); return dpv.toString(); } /** * Debugging function to check that the parser has set the parent * link for every node in the tree. * @throws IllegalStateException if a parent link is missing */ public void checkParentLinks() { this.visit(new NodeVisitor() { public boolean visit(AstNode node) { int type = node.getType(); if (type == Token.SCRIPT) return true; if (node.getParent() == null) throw new IllegalStateException ("No parent for node: " + node + "\n" + node.toSource(0)); return true; } }); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ArrayLiteral.java0000644000175000017500000001561211314263504034135 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * AST node for an Array literal. The elements list will always be * non-{@code null}, although the list will have no elements if the Array literal * is empty.

* * Node type is {@link Token#ARRAYLIT}.

* *

ArrayLiteral :
 *        [ Elisionopt ]
 *        [ ElementList ]
 *        [ ElementList , Elisionopt ]
 * ElementList :
 *        Elisionopt AssignmentExpression
 *        ElementList , Elisionopt AssignmentExpression
 * Elision :
 *        ,
 *        Elision ,
*/ public class ArrayLiteral extends AstNode implements DestructuringForm { private static final List NO_ELEMS = Collections.unmodifiableList(new ArrayList()); private List elements; private int destructuringLength; private int skipCount; private boolean isDestructuring; { type = Token.ARRAYLIT; } public ArrayLiteral() { } public ArrayLiteral(int pos) { super(pos); } public ArrayLiteral(int pos, int len) { super(pos, len); } /** * Returns the element list * @return the element list. If there are no elements, returns an immutable * empty list. Elisions are represented as {@link EmptyExpression} * nodes. */ public List getElements() { return elements != null ? elements : NO_ELEMS; } /** * Sets the element list, and sets each element's parent to this node. * @param elements the element list. Can be {@code null}. */ public void setElements(List elements) { if (elements == null) { this.elements = null; } else { if (this.elements != null) this.elements.clear(); for (AstNode e : elements) addElement(e); } } /** * Adds an element to the list, and sets its parent to this node. * @param element the element to add * @throws IllegalArgumentException if element is {@code null}. To indicate * an empty element, use an {@link EmptyExpression} node. */ public void addElement(AstNode element) { assertNotNull(element); if (elements == null) elements = new ArrayList(); elements.add(element); element.setParent(this); } /** * Returns the number of elements in this {@code Array} literal, * including empty elements. */ public int getSize() { return elements == null ? 0 : elements.size(); } /** * Returns element at specified index. * @param index the index of the element to retrieve * @return the element * @throws IndexOutOfBoundsException if the index is invalid */ public AstNode getElement(int index) { if (elements == null) throw new IndexOutOfBoundsException("no elements"); return elements.get(index); } /** * Returns destructuring length */ public int getDestructuringLength() { return destructuringLength; } /** * Sets destructuring length. This is set by the parser and used * by the code generator. {@code for ([a,] in obj)} is legal, * but {@code for ([a] in obj)} is not since we have both key and * value supplied. The difference is only meaningful in array literals * used in destructuring-assignment contexts. */ public void setDestructuringLength(int destructuringLength) { this.destructuringLength = destructuringLength; } /** * Used by code generator. * @return the number of empty elements */ public int getSkipCount() { return skipCount; } /** * Used by code generator. * @param count the count of empty elements */ public void setSkipCount(int count) { skipCount = count; } /** * Marks this node as being a destructuring form - that is, appearing * in a context such as {@code for ([a, b] in ...)} where it's the * target of a destructuring assignment. */ public void setIsDestructuring(boolean destructuring) { isDestructuring = destructuring; } /** * Returns true if this node is in a destructuring position: * a function parameter, the target of a variable initializer, the * iterator of a for..in loop, etc. */ public boolean isDestructuring() { return isDestructuring; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("["); if (elements != null) { printList(elements, sb); } sb.append("]"); return sb.toString(); } /** * Visits this node, then visits its element expressions in order. * Any empty elements are represented by {@link EmptyExpression} * objects, so the callback will never be passed {@code null}. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { for (AstNode e : getElements()) { e.visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ElementGet.java0000644000175000017500000001120111314263504033561 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for an indexed property reference, such as {@code foo['bar']} or * {@code foo[2]}. This is sometimes called an "element-get" operation, hence * the name of the node.

* * Node type is {@link Token#GETELEM}.

* * The node bounds extend from the beginning position of the target through the * closing right-bracket. In the presence of a syntax error, the right bracket * position is -1, and the node ends at the end of the element expression. */ public class ElementGet extends AstNode { private AstNode target; private AstNode element; private int lb = -1; private int rb = -1; { type = Token.GETELEM; } public ElementGet() { } public ElementGet(int pos) { super(pos); } public ElementGet(int pos, int len) { super(pos, len); } public ElementGet(AstNode target, AstNode element) { setTarget(target); setElement(element); } /** * Returns the object on which the element is being fetched. */ public AstNode getTarget() { return target; } /** * Sets target object, and sets its parent to this node. * @param target expression evaluating to the object upon which * to do the element lookup * @throws IllegalArgumentException if target is {@code null} */ public void setTarget(AstNode target) { assertNotNull(target); this.target = target; target.setParent(this); } /** * Returns the element being accessed */ public AstNode getElement() { return element; } /** * Sets the element being accessed, and sets its parent to this node. * @throws IllegalArgumentException if element is {@code null} */ public void setElement(AstNode element) { assertNotNull(element); this.element = element; element.setParent(this); } /** * Returns left bracket position */ public int getLb() { return lb; } /** * Sets left bracket position */ public void setLb(int lb) { this.lb = lb; } /** * Returns right bracket position, -1 if missing */ public int getRb() { return rb; } /** * Sets right bracket position, -1 if not present */ public void setRb(int rb) { this.rb = rb; } public void setParens(int lb, int rb) { this.lb = lb; this.rb = rb; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(target.toSource(0)); sb.append("["); sb.append(element.toSource(0)); sb.append("]"); return sb.toString(); } /** * Visits this node, the target, and the index expression. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { target.visit(v); element.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/VariableInitializer.java0000644000175000017500000001163211314263504035471 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * A variable declaration or initializer, part of a {@link VariableDeclaration} * expression. The variable "target" can be a simple name or a destructuring * form. The initializer, if present, can be any expression.

* * Node type is one of {@link Token#VAR}, {@link Token#CONST}, or * {@link Token#LET}.

*/ public class VariableInitializer extends AstNode { private AstNode target; private AstNode initializer; { type = Token.VAR; } /** * Sets the node type. * @throws IllegalArgumentException if {@code nodeType} is not one of * {@link Token#VAR}, {@link Token#CONST}, or {@link Token#LET} */ public void setNodeType(int nodeType) { if (nodeType != Token.VAR && nodeType != Token.CONST && nodeType != Token.LET) throw new IllegalArgumentException("invalid node type"); setType(nodeType); } public VariableInitializer() { } public VariableInitializer(int pos) { super(pos); } public VariableInitializer(int pos, int len) { super(pos, len); } /** * Returns true if this is a destructuring assignment. If so, the * initializer must be non-{@code null}. * @return {@code true} if the {@code target} field is a destructuring form * (an {@link ArrayLiteral} or {@link ObjectLiteral} node) */ public boolean isDestructuring() { return !(target instanceof Name); } /** * Returns the variable name or destructuring form */ public AstNode getTarget() { return target; } /** * Sets the variable name or destructuring form, and sets * its parent to this node. * @throws IllegalArgumentException if target is {@code null} */ public void setTarget(AstNode target) { // Don't throw exception if target is an "invalid" node type. // See mozilla/js/tests/js1_7/block/regress-350279.js if (target == null) throw new IllegalArgumentException("invalid target arg"); this.target = target; target.setParent(this); } /** * Returns the initial value, or {@code null} if not provided */ public AstNode getInitializer() { return initializer; } /** * Sets the initial value expression, and sets its parent to this node. * @param initializer the initial value. May be {@code null}. */ public void setInitializer(AstNode initializer) { this.initializer = initializer; if (initializer != null) initializer.setParent(this); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(target.toSource(0)); if (initializer != null) { sb.append (" = "); sb.append(initializer.toSource(0)); } return sb.toString(); } /** * Visits this node, then the target expression, then the initializer * expression if present. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { target.visit(v); if (initializer != null) { initializer.visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/LabeledStatement.java0000644000175000017500000001124511314263504034755 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.List; /** * A labeled statement. A statement can have more than one label. In * this AST representation, all labels for a statement are collapsed into * the "labels" list of a single {@link LabeledStatement} node.

* * Node type is {@link Token#EXPR_VOID}.

*/ public class LabeledStatement extends AstNode { private List

*/ public class ArrayComprehension extends Scope { private AstNode result; private List loops = new ArrayList(); private AstNode filter; private int ifPosition = -1; private int lp = -1; private int rp = -1; { type = Token.ARRAYCOMP; } public ArrayComprehension() { } public ArrayComprehension(int pos) { super(pos); } public ArrayComprehension(int pos, int len) { super(pos, len); } /** * Returns result expression node (just after opening bracket) */ public AstNode getResult() { return result; } /** * Sets result expression, and sets its parent to this node. * @throws IllegalArgumentException if result is {@code null} */ public void setResult(AstNode result) { assertNotNull(result); this.result = result; result.setParent(this); } /** * Returns loop list */ public List getLoops() { return loops; } /** * Sets loop list * @throws IllegalArgumentException if loops is {@code null} */ public void setLoops(List loops) { assertNotNull(loops); this.loops.clear(); for (ArrayComprehensionLoop acl : loops) { addLoop(acl); } } /** * Adds a child loop node, and sets its parent to this node. * @throws IllegalArgumentException if acl is {@code null} */ public void addLoop(ArrayComprehensionLoop acl) { assertNotNull(acl); loops.add(acl); acl.setParent(this); } /** * Returns filter expression, or {@code null} if not present */ public AstNode getFilter() { return filter; } /** * Sets filter expression, and sets its parent to this node. * Can be {@code null}. */ public void setFilter(AstNode filter) { this.filter = filter; if (filter != null) filter.setParent(this); } /** * Returns position of 'if' keyword, -1 if not present */ public int getIfPosition() { return ifPosition; } /** * Sets position of 'if' keyword */ public void setIfPosition(int ifPosition) { this.ifPosition = ifPosition; } /** * Returns filter left paren position, or -1 if no filter */ public int getFilterLp() { return lp; } /** * Sets filter left paren position, or -1 if no filter */ public void setFilterLp(int lp) { this.lp = lp; } /** * Returns filter right paren position, or -1 if no filter */ public int getFilterRp() { return rp; } /** * Sets filter right paren position, or -1 if no filter */ public void setFilterRp(int rp) { this.rp = rp; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(250); sb.append("["); sb.append(result.toSource(0)); for (ArrayComprehensionLoop loop : loops) { sb.append(loop.toSource(0)); } if (filter != null) { sb.append(" if ("); sb.append(filter.toSource(0)); sb.append(")"); } sb.append("]"); return sb.toString(); } /** * Visits this node, the result expression, the loops, and the optional * filter. */ @Override public void visit(NodeVisitor v) { if (!v.visit(this)) { return; } result.visit(v); for (ArrayComprehensionLoop loop : loops) { loop.visit(v); } if (filter != null) { filter.visit(v); } } } ././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ParenthesizedExpression.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ParenthesizedExpression.j0000644000175000017500000000637011314263504035740 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for a parenthesized expression. * Node type is {@link Token#LP}.

*/ public class ParenthesizedExpression extends AstNode { private AstNode expression; { type = Token.LP; } public ParenthesizedExpression() { } public ParenthesizedExpression(int pos) { super(pos); } public ParenthesizedExpression(int pos, int len) { super(pos, len); } public ParenthesizedExpression(AstNode expr) { this(expr != null ? expr.getPosition() : 0, expr != null ? expr.getLength() : 1, expr); } public ParenthesizedExpression(int pos, int len, AstNode expr) { super(pos, len); setExpression(expr); } /** * Returns the expression between the parens */ public AstNode getExpression() { return expression; } /** * Sets the expression between the parens, and sets the parent * to this node. * @param expression the expression between the parens * @throws IllegalArgumentException} if expression is {@code null} */ public void setExpression(AstNode expression) { assertNotNull(expression); this.expression = expression; expression.setParent(this); } @Override public String toSource(int depth) { return makeIndent(depth) + "(" + expression.toSource(0) + ")"; } /** * Visits this node, then the child expression. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { expression.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/Jump.java0000644000175000017500000001151211314263504032450 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Roshan James * Roger Lawrence * Mike McCabe * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Node; import org.mozilla.javascript.Token; /** * Used for code generation. During codegen, the AST is transformed * into an Intermediate Representation (IR) in which loops, ifs, switches * and other control-flow statements are rewritten as labeled jumps. * If the parser is set to IDE-mode, the resulting AST will not contain * any instances of this class. */ public class Jump extends AstNode { public Node target; private Node target2; private Jump jumpNode; public Jump() { type = Token.ERROR; } public Jump(int nodeType) { type = nodeType; } public Jump(int type, int lineno) { this(type); setLineno(lineno); } public Jump(int type, Node child) { this(type); addChildToBack(child); } public Jump(int type, Node child, int lineno) { this(type, child); setLineno(lineno); } public Jump getJumpStatement() { if (type != Token.BREAK && type != Token.CONTINUE) codeBug(); return jumpNode; } public void setJumpStatement(Jump jumpStatement) { if (type != Token.BREAK && type != Token.CONTINUE) codeBug(); if (jumpStatement == null) codeBug(); if (this.jumpNode != null) codeBug(); //only once this.jumpNode = jumpStatement; } public Node getDefault() { if (type != Token.SWITCH) codeBug(); return target2; } public void setDefault(Node defaultTarget) { if (type != Token.SWITCH) codeBug(); if (defaultTarget.getType() != Token.TARGET) codeBug(); if (target2 != null) codeBug(); //only once target2 = defaultTarget; } public Node getFinally() { if (type != Token.TRY) codeBug(); return target2; } public void setFinally(Node finallyTarget) { if (type != Token.TRY) codeBug(); if (finallyTarget.getType() != Token.TARGET) codeBug(); if (target2 != null) codeBug(); //only once target2 = finallyTarget; } public Jump getLoop() { if (type != Token.LABEL) codeBug(); return jumpNode; } public void setLoop(Jump loop) { if (type != Token.LABEL) codeBug(); if (loop == null) codeBug(); if (jumpNode != null) codeBug(); //only once jumpNode = loop; } public Node getContinue() { if (type != Token.LOOP) codeBug(); return target2; } public void setContinue(Node continueTarget) { if (type != Token.LOOP) codeBug(); if (continueTarget.getType() != Token.TARGET) codeBug(); if (target2 != null) codeBug(); //only once target2 = continueTarget; } /** * Jumps are only used directly during code generation, and do * not support this interface. * @throws UnsupportedOperationException */ @Override public void visit(NodeVisitor visitor) { throw new UnsupportedOperationException(this.toString()); } @Override public String toSource(int depth) { throw new UnsupportedOperationException(this.toString()); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/StringLiteral.java0000644000175000017500000000760611314263504034331 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for a single- or double-quoted string literal. * Node type is {@link Token#STRING}.

*/ public class StringLiteral extends AstNode { private String value; private char quoteChar; { type = Token.STRING; } public StringLiteral() { } public StringLiteral(int pos) { super(pos); } /** * Creates a string literal node at the specified position. * @param len the length including the enclosing quotes */ public StringLiteral(int pos, int len) { super(pos, len); } /** * Returns the node's value: the parsed string without the enclosing quotes * @return the node's value, a {@link String} of unescaped characters * that includes the delimiter quotes. */ public String getValue() { return value; } /** * Returns the string value, optionally including the enclosing quotes. */ public String getValue(boolean includeQuotes) { if (!includeQuotes) return value; return quoteChar + value + quoteChar; } /** * Sets the node's value. Do not include the enclosing quotes. * @param value the node's value * @throws IllegalArgumentException} if value is {@code null} */ public void setValue(String value) { assertNotNull(value); this.value = value; } /** * Returns the character used as the delimiter for this string. */ public char getQuoteCharacter() { return quoteChar; } public void setQuoteCharacter(char c) { quoteChar = c; } @Override public String toSource(int depth) { // TODO(stevey): make sure this unescapes everything properly String q = String.valueOf(getQuoteCharacter()); String rep = "\\\\" + q; String s = value.replaceAll(q, rep); s = s.replaceAll("\n", "\\\\n"); s = s.replaceAll("\r", "\\\\r"); s = s.replaceAll("\t", "\\\\t"); s = s.replaceAll("\f", "\\\\f"); return makeIndent(depth) + q + s + q; } /** * Visits this node. There are no children to visit. */ @Override public void visit(NodeVisitor v) { v.visit(this); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/Yield.java0000644000175000017500000000604111314263504032604 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for JavaScript 1.7 {@code yield} expression or statement. * Node type is {@link Token#YIELD}.

* *

Yield :
 *   yield [no LineTerminator here] [non-paren Expression] ;
*/ public class Yield extends AstNode { private AstNode value; { type = Token.YIELD; } public Yield() { } public Yield(int pos) { super(pos); } public Yield(int pos, int len) { super(pos, len); } public Yield(int pos, int len, AstNode value) { super(pos, len); setValue(value); } /** * Returns yielded expression, {@code null} if none */ public AstNode getValue() { return value; } /** * Sets yielded expression, and sets its parent to this node. * @param expr the value to yield. Can be {@code null}. */ public void setValue(AstNode expr) { this.value = expr; if (expr != null) expr.setParent(this); } @Override public String toSource(int depth) { return value == null ? "yield" : "yield " + value.toSource(0); } /** * Visits this node, and if present, the yielded value. */ @Override public void visit(NodeVisitor v) { if (v.visit(this) && value != null) { value.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ParseProblem.java0000644000175000017500000000652311314263504034136 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; /** * Encapsulates information for a JavaScript parse error or warning. */ public class ParseProblem { public static enum Type {Error, Warning} private Type type; private String message; private String sourceName; private int offset; private int length; /** * Constructs a new ParseProblem. */ public ParseProblem(ParseProblem.Type type, String message, String sourceName, int offset, int length) { setType(type); setMessage(message); setSourceName(sourceName); setFileOffset(offset); setLength(length); } public ParseProblem.Type getType() { return type; } public void setType(ParseProblem.Type type) { this.type = type; } public String getMessage() { return message; } public void setMessage(String msg) { this.message = msg; } public String getSourceName() { return sourceName; } public void setSourceName(String name) { this.sourceName = name; } public int getFileOffset() { return offset; } public void setFileOffset(int offset) { this.offset = offset; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } @Override public String toString() { StringBuilder sb = new StringBuilder(200); sb.append(sourceName).append(":"); sb.append("offset=").append(offset).append(","); sb.append("length=").append(length).append(","); sb.append(type == Type.Error ? "error: " : "warning: "); sb.append(message); return sb.toString(); } } ././@LongLink0000000000000000000000000000014600000000000011216 Lustar 00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ConditionalExpression.javajenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ConditionalExpression.jav0000644000175000017500000001367311314263504035731 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node representing the ternary operator. Node type is * {@link Token#HOOK}. * *
ConditionalExpression :
 *        LogicalORExpression
 *        LogicalORExpression ? AssignmentExpression
 *                            : AssignmentExpression
* * ConditionalExpressionNoIn : * LogicalORExpressionNoIn * LogicalORExpressionNoIn ? AssignmentExpression * : AssignmentExpressionNoIn */ public class ConditionalExpression extends AstNode { private AstNode testExpression; private AstNode trueExpression; private AstNode falseExpression; private int questionMarkPosition = -1; private int colonPosition = -1; { type = Token.HOOK; } public ConditionalExpression() { } public ConditionalExpression(int pos) { super(pos); } public ConditionalExpression(int pos, int len) { super(pos, len); } /** * Returns test expression */ public AstNode getTestExpression() { return testExpression; } /** * Sets test expression, and sets its parent. * @param testExpression test expression * @throws IllegalArgumentException if testExpression is {@code null} */ public void setTestExpression(AstNode testExpression) { assertNotNull(testExpression); this.testExpression = testExpression; testExpression.setParent(this); } /** * Returns expression to evaluate if test is true */ public AstNode getTrueExpression() { return trueExpression; } /** * Sets expression to evaluate if test is true, and * sets its parent to this node. * @param trueExpression expression to evaluate if test is true * @throws IllegalArgumentException if expression is {@code null} */ public void setTrueExpression(AstNode trueExpression) { assertNotNull(trueExpression); this.trueExpression = trueExpression; trueExpression.setParent(this); } /** * Returns expression to evaluate if test is false */ public AstNode getFalseExpression() { return falseExpression; } /** * Sets expression to evaluate if test is false, and sets its * parent to this node. * @param falseExpression expression to evaluate if test is false * @throws IllegalArgumentException if {@code falseExpression} * is {@code null} */ public void setFalseExpression(AstNode falseExpression) { assertNotNull(falseExpression); this.falseExpression = falseExpression; falseExpression.setParent(this); } /** * Returns position of ? token */ public int getQuestionMarkPosition() { return questionMarkPosition; } /** * Sets position of ? token * @param questionMarkPosition position of ? token */ public void setQuestionMarkPosition(int questionMarkPosition) { this.questionMarkPosition = questionMarkPosition; } /** * Returns position of : token */ public int getColonPosition() { return colonPosition; } /** * Sets position of : token * @param colonPosition position of : token */ public void setColonPosition(int colonPosition) { this.colonPosition = colonPosition; } @Override public boolean hasSideEffects() { if (testExpression == null || trueExpression == null || falseExpression == null) codeBug(); return trueExpression.hasSideEffects() && falseExpression.hasSideEffects(); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(testExpression.toSource(depth)); sb.append(" ? "); sb.append(trueExpression.toSource(0)); sb.append(" : "); sb.append(falseExpression.toSource(0)); return sb.toString(); } /** * Visits this node, then the test-expression, the true-expression, * and the false-expression. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { testExpression.visit(v); trueExpression.visit(v); falseExpression.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ThrowStatement.java0000644000175000017500000000663111314263504034533 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * Throw statement. Node type is {@link Token#THROW}.

* *

ThrowStatement :
 *      throw [no LineTerminator here] Expression ;
*/ public class ThrowStatement extends AstNode { private AstNode expression; { type = Token.THROW; } public ThrowStatement() { } public ThrowStatement(int pos) { super(pos); } public ThrowStatement(int pos, int len) { super(pos, len); } public ThrowStatement(AstNode expr) { setExpression(expr); } public ThrowStatement(int pos, AstNode expr) { super(pos, expr.getLength()); setExpression(expr); } public ThrowStatement(int pos, int len, AstNode expr) { super(pos, len); setExpression(expr); } /** * Returns the expression being thrown */ public AstNode getExpression() { return expression; } /** * Sets the expression being thrown, and sets its parent * to this node. * @throws IllegalArgumentException} if expression is {@code null} */ public void setExpression(AstNode expression) { assertNotNull(expression); this.expression = expression; expression.setParent(this); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("throw"); sb.append(" "); sb.append(expression.toSource(0)); sb.append(";\n"); return sb.toString(); } /** * Visits this node, then the thrown expression. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { expression.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/LetNode.java0000644000175000017500000001171111314263504033070 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for let statements and expressions. * Node type is {@link Token#LET} or {@link Token#LETEXPR}.

* *

 LetStatement:
 *     let ( VariableDeclarationList ) Block
 * LetExpression:
 *     let ( VariableDeclarationList ) Expression
* * Note that standalone let-statements with no parens or body block, * such as {@code let x=6, y=7;}, are represented as a * {@link VariableDeclaration} node of type {@code Token.LET}, * wrapped with an {@link ExpressionStatement}.

*/ public class LetNode extends Scope { private VariableDeclaration variables; private AstNode body; private int lp = -1; private int rp = -1; { type = Token.LETEXPR; } public LetNode() { } public LetNode(int pos) { super(pos); } public LetNode(int pos, int len) { super(pos, len); } /** * Returns variable list */ public VariableDeclaration getVariables() { return variables; } /** * Sets variable list. Sets list parent to this node. * @throws IllegalArgumentException if variables is {@code null} */ public void setVariables(VariableDeclaration variables) { assertNotNull(variables); this.variables = variables; variables.setParent(this); } /** * Returns body statement or expression. Body is {@code null} if the * form of the let statement is similar to a VariableDeclaration, with no * curly-brace. (This form is used to define let-bound variables in the * scope of the current block.)

* * @return the body form */ public AstNode getBody() { return body; } /** * Sets body statement or expression. Also sets the body parent to this * node. * @param body the body statement or expression. May be * {@code null}. */ public void setBody(AstNode body) { this.body = body; if (body != null) body.setParent(this); } /** * Returns left paren position, -1 if missing */ public int getLp() { return lp; } /** * Sets left paren position */ public void setLp(int lp) { this.lp = lp; } /** * Returns right paren position, -1 if missing */ public int getRp() { return rp; } /** * Sets right paren position */ public void setRp(int rp) { this.rp = rp; } /** * Sets both paren positions */ public void setParens(int lp, int rp) { this.lp = lp; this.rp = rp; } @Override public String toSource(int depth) { String pad = makeIndent(depth); StringBuilder sb = new StringBuilder(); sb.append(pad); sb.append("let ("); printList(variables.getVariables(), sb); sb.append(") "); if (body != null) { sb.append(body.toSource(depth)); } return sb.toString(); } /** * Visits this node, the variable list, and if present, the body * expression or statement. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { variables.visit(v); if (body != null) { body.visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/XmlDotQuery.java0000644000175000017500000000644311314263504034001 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node representing an E4X {@code foo.(bar)} query expression. * The node type (operator) is {@link Token#DOTQUERY}. * Its {@code getLeft} node is the target ("foo" in the example), * and the {@code getRight} node is the filter expression node.

* * This class exists separately from {@link InfixExpression} largely because it * has different printing needs. The position of the left paren is just after * the dot (operator) position, and the right paren is the final position in the * bounds of the node. If the right paren is missing, the node ends at the end * of the filter expression. */ public class XmlDotQuery extends InfixExpression { private int rp = -1; { type = Token.DOTQUERY; } public XmlDotQuery() { } public XmlDotQuery(int pos) { super(pos); } public XmlDotQuery(int pos, int len) { super(pos, len); } /** * Returns right-paren position, -1 if missing.

* * Note that the left-paren is automatically the character * immediately after the "." in the operator - no whitespace is * permitted between the dot and lp by the scanner. */ public int getRp() { return rp; } /** * Sets right-paren position */ public void setRp(int rp) { this.rp = rp; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(getLeft().toSource(0)); sb.append(".("); sb.append(getRight().toSource(0)); sb.append(")"); return sb.toString(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ErrorNode.java0000644000175000017500000000512711314263504033441 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node representing a parse error or a warning. Node type is * {@link Token#ERROR}.

*/ public class ErrorNode extends AstNode { private String message; { type = Token.ERROR; } public ErrorNode() { } public ErrorNode(int pos) { super(pos); } public ErrorNode(int pos, int len) { super(pos, len); } /** * Returns error message key */ public String getMessage() { return message; } /** * Sets error message key */ public void setMessage(String message) { this.message = message; } @Override public String toSource(int depth) { return ""; } /** * Error nodes are not visited during normal visitor traversals, * but comply with the {@link AstNode#visit} interface. */ @Override public void visit(NodeVisitor v) { v.visit(this); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/XmlPropRef.java0000644000175000017500000000734611314263504033605 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for an E4X XML {@code [expr]} property-ref expression. * The node type is {@link Token#REF_NAME}.

* * Syntax:

* *

 @opt ns:: opt name
* * Examples include {@code name}, {@code ns::name}, {@code ns::*}, * {@code *::name}, {@code *::*}, {@code @attr}, {@code @ns::attr}, * {@code @ns::*}, {@code @*::attr}, {@code @*::*} and {@code @*}.

* * The node starts at the {@code @} token, if present. Otherwise it starts * at the namespace name. The node bounds extend through the closing * right-bracket, or if it is missing due to a syntax error, through the * end of the index expression.

*/ public class XmlPropRef extends XmlRef { private Name propName; { type = Token.REF_NAME; } public XmlPropRef() { } public XmlPropRef(int pos) { super(pos); } public XmlPropRef(int pos, int len) { super(pos, len); } /** * Returns property name. */ public Name getPropName() { return propName; } /** * Sets property name, and sets its parent to this node. * @throws IllegalArgumentException if {@code propName} is {@code null} */ public void setPropName(Name propName) { assertNotNull(propName); this.propName = propName; propName.setParent(this); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); if (isAttributeAccess()) { sb.append("@"); } if (namespace != null) { sb.append(namespace.toSource(0)); sb.append("::"); } sb.append(propName.toSource(0)); return sb.toString(); } /** * Visits this node, then the namespace if present, then the property name. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { if (namespace != null) { namespace.visit(v); } propName.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/Scope.java0000644000175000017500000002112211314263504032604 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Roger Lawrence * Mike McCabe * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Node; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Represents a scope in the lexical scope chain. Base type for * all {@link AstNode} implementations that can introduce a new scope. */ public class Scope extends Jump { // Use LinkedHashMap so that the iteration order is the insertion order protected Map symbolTable; protected Scope parentScope; protected ScriptNode top; // current script or function scope private List childScopes; { this.type = Token.BLOCK; } public Scope() { } public Scope(int pos) { this.position = pos; } public Scope(int pos, int len) { this(pos); this.length = len; } public Scope getParentScope() { return parentScope; } /** * Sets parent scope */ public void setParentScope(Scope parentScope) { this.parentScope = parentScope; this.top = parentScope == null ? (ScriptNode)this : parentScope.top; } /** * Used only for code generation. */ public void clearParentScope() { this.parentScope = null; } /** * Return a list of the scopes whose parent is this scope. * @return the list of scopes we enclose, or {@code null} if none */ public List getChildScopes() { return childScopes; } /** * Add a scope to our list of child scopes. * Sets the child's parent scope to this scope. * @throws IllegalStateException if the child's parent scope is * non-{@code null} */ public void addChildScope(Scope child) { if (childScopes == null) { childScopes = new ArrayList(); } childScopes.add(child); child.setParentScope(this); } /** * Used by the parser; not intended for typical use. * Changes the parent-scope links for this scope's child scopes * to the specified new scope. Copies symbols from this scope * into new scope. * * @param newScope the scope that will replace this one on the * scope stack. */ public void replaceWith(Scope newScope) { if (childScopes != null) { for (Scope kid : childScopes) { newScope.addChildScope(kid); // sets kid's parent } childScopes.clear(); childScopes = null; } if (symbolTable != null && !symbolTable.isEmpty()) { joinScopes(this, newScope); } } /** * Returns current script or function scope */ public ScriptNode getTop() { return top; } /** * Sets top current script or function scope */ public void setTop(ScriptNode top) { this.top = top; } /** * Creates a new scope node, moving symbol table information * from "scope" to the new node, and making "scope" a nested * scope contained by the new node. * Useful for injecting a new scope in a scope chain. */ public static Scope splitScope(Scope scope) { Scope result = new Scope(scope.getType()); result.symbolTable = scope.symbolTable; scope.symbolTable = null; result.parent = scope.parent; result.setParentScope(scope.getParentScope()); result.setParentScope(result); scope.parent = result; result.top = scope.top; return result; } /** * Copies all symbols from source scope to dest scope. */ public static void joinScopes(Scope source, Scope dest) { Map src = source.ensureSymbolTable(); Map dst = dest.ensureSymbolTable(); if (!Collections.disjoint(src.keySet(), dst.keySet())) { codeBug(); } for (Map.Entry entry: src.entrySet()) { Symbol sym = entry.getValue(); sym.setContainingTable(dest); dst.put(entry.getKey(), sym); } } /** * Returns the scope in which this name is defined * @param name the symbol to look up * @return this {@link Scope}, one of its parent scopes, or {@code null} if * the name is not defined any this scope chain */ public Scope getDefiningScope(String name) { for (Scope s = this; s != null; s = s.parentScope) { Map symbolTable = s.getSymbolTable(); if (symbolTable != null && symbolTable.containsKey(name)) { return s; } } return null; } /** * Looks up a symbol in this scope. * @param name the symbol name * @return the Symbol, or {@code null} if not found */ public Symbol getSymbol(String name) { return symbolTable == null ? null : symbolTable.get(name); } /** * Enters a symbol into this scope. */ public void putSymbol(Symbol symbol) { if (symbol.getName() == null) throw new IllegalArgumentException("null symbol name"); ensureSymbolTable(); symbolTable.put(symbol.getName(), symbol); symbol.setContainingTable(this); top.addSymbol(symbol); } /** * Returns the symbol table for this scope. * @return the symbol table. May be {@code null}. */ public Map getSymbolTable() { return symbolTable; } /** * Sets the symbol table for this scope. May be {@code null}. */ public void setSymbolTable(Map table) { symbolTable = table; } private Map ensureSymbolTable() { if (symbolTable == null) { symbolTable = new LinkedHashMap(5); } return symbolTable; } /** * Returns a copy of the child list, with each child cast to an * {@link AstNode}. * @throws ClassCastException if any non-{@code AstNode} objects are * in the child list, e.g. if this method is called after the code * generator begins the tree transformation. */ public List getStatements() { List stmts = new ArrayList(); Node n = getFirstChild(); while (n != null) { stmts.add((AstNode)n); n = n.getNext(); } return stmts; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("{\n"); for (Node kid : this) { sb.append(((AstNode)kid).toSource(depth+1)); } sb.append(makeIndent(depth)); sb.append("}\n"); return sb.toString(); } @Override public void visit(NodeVisitor v) { if (v.visit(this)) { for (Node kid : this) { ((AstNode)kid).visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/AstNode.java0000644000175000017500000005317211314263504033102 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Kit; import org.mozilla.javascript.Node; import org.mozilla.javascript.Token; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Base class for AST node types. The goal of the AST is to represent the * physical source code, to make it useful for code-processing tools such * as IDEs or pretty-printers. The parser must not rewrite the parse tree * when producing this representation.

* * The {@code AstNode} hierarchy sits atop the older {@link Node} class, * which was designed for code generation. The {@code Node} class is a * flexible, weakly-typed class suitable for creating and rewriting code * trees, but using it requires you to remember the exact ordering of the * child nodes, which are kept in a linked list. The {@code AstNode} * hierarchy is a strongly-typed facade with named accessors for children * and common properties, but under the hood it's still using a linked list * of child nodes. It isn't a very good idea to use the child list directly * unless you know exactly what you're doing.

* * Note that {@code AstNode} records additional information, including * the node's position, length, and parent node. Also, some {@code AstNode} * subclasses record some of their child nodes in instance members, since * they are not needed for code generation. In a nutshell, only the code * generator should be mixing and matching {@code AstNode} and {@code Node} * objects.

* * All offset fields in all subclasses of AstNode are relative to their * parent. For things like paren, bracket and keyword positions, the * position is relative to the current node. The node start position is * relative to the parent node.

* * During the actual parsing, node positions are absolute; adding the node to * its parent fixes up the offsets to be relative. By the time you see the AST * (e.g. using the {@code Visitor} interface), the offsets are relative.

* * {@code AstNode} objects have property lists accessible via the * {@link #getProp} and {@link #putProp} methods. The property lists are * integer-keyed with arbitrary {@code Object} values. For the most part the * parser generating the AST avoids using properties, preferring fields for * elements that are always set. Property lists are intended for user-defined * annotations to the tree. The Rhino code generator acts as a client and * uses node properties extensively. You are welcome to use the property-list * API for anything your client needs.

* * This hierarchy does not have separate branches for expressions and * statements, as the distinction in JavaScript is not as clear-cut as in * Java or C++.

*/ public abstract class AstNode extends Node implements Comparable { protected int position = -1; protected int length = 1; protected AstNode parent; private static Map operatorNames = new HashMap(); static { operatorNames.put(Token.IN, "in"); operatorNames.put(Token.TYPEOF, "typeof"); operatorNames.put(Token.INSTANCEOF, "instanceof"); operatorNames.put(Token.DELPROP, "delete"); operatorNames.put(Token.COMMA, ","); operatorNames.put(Token.COLON, ":"); operatorNames.put(Token.OR, "||"); operatorNames.put(Token.AND, "&&"); operatorNames.put(Token.INC, "++"); operatorNames.put(Token.DEC, "--"); operatorNames.put(Token.BITOR, "|"); operatorNames.put(Token.BITXOR, "^"); operatorNames.put(Token.BITAND, "&"); operatorNames.put(Token.EQ, "=="); operatorNames.put(Token.NE, "!="); operatorNames.put(Token.LT, "<"); operatorNames.put(Token.GT, ">"); operatorNames.put(Token.LE, "<="); operatorNames.put(Token.GE, ">="); operatorNames.put(Token.LSH, "<<"); operatorNames.put(Token.RSH, ">>"); operatorNames.put(Token.URSH, ">>>"); operatorNames.put(Token.ADD, "+"); operatorNames.put(Token.SUB, "-"); operatorNames.put(Token.MUL, "*"); operatorNames.put(Token.DIV, "/"); operatorNames.put(Token.MOD, "%"); operatorNames.put(Token.NOT, "!"); operatorNames.put(Token.BITNOT, "~"); operatorNames.put(Token.POS, "+"); operatorNames.put(Token.NEG, "-"); operatorNames.put(Token.SHEQ, "==="); operatorNames.put(Token.SHNE, "!=="); operatorNames.put(Token.ASSIGN, "="); operatorNames.put(Token.ASSIGN_BITOR, "|="); operatorNames.put(Token.ASSIGN_BITAND, "&="); operatorNames.put(Token.ASSIGN_LSH, "<<="); operatorNames.put(Token.ASSIGN_RSH, ">>="); operatorNames.put(Token.ASSIGN_URSH, ">>>="); operatorNames.put(Token.ASSIGN_ADD, "+="); operatorNames.put(Token.ASSIGN_SUB, "-="); operatorNames.put(Token.ASSIGN_MUL, "*="); operatorNames.put(Token.ASSIGN_DIV, "/="); operatorNames.put(Token.ASSIGN_MOD, "%="); } public static class PositionComparator implements Comparator { /** * Sorts nodes by (relative) start position. The start positions are * relative to their parent, so this comparator is only meaningful for * comparing siblings. */ public int compare(AstNode n1, AstNode n2) { return n1.position - n2.position; } } public AstNode() { super(Token.ERROR); } /** * Constructs a new AstNode * @param pos the start position */ public AstNode(int pos) { this(); position = pos; } /** * Constructs a new AstNode * @param pos the start position * @param len the number of characters spanned by the node in the source * text */ public AstNode(int pos, int len) { this(); position = pos; length = len; } /** * Returns relative position in parent */ public int getPosition() { return position; } /** * Sets relative position in parent */ public void setPosition(int position) { this.position = position; } /** * Returns the absolute document position of the node. * Computes it by adding the node's relative position * to the relative positions of all its parents. */ public int getAbsolutePosition() { int pos = position; AstNode parent = this.parent; while (parent != null) { pos += parent.getPosition(); parent = parent.getParent(); } return pos; } /** * Returns node length */ public int getLength() { return length; } /** * Sets node length */ public void setLength(int length) { this.length = length; } /** * Sets the node start and end positions. * Computes the length as ({@code end} - {@code position}). */ public void setBounds(int position, int end) { setPosition(position); setLength(end - position); } /** * Make this node's position relative to a parent. * Typically only used by the parser when constructing the node. * @param parentPosition the absolute parent position; the * current node position is assumed to be absolute and is * decremented by parentPosition. */ public void setRelative(int parentPosition) { this.position -= parentPosition; } /** * Returns the node parent, or {@code null} if it has none */ public AstNode getParent() { return parent; } /** * Sets the node parent. This method automatically adjusts the * current node's start position to be relative to the new parent. * @param parent the new parent. Can be {@code null}. */ public void setParent(AstNode parent) { if (parent == this.parent) { return; } // Convert position back to absolute. if (this.parent != null) { setRelative(-this.parent.getPosition()); } this.parent = parent; if (parent != null) { setRelative(parent.getPosition()); } } /** * Adds a child or function to the end of the block. * Sets the parent of the child to this node, and fixes up * the start position of the child to be relative to this node. * Sets the length of this node to include the new child. * @param kid the child * @throws IllegalArgumentException if kid is {@code null} */ public void addChild(AstNode kid) { assertNotNull(kid); int end = kid.getPosition() + kid.getLength(); setLength(end - this.getPosition()); addChildToBack(kid); kid.setParent(this); } /** * Returns the root of the tree containing this node. * @return the {@link AstRoot} at the root of this node's parent * chain, or {@code null} if the topmost parent is not an {@code AstRoot}. */ public AstRoot getAstRoot() { AstNode parent = this; // this node could be the AstRoot while (parent != null && !(parent instanceof AstRoot)) { parent = parent.getParent(); } return (AstRoot)parent; } /** * Emits source code for this node. Callee is responsible for calling this * function recursively on children, incrementing indent as appropriate.

* * Note: if the parser was in error-recovery mode, some AST nodes may have * {@code null} children that are expected to be non-{@code null} * when no errors are present. In this situation, the behavior of the * {@code toSource} method is undefined: {@code toSource} * implementations may assume that the AST node is error-free, since it is * intended to be invoked only at runtime after a successful parse.

* * @param depth the current recursion depth, typically beginning at 0 * when called on the root node. */ public abstract String toSource(int depth); /** * Prints the source indented to depth 0. */ public String toSource() { return this.toSource(0); } /** * Constructs an indentation string. * @param indent the number of indentation steps */ public String makeIndent(int indent) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; i++) { sb.append(" "); } return sb.toString(); } /** * Returns a short, descriptive name for the node, such as * "ArrayComprehension". */ public String shortName() { String classname = getClass().getName(); int last = classname.lastIndexOf("."); return classname.substring(last + 1); } /** * Returns the string name for this operator. * @param op the token type, e.g. {@link Token#ADD} or {@link Token#TYPEOF} * @return the source operator string, such as "+" or "typeof" */ public static String operatorToString(int op) { String result = operatorNames.get(op); if (result == null) throw new IllegalArgumentException("Invalid operator: " + op); return result; } /** * Visits this node and its children in an arbitrary order.

* * It's up to each node subclass to decide the order for processing * its children. The subclass also decides (and should document) * which child nodes are not passed to the {@code NodeVisitor}. * For instance, nodes representing keywords like {@code each} or * {@code in} may not be passed to the visitor object. The visitor * can simply query the current node for these children if desired.

* * Generally speaking, the order will be deterministic; the order is * whatever order is decided by each child node. Normally child nodes * will try to visit their children in lexical order, but there may * be exceptions to this rule.

* * @param visitor the object to call with this node and its children */ public abstract void visit(NodeVisitor visitor); // subclasses with potential side effects should override this public boolean hasSideEffects() { switch (getType()) { case Token.ASSIGN: case Token.ASSIGN_ADD: case Token.ASSIGN_BITAND: case Token.ASSIGN_BITOR: case Token.ASSIGN_BITXOR: case Token.ASSIGN_DIV: case Token.ASSIGN_LSH: case Token.ASSIGN_MOD: case Token.ASSIGN_MUL: case Token.ASSIGN_RSH: case Token.ASSIGN_SUB: case Token.ASSIGN_URSH: case Token.BLOCK: case Token.BREAK: case Token.CALL: case Token.CATCH: case Token.CATCH_SCOPE: case Token.CONST: case Token.CONTINUE: case Token.DEC: case Token.DELPROP: case Token.DEL_REF: case Token.DO: case Token.ELSE: case Token.ENTERWITH: case Token.ERROR: // Avoid cascaded error messages case Token.EXPORT: case Token.EXPR_RESULT: case Token.FINALLY: case Token.FUNCTION: case Token.FOR: case Token.GOTO: case Token.IF: case Token.IFEQ: case Token.IFNE: case Token.IMPORT: case Token.INC: case Token.JSR: case Token.LABEL: case Token.LEAVEWITH: case Token.LET: case Token.LETEXPR: case Token.LOCAL_BLOCK: case Token.LOOP: case Token.NEW: case Token.REF_CALL: case Token.RETHROW: case Token.RETURN: case Token.RETURN_RESULT: case Token.SEMI: case Token.SETELEM: case Token.SETELEM_OP: case Token.SETNAME: case Token.SETPROP: case Token.SETPROP_OP: case Token.SETVAR: case Token.SET_REF: case Token.SET_REF_OP: case Token.SWITCH: case Token.TARGET: case Token.THROW: case Token.TRY: case Token.VAR: case Token.WHILE: case Token.WITH: case Token.WITHEXPR: case Token.YIELD: return true; default: return false; } } /** * Bounces an IllegalArgumentException up if arg is {@code null}. * @param arg any method argument * @throws IllegalArgumentException if the argument is {@code null} */ protected void assertNotNull(Object arg) { if (arg == null) throw new IllegalArgumentException("arg cannot be null"); } /** * Prints a comma-separated item list into a {@link StringBuilder}. * @param items a list to print * @param sb a {@link StringBuilder} into which to print */ protected void printList(List items, StringBuilder sb) { int max = items.size(); int count = 0; for (AstNode item : items) { sb.append(item.toSource(0)); if (count++ < max-1) { sb.append(", "); } } } /** * @see Kit#codeBug */ public static RuntimeException codeBug() throws RuntimeException { throw Kit.codeBug(); } // TODO(stevey): think of a way to have polymorphic toString // methods while keeping the ability to use Node.toString for // dumping the IR with Token.printTrees. Most likely: change // Node.toString to be Node.dumpTree and change callers to use that. // For now, need original toString, to compare output to old Rhino's. // @Override // public String toString() { // return this.getClass().getName() + ": " + // Token.typeToName(getType()); // } /** * Returns the innermost enclosing function, or {@code null} if not in a * function. Begins the search with this node's parent. * @return the {@link FunctionNode} enclosing this node, else {@code null} */ public FunctionNode getEnclosingFunction() { AstNode parent = this.getParent(); while (parent != null && !(parent instanceof FunctionNode)) { parent = parent.getParent(); } return (FunctionNode)parent; } /** * Returns the innermost enclosing {@link Scope} node, or {@code null} * if we're not nested in a scope. Begins the search with this node's parent. * Note that this is not the same as the defining scope for a {@link Name}. * * @return the {@link Scope} enclosing this node, else {@code null} */ public Scope getEnclosingScope() { AstNode parent = this.getParent(); while (parent != null && !(parent instanceof Scope)) { parent = parent.getParent(); } return (Scope)parent; } /** * Permits AST nodes to be sorted based on start position and length. * This makes it easy to sort Comment and Error nodes into a set of * other AST nodes: just put them all into a {@link java.util.SortedSet}, * for instance. * @param other another node * @return -1 if this node's start position is less than {@code other}'s * start position. If tied, -1 if this node's length is less than * {@code other}'s length. If the lengths are equal, sorts abitrarily * on hashcode unless the nodes are the same per {@link #equals}. */ public int compareTo(AstNode other) { if (this.equals(other)) return 0; int abs1 = this.getAbsolutePosition(); int abs2 = other.getAbsolutePosition(); if (abs1 < abs2) return -1; if (abs2 < abs1) return 1; int len1 = this.getLength(); int len2 = other.getLength(); if (len1 < len2) return -1; if (len2 < len1) return 1; return this.hashCode() - other.hashCode(); } /** * Returns the depth of this node. The root is depth 0, its * children are depth 1, and so on. * @return the node depth in the tree */ public int depth() { return parent == null ? 0 : 1 + parent.depth(); } protected static class DebugPrintVisitor implements NodeVisitor { private StringBuilder buffer; private static final int DEBUG_INDENT = 2; public DebugPrintVisitor(StringBuilder buf) { buffer = buf; } public String toString() { return buffer.toString(); } private String makeIndent(int depth) { StringBuilder sb = new StringBuilder(DEBUG_INDENT * depth); for (int i = 0; i < (DEBUG_INDENT * depth); i++) { sb.append(" "); } return sb.toString(); } public boolean visit(AstNode node) { int tt = node.getType(); String name = Token.typeToName(tt); buffer.append(node.getAbsolutePosition()).append("\t"); buffer.append(makeIndent(node.depth())); buffer.append(name).append(" "); buffer.append(node.getPosition()).append(" "); buffer.append(node.getLength()); if (tt == Token.NAME) { buffer.append(" ").append(((Name)node).getIdentifier()); } buffer.append("\n"); return true; // process kids } } /** * Return the line number recorded for this node. * If no line number was recorded, searches the parent chain. * @return the nearest line number, or -1 if none was found */ @Override public int getLineno() { if (lineno != -1) return lineno; if (parent != null) return parent.getLineno(); return -1; } /** * Returns a debugging representation of the parse tree * starting at this node. * @return a very verbose indented printout of the tree. * The format of each line is: abs-pos name position length [identifier] */ public String debugPrint() { DebugPrintVisitor dpv = new DebugPrintVisitor(new StringBuilder(1000)); visit(dpv); return dpv.toString(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/Comment.java0000644000175000017500000001101311314263504033133 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * Node representing comments. * Node type is {@link Token#COMMENT}.

* *

JavaScript effectively has five comment types: *

    *
  1. // line comments
  2. *
  3. /* block comments *\/
  4. *
  5. /** jsdoc comments *\/
  6. *
  7. <!-- html-open line comments
  8. *
  9. ^\\s*--> html-close line comments
  10. *
* *

The first three should be familiar to Java programmers. JsDoc comments * are really just block comments with some conventions about the formatting * within the comment delimiters. Line and block comments are described in the * Ecma-262 specification.

* *

SpiderMonkey and Rhino also support HTML comment syntax, but somewhat * counterintuitively, the syntax does not produce a block comment. Instead, * everything from the string <!-- through the end of the line is considered * a comment, and if the token --> is the first non-whitespace on the line, * then the line is considered a line comment. This is to support parsing * JavaScript in <script> HTML tags that has been "hidden" from very old * browsers by surrounding it with HTML comment delimiters.

* * Note the node start position for Comment nodes is still relative to the * parent, but Comments are always stored directly in the AstRoot node, so * they are also effectively absolute offsets. */ public class Comment extends AstNode { private String value; private Token.CommentType commentType; { type = Token.COMMENT; } /** * Constructs a new Comment * @param pos the start position * @param len the length including delimiter(s) * @param type the comment type * @param value the value of the comment, as a string */ public Comment(int pos, int len, Token.CommentType type, String value) { super(pos, len); commentType = type; this.value = value; } /** * Returns the comment style */ public Token.CommentType getCommentType() { return commentType; } /** * Sets the comment style * @param type the comment style, a * {@link org.mozilla.javascript.Token.CommentType} */ public void setCommentType(Token.CommentType type) { this.commentType = type; } /** * Returns a string of the comment value. */ public String getValue() { return value; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(getLength() + 10); sb.append(makeIndent(depth)); sb.append(value); return sb.toString(); } /** * Comment nodes are not visited during normal visitor traversals, * but comply with the {@link AstNode#visit} interface. */ @Override public void visit(NodeVisitor v) { v.visit(this); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/RegExpLiteral.java0000644000175000017500000000602611314263504034250 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for a RegExp literal. * Node type is {@link Token#REGEXP}.

*/ public class RegExpLiteral extends AstNode { private String value; private String flags; { type = Token.REGEXP; } public RegExpLiteral() { } public RegExpLiteral(int pos) { super(pos); } public RegExpLiteral(int pos, int len) { super(pos, len); } /** * Returns the regexp string without delimiters */ public String getValue() { return value; } /** * Sets the regexp string without delimiters * @throws IllegalArgumentException} if value is {@code null} */ public void setValue(String value) { assertNotNull(value); this.value = value; } /** * Returns regexp flags, {@code null} or "" if no flags specified */ public String getFlags() { return flags; } /** * Sets regexp flags. Can be {@code null} or "". */ public void setFlags(String flags) { this.flags = flags; } @Override public String toSource(int depth) { return makeIndent(depth) + "/" + value + "/" + (flags == null ? "" : flags); } /** * Visits this node. There are no children to visit. */ @Override public void visit(NodeVisitor v) { v.visit(this); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/CatchClause.java0000644000175000017500000001265611314263504033726 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * Node representing a catch-clause of a try-statement. * Node type is {@link Token#CATCH}. * *

CatchClause :
 *        catch ( Identifier [if Expression] ) Block
*/ public class CatchClause extends AstNode { private Name varName; private AstNode catchCondition; private Block body; private int ifPosition = -1; private int lp = -1; private int rp = -1; { type = Token.CATCH; } public CatchClause() { } public CatchClause(int pos) { super(pos); } public CatchClause(int pos, int len) { super(pos, len); } /** * Returns catch variable node * @return catch variable */ public Name getVarName() { return varName; } /** * Sets catch variable node, and sets its parent to this node. * @param varName catch variable * @throws IllegalArgumentException if varName is {@code null} */ public void setVarName(Name varName) { assertNotNull(varName); this.varName = varName; varName.setParent(this); } /** * Returns catch condition node, if present * @return catch condition node, {@code null} if not present */ public AstNode getCatchCondition() { return catchCondition; } /** * Sets catch condition node, and sets its parent to this node. * @param catchCondition catch condition node. Can be {@code null}. */ public void setCatchCondition(AstNode catchCondition) { this.catchCondition = catchCondition; if (catchCondition != null) catchCondition.setParent(this); } /** * Returns catch body */ public Block getBody() { return body; } /** * Sets catch body, and sets its parent to this node. * @throws IllegalArgumentException if body is {@code null} */ public void setBody(Block body) { assertNotNull(body); this.body = body; body.setParent(this); } /** * Returns left paren position */ public int getLp() { return lp; } /** * Sets left paren position */ public void setLp(int lp) { this.lp = lp; } /** * Returns right paren position */ public int getRp() { return rp; } /** * Sets right paren position */ public void setRp(int rp) { this.rp = rp; } /** * Sets both paren positions */ public void setParens(int lp, int rp) { this.lp = lp; this.rp = rp; } /** * Returns position of "if" keyword * @return position of "if" keyword, if present, or -1 */ public int getIfPosition() { return ifPosition; } /** * Sets position of "if" keyword * @param ifPosition position of "if" keyword, if present, or -1 */ public void setIfPosition(int ifPosition) { this.ifPosition = ifPosition; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("catch ("); sb.append(varName.toSource(0)); if (catchCondition != null) { sb.append(" if "); sb.append(catchCondition.toSource(0)); } sb.append(") "); sb.append(body.toSource(0)); return sb.toString(); } /** * Visits this node, the catch var name node, the condition if * non-{@code null}, and the catch body. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { varName.visit(v); if (catchCondition != null) { catchCondition.visit(v); } body.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ReturnStatement.java0000644000175000017500000000645311314263504034711 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * Return statement. Node type is {@link Token#RETURN}.

* *

ReturnStatement :
 *      return [no LineTerminator here] [Expression] ;
*/ public class ReturnStatement extends AstNode { private AstNode returnValue; { type = Token.RETURN; } public ReturnStatement() { } public ReturnStatement(int pos) { super(pos); } public ReturnStatement(int pos, int len) { super(pos, len); } public ReturnStatement(int pos, int len, AstNode returnValue) { super(pos, len); setReturnValue(returnValue); } /** * Returns return value, {@code null} if return value is void */ public AstNode getReturnValue() { return returnValue; } /** * Sets return value expression, and sets its parent to this node. * Can be {@code null}. */ public void setReturnValue(AstNode returnValue) { this.returnValue = returnValue; if (returnValue != null) returnValue.setParent(this); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("return"); if (returnValue != null) { sb.append(" "); sb.append(returnValue.toSource(0)); } sb.append(";\n"); return sb.toString(); } /** * Visits this node, then the return value if specified. */ @Override public void visit(NodeVisitor v) { if (v.visit(this) && returnValue != null) { returnValue.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/Name.java0000644000175000017500000001411511314263504032417 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for a simple name. A simple name is an identifier that is * not a keyword. Node type is {@link Token#NAME}.

* * This node type is also used to represent certain non-identifier names that * are part of the language syntax. It's used for the "get" and "set" * pseudo-keywords for object-initializer getter/setter properties, and it's * also used for the "*" wildcard in E4X XML namespace and name expressions. */ public class Name extends AstNode { private String identifier; private Scope scope; { type = Token.NAME; } public Name() { } public Name(int pos) { super(pos); } public Name(int pos, int len) { super(pos, len); } /** * Constructs a new {@link Name} * @param pos node start position * @param len node length * @param name the identifier associated with this {@code Name} node */ public Name(int pos, int len, String name) { super(pos, len); setIdentifier(name); } public Name(int pos, String name) { super(pos); setIdentifier(name); setLength(name.length()); } /** * Returns the node's identifier */ public String getIdentifier() { return identifier; } /** * Sets the node's identifier * @throws IllegalArgumentException if identifier is null */ public void setIdentifier(String identifier) { assertNotNull(identifier); this.identifier = identifier; setLength(identifier.length()); } /** * Set the {@link Scope} associated with this node. This method does not * set the scope's ast-node field to this node. The field exists only * for temporary storage by the code generator. Not every name has an * associated scope - typically only function and variable names (but not * property names) are registered in a scope. * * @param s the scope. Can be null. Doesn't set any fields in the * scope. */ public void setScope(Scope s) { scope = s; } /** * Return the {@link Scope} associated with this node. This is * only used for (and set by) the code generator, so it will always * be null in frontend AST-processing code. Use {@link #getDefiningScope} * to find the lexical {@code Scope} in which this {@code Name} is defined, * if any. */ public Scope getScope() { return scope; } /** * Returns the {@link Scope} in which this {@code Name} is defined. * @return the scope in which this name is defined, or {@code null} * if it's not defined in the current lexical scope chain */ public Scope getDefiningScope() { Scope enclosing = getEnclosingScope(); String name = getIdentifier(); return enclosing == null ? null : enclosing.getDefiningScope(name); } /** * Return true if this node is known to be defined as a symbol in a * lexical scope other than the top-level (global) scope. * * @return {@code true} if this name appears as local variable, a let-bound * variable not in the global scope, a function parameter, a loop * variable, the property named in a {@link PropertyGet}, or in any other * context where the node is known not to resolve to the global scope. * Returns {@code false} if the node is defined in the top-level scope * (i.e., its defining scope is an {@link AstRoot} object), or if its * name is not defined as a symbol in the symbol table, in which case it * may be an external or built-in name (or just an error of some sort.) */ public boolean isLocalName() { Scope scope = getDefiningScope(); return scope != null && scope.getParentScope() != null; } /** * Return the length of this node's identifier, to let you pretend * it's a {@link String}. Don't confuse this method with the * {@link AstNode#getLength} method, which returns the range of * characters that this node overlaps in the source input. */ public int length() { return identifier == null ? 0 : identifier.length(); } @Override public String toSource(int depth) { return makeIndent(depth) + (identifier == null ? "" : identifier); } /** * Visits this node. There are no children to visit. */ @Override public void visit(NodeVisitor v) { v.visit(this); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/NewExpression.java0000644000175000017500000001005311314263504034345 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * New expression. Node type is {@link Token#NEW}.

* *

NewExpression :
 *      MemberExpression
 *      new NewExpression
* * This node is a subtype of {@link FunctionCall}, mostly for internal code * sharing. Structurally a {@code NewExpression} node is very similar to a * {@code FunctionCall}, so it made a certain amount of sense. */ public class NewExpression extends FunctionCall { private ObjectLiteral initializer; { type = Token.NEW; } public NewExpression() { } public NewExpression(int pos) { super(pos); } public NewExpression(int pos, int len) { super(pos, len); } /** * Returns initializer object, if any. * @return extra initializer object-literal expression, or {@code null} if * not specified. */ public ObjectLiteral getInitializer() { return initializer; } /** * Sets initializer object. Rhino supports an experimental syntax * of the form {@code new expr [ ( arglist ) ] [initializer]}, * in which initializer is an object literal that is used to set * additional properties on the newly-created {@code expr} object. * * @param initializer extra initializer object. * Can be {@code null}. */ public void setInitializer(ObjectLiteral initializer) { this.initializer = initializer; if (initializer != null) initializer.setParent(this); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("new "); sb.append(target.toSource(0)); sb.append("("); if (arguments != null) { printList(arguments, sb); } sb.append(")"); if (initializer != null) { sb.append(" "); sb.append(initializer.toSource(0)); } return sb.toString(); } /** * Visits this node, the target, and each argument. If there is * a trailing initializer node, visits that last. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { target.visit(v); for (AstNode arg : getArguments()) { arg.visit(v); } if (initializer != null) { initializer.visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/PropertyGet.java0000644000175000017500000000762311314263504034031 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for the '.' operator. Node type is {@link Token#GETPROP}. */ public class PropertyGet extends InfixExpression { { type = Token.GETPROP; } public PropertyGet() { } public PropertyGet(int pos) { super(pos); } public PropertyGet(int pos, int len) { super(pos, len); } public PropertyGet(int pos, int len, AstNode target, Name property) { super(pos, len, target, property); } /** * Constructor. Updates bounds to include left ({@code target}) and * right ({@code property}) nodes. */ public PropertyGet(AstNode target, Name property) { super(target, property); } public PropertyGet(AstNode target, Name property, int dotPosition) { super(Token.GETPROP, target, property, dotPosition); } /** * Returns the object on which the property is being fetched. * Should never be {@code null}. */ public AstNode getTarget() { return getLeft(); } /** * Sets target object, and sets its parent to this node. * @param target expression evaluating to the object upon which * to do the property lookup * @throws IllegalArgumentException} if {@code target} is {@code null} */ public void setTarget(AstNode target) { setLeft(target); } /** * Returns the property being accessed. */ public Name getProperty() { return (Name)getRight(); } /** * Sets the property being accessed, and sets its parent to this node. * @throws IllegalArgumentException} if {@code property} is {@code null} */ public void setProperty(Name property) { setRight(property); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(getLeft().toSource(0)); sb.append("."); sb.append(getRight().toSource(0)); return sb.toString(); } /** * Visits this node, the target expression, and the property name. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { getTarget().visit(v); getProperty().visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/NodeVisitor.java0000644000175000017500000000464511314263504034013 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; /** * Simple visitor interface for traversing the AST. The nodes are visited in * an arbitrary order. The visitor must cast nodes to the appropriate * type based on their token-type. */ public interface NodeVisitor { /** * Visits an AST node. * @param node the AST node. Will never visit an {@link AstRoot} node, * since the {@code AstRoot} is where the visiting begins. * @return {@code true} if the children should be visited. * If {@code false}, the subtree rooted at this node is skipped. * The {@code node} argument should never be {@code null} -- * the individual {@link AstNode} classes should skip any children * that are not present in the source when they invoke this method. */ boolean visit(AstNode node); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/Assignment.java0000644000175000017500000000451411314263504033651 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; /** * AST node representing the set of assignment operators such as {@code =}, * {@code *=} and {@code +=}. */ public class Assignment extends InfixExpression { public Assignment() { } public Assignment(int pos) { super(pos); } public Assignment(int pos, int len) { super(pos, len); } public Assignment(int pos, int len, AstNode left, AstNode right) { super(pos, len, left, right); } public Assignment(AstNode left, AstNode right) { super(left, right); } public Assignment(int operator, AstNode left, AstNode right, int operatorPos) { super(operator, left, right, operatorPos); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/FunctionNode.java0000644000175000017500000003266011314263504034137 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Bob Jervis * Norris Boyd * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Node; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A JavaScript function declaration or expression.

* Node type is {@link Token#FUNCTION}.

* *

FunctionDeclaration :
 *        function Identifier ( FormalParameterListopt ) { FunctionBody }
 * FunctionExpression :
 *        function Identifieropt ( FormalParameterListopt ) { FunctionBody }
 * FormalParameterList :
 *        Identifier
 *        FormalParameterList , Identifier
 * FunctionBody :
 *        SourceElements
 * Program :
 *        SourceElements
 * SourceElements :
 *        SourceElement
 *        SourceElements SourceElement
 * SourceElement :
 *        Statement
 *        FunctionDeclaration
* * JavaScript 1.8 introduces "function closures" of the form *
function ([params] ) Expression
* * In this case the FunctionNode node will have no body but will have an * expression. */ public class FunctionNode extends ScriptNode { /** * There are three types of functions that can be defined. The first * is a function statement. This is a function appearing as a top-level * statement (i.e., not nested inside some other statement) in either a * script or a function.

* * The second is a function expression, which is a function appearing in * an expression except for the third type, which is...

* * The third type is a function expression where the expression is the * top-level expression in an expression statement.

* * The three types of functions have different treatment and must be * distinguished.

*/ public static final int FUNCTION_STATEMENT = 1; public static final int FUNCTION_EXPRESSION = 2; public static final int FUNCTION_EXPRESSION_STATEMENT = 3; public static enum Form { FUNCTION, GETTER, SETTER } private static final List NO_PARAMS = Collections.unmodifiableList(new ArrayList()); private Name functionName; private List params; private AstNode body; private boolean isExpressionClosure; private Form functionForm = Form.FUNCTION; private int lp = -1; private int rp = -1; // codegen variables private int functionType; private boolean needsActivation; private boolean ignoreDynamicScope; private boolean isGenerator; private List generatorResumePoints; private Map liveLocals; private AstNode memberExprNode; { type = Token.FUNCTION; } public FunctionNode() { } public FunctionNode(int pos) { super(pos); } public FunctionNode(int pos, Name name) { super(pos); setFunctionName(name); } /** * Returns function name * @return function name, {@code null} for anonymous functions */ public Name getFunctionName() { return functionName; } /** * Sets function name, and sets its parent to this node. * @param name function name, {@code null} for anonymous functions */ public void setFunctionName(Name name) { functionName = name; if (name != null) name.setParent(this); } /** * Returns the function name as a string * @return the function name, {@code ""} if anonymous */ public String getName() { return functionName != null ? functionName.getIdentifier() : ""; } /** * Returns the function parameter list * @return the function parameter list. Returns an immutable empty * list if there are no parameters. */ public List getParams() { return params != null ? params : NO_PARAMS; } /** * Sets the function parameter list, and sets the parent for * each element of the list. * @param params the function parameter list, or {@code null} if no params */ public void setParams(List params) { if (params == null) { this.params = null; } else { if (this.params != null) this.params.clear(); for (AstNode param : params) addParam(param); } } /** * Adds a parameter to the function parameter list. * Sets the parent of the param node to this node. * @param param the parameter * @throws IllegalArgumentException if param is {@code null} */ public void addParam(AstNode param) { assertNotNull(param); if (params == null) { params = new ArrayList(); } params.add(param); param.setParent(this); } /** * Returns true if the specified {@link AstNode} node is a parameter * of this Function node. This provides a way during AST traversal * to disambiguate the function name node from the parameter nodes. */ public boolean isParam(AstNode node) { return params == null ? false : params.contains(node); } /** * Returns function body. Normally a {@link Block}, but can be a plain * {@link AstNode} if it's a function closure. * * @return the body. Can be {@code null} only if the AST is malformed. */ public AstNode getBody() { return body; } /** * Sets function body, and sets its parent to this node. * Also sets the encoded source bounds based on the body bounds. * Assumes the function node absolute position has already been set, * and the body node's absolute position and length are set.

* * @param body function body. Its parent is set to this node, and its * position is updated to be relative to this node. * * @throws IllegalArgumentException if body is {@code null} */ public void setBody(AstNode body) { assertNotNull(body); this.body = body; if (Boolean.TRUE.equals(body.getProp(Node.EXPRESSION_CLOSURE_PROP))) { setIsExpressionClosure(true); } int absEnd = body.getPosition() + body.getLength(); body.setParent(this); this.setLength(absEnd - this.position); setEncodedSourceBounds(this.position, absEnd); } /** * Returns left paren position, -1 if missing */ public int getLp() { return lp; } /** * Sets left paren position */ public void setLp(int lp) { this.lp = lp; } /** * Returns right paren position, -1 if missing */ public int getRp() { return rp; } /** * Sets right paren position */ public void setRp(int rp) { this.rp = rp; } /** * Sets both paren positions */ public void setParens(int lp, int rp) { this.lp = lp; this.rp = rp; } /** * Returns whether this is a 1.8 function closure */ public boolean isExpressionClosure() { return isExpressionClosure; } /** * Sets whether this is a 1.8 function closure */ public void setIsExpressionClosure(boolean isExpressionClosure) { this.isExpressionClosure = isExpressionClosure; } /** * Return true if this function requires an Ecma-262 Activation object. * The Activation object is implemented by * {@link org.mozilla.javascript.NativeCall}, and is fairly expensive * to create, so when possible, the interpreter attempts to use a plain * call frame instead. * * @return true if this function needs activation. It could be needed * if there is a lexical closure, or dynamic scope, or in a number of * other situations. */ public boolean requiresActivation() { return needsActivation; } public void setRequiresActivation() { needsActivation = true; } public boolean getIgnoreDynamicScope() { return ignoreDynamicScope; } public void setIgnoreDynamicScope() { ignoreDynamicScope = true; } public boolean isGenerator() { return isGenerator; } public void setIsGenerator() { isGenerator = true; } public void addResumptionPoint(Node target) { if (generatorResumePoints == null) generatorResumePoints = new ArrayList(); generatorResumePoints.add(target); } public List getResumptionPoints() { return generatorResumePoints; } public Map getLiveLocals() { return liveLocals; } public void addLiveLocals(Node node, int[] locals) { if (liveLocals == null) liveLocals = new HashMap(); liveLocals.put(node, locals); } @Override public int addFunction(FunctionNode fnNode) { int result = super.addFunction(fnNode); if (getFunctionCount() > 0) { needsActivation = true; } return result; } /** * Returns the function type (statement, expr, statement expr) */ public int getFunctionType() { return functionType; } public void setFunctionType(int type) { functionType = type; } public boolean isGetterOrSetter() { return functionForm == Form.GETTER || functionForm == Form.SETTER; } public boolean isGetter() { return functionForm == Form.GETTER; } public boolean isSetter() { return functionForm == Form.SETTER; } public void setFunctionIsGetter() { functionForm = Form.GETTER; } public void setFunctionIsSetter() { functionForm = Form.SETTER; } /** * Rhino supports a nonstandard Ecma extension that allows you to * say, for instance, function a.b.c(arg1, arg) {...}, and it will * be rewritten at codegen time to: a.b.c = function(arg1, arg2) {...} * If we detect an expression other than a simple Name in the position * where a function name was expected, we record that expression here. *

* This extension is only available by setting the CompilerEnv option * "isAllowMemberExprAsFunctionName" in the Parser. */ public void setMemberExprNode(AstNode node) { memberExprNode = node; if (node != null) node.setParent(this); } public AstNode getMemberExprNode() { return memberExprNode; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("function"); if (functionName != null) { sb.append(" "); sb.append(functionName.toSource(0)); } if (params == null) { sb.append("() "); } else { sb.append("("); printList(params, sb); sb.append(") "); } if (isExpressionClosure) { sb.append(" "); sb.append(getBody().toSource(0)); } else { sb.append(getBody().toSource(depth).trim()); } if (functionType == FUNCTION_STATEMENT) { sb.append("\n"); } return sb.toString(); } /** * Visits this node, the function name node if supplied, * the parameters, and the body. If there is a member-expr node, * it is visited last. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { if (functionName != null) { functionName.visit(v); } for (AstNode param : getParams()) { param.visit(v); } getBody().visit(v); if (!isExpressionClosure) { if (memberExprNode != null) { memberExprNode.visit(v); } } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/XmlElemRef.java0000644000175000017500000001146211314263504033541 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for an E4X XML {@code [expr]} member-ref expression. * The node type is {@link Token#REF_MEMBER}.

* * Syntax:

* *

 @opt ns:: opt [ expr ]
* * Examples include {@code ns::[expr]}, {@code @ns::[expr]}, {@code @[expr]}, * {@code *::[expr]} and {@code @*::[expr]}.

* * Note that the form {@code [expr]} (i.e. no namespace or * attribute-qualifier) is not a legal {@code XmlElemRef} expression, * since it's already used for standard JavaScript {@link ElementGet} * array-indexing. Hence, an {@code XmlElemRef} node always has * either the attribute-qualifier, a non-{@code null} namespace node, * or both.

* * The node starts at the {@code @} token, if present. Otherwise it starts * at the namespace name. The node bounds extend through the closing * right-bracket, or if it is missing due to a syntax error, through the * end of the index expression.

*/ public class XmlElemRef extends XmlRef { private AstNode indexExpr; private int lb = -1; private int rb = -1; { type = Token.REF_MEMBER; } public XmlElemRef() { } public XmlElemRef(int pos) { super(pos); } public XmlElemRef(int pos, int len) { super(pos, len); } /** * Returns index expression: the 'expr' in {@code @[expr]} * or {@code @*::[expr]}. */ public AstNode getExpression() { return indexExpr; } /** * Sets index expression, and sets its parent to this node. * @throws IllegalArgumentException if {@code expr} is {@code null} */ public void setExpression(AstNode expr) { assertNotNull(expr); indexExpr = expr; expr.setParent(this); } /** * Returns left bracket position, or -1 if missing. */ public int getLb() { return lb; } /** * Sets left bracket position, or -1 if missing. */ public void setLb(int lb) { this.lb = lb; } /** * Returns left bracket position, or -1 if missing. */ public int getRb() { return rb; } /** * Sets right bracket position, -1 if missing. */ public void setRb(int rb) { this.rb = rb; } /** * Sets both bracket positions. */ public void setBrackets(int lb, int rb) { this.lb = lb; this.rb = rb; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); if (isAttributeAccess()) { sb.append("@"); } if (namespace != null) { sb.append(namespace.toSource(0)); sb.append("::"); } sb.append("["); sb.append(indexExpr.toSource(0)); sb.append("]"); return sb.toString(); } /** * Visits this node, then the namespace if provided, then the * index expression. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { if (namespace != null) { namespace.visit(v); } indexExpr.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/UnaryExpression.java0000644000175000017500000001357511314263504034726 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node representing unary operators such as {@code ++}, * {@code ~}, {@code typeof} and {@code delete}. The type field * is set to the appropriate Token type for the operator. The node length spans * from the operator to the end of the operand (for prefix operators) or from * the start of the operand to the operator (for postfix).

* * The {@code default xml namespace = <expr>} statement in E4X * (JavaScript 1.6) is represented as a {@code UnaryExpression} of node * type {@link Token#DEFAULTNAMESPACE}, wrapped with an * {@link ExpressionStatement}. */ public class UnaryExpression extends AstNode { private AstNode operand; private boolean isPostfix; public UnaryExpression() { } public UnaryExpression(int pos) { super(pos); } /** * Constructs a new postfix UnaryExpression */ public UnaryExpression(int pos, int len) { super(pos, len); } /** * Constructs a new prefix UnaryExpression. */ public UnaryExpression(int operator, int operatorPosition, AstNode operand) { this(operator, operatorPosition, operand, false); } /** * Constructs a new UnaryExpression with the specified operator * and operand. It sets the parent of the operand, and sets its own bounds * to encompass the operator and operand. * @param operator the node type * @param operatorPosition the absolute position of the operator. * @param operand the operand expression * @param postFix true if the operator follows the operand. Int * @throws IllegalArgumentException} if {@code operand} is {@code null} */ public UnaryExpression(int operator, int operatorPosition, AstNode operand, boolean postFix) { assertNotNull(operand); int beg = postFix ? operand.getPosition() : operatorPosition; // JavaScript only has ++ and -- postfix operators, so length is 2 int end = postFix ? operatorPosition + 2 : operand.getPosition() + operand.getLength(); setBounds(beg, end); setOperator(operator); setOperand(operand); isPostfix = postFix; } /** * Returns operator token – alias for {@link #getType} */ public int getOperator() { return type; } /** * Sets operator – same as {@link #setType}, but throws an * exception if the operator is invalid * @throws IllegalArgumentException if operator is not a valid * Token code */ public void setOperator(int operator) { if (!Token.isValidToken(operator)) throw new IllegalArgumentException("Invalid token: " + operator); setType(operator); } public AstNode getOperand() { return operand; } /** * Sets the operand, and sets its parent to be this node. * @throws IllegalArgumentException} if {@code operand} is {@code null} */ public void setOperand(AstNode operand) { assertNotNull(operand); this.operand = operand; operand.setParent(this); } /** * Returns whether the operator is postfix */ public boolean isPostfix() { return isPostfix; } /** * Returns whether the operator is prefix */ public boolean isPrefix() { return !isPostfix; } /** * Sets whether the operator is postfix */ public void setIsPostfix(boolean isPostfix) { this.isPostfix = isPostfix; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); if (!isPostfix) { sb.append(operatorToString(getType())); if (getType() == Token.TYPEOF || getType() == Token.DELPROP) { sb.append(" "); } } sb.append(operand.toSource()); if (isPostfix) { sb.append(operatorToString(getType())); } return sb.toString(); } /** * Visits this node, then the operand. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { operand.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/DoLoop.java0000644000175000017500000000660111314263504032734 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * Do statement. Node type is {@link Token#DO}.

* *

DoLoop:
 * do Statement while ( Expression ) ;
*/ public class DoLoop extends Loop { private AstNode condition; private int whilePosition = -1; { type = Token.DO; } public DoLoop() { } public DoLoop(int pos) { super(pos); } public DoLoop(int pos, int len) { super(pos, len); } /** * Returns loop condition */ public AstNode getCondition() { return condition; } /** * Sets loop condition, and sets its parent to this node. * @throws IllegalArgumentException if condition is null */ public void setCondition(AstNode condition) { assertNotNull(condition); this.condition = condition; condition.setParent(this); } /** * Returns source position of "while" keyword */ public int getWhilePosition() { return whilePosition; } /** * Sets source position of "while" keyword */ public void setWhilePosition(int whilePosition) { this.whilePosition = whilePosition; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append("do "); sb.append(body.toSource(depth).trim()); sb.append(" while ("); sb.append(condition.toSource(0)); sb.append(");\n"); return sb.toString(); } /** * Visits this node, the body, and then the while-expression. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { body.visit(v); condition.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/WhileLoop.java0000644000175000017500000000627111314263504033445 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * While statement. Node type is {@link Token#WHILE}.

* *

WhileStatement:
 *     while ( Expression ) Statement
*/ public class WhileLoop extends Loop { private AstNode condition; { type = Token.WHILE; } public WhileLoop() { } public WhileLoop(int pos) { super(pos); } public WhileLoop(int pos, int len) { super(pos, len); } /** * Returns loop condition */ public AstNode getCondition() { return condition; } /** * Sets loop condition * @throws IllegalArgumentException} if condition is {@code null} */ public void setCondition(AstNode condition) { assertNotNull(condition); this.condition = condition; condition.setParent(this); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("while ("); sb.append(condition.toSource(0)); sb.append(") "); if (body instanceof Block) { sb.append(body.toSource(depth).trim()); sb.append("\n"); } else { sb.append("\n").append(body.toSource(depth+1)); } return sb.toString(); } /** * Visits this node, the condition, then the body. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { condition.visit(v); body.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/BreakStatement.java0000644000175000017500000001003311314263504034443 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * A break statement. Node type is {@link Token#BREAK}.

* *

BreakStatement :
 *   break [no LineTerminator here] [Identifier] ;
*/ public class BreakStatement extends Jump { private Name breakLabel; private AstNode target; { type = Token.BREAK; } public BreakStatement() { } public BreakStatement(int pos) { // can't call super (Jump) for historical reasons position = pos; } public BreakStatement(int pos, int len) { position = pos; length = len; } /** * Returns the intended label of this break statement * @return the break label. {@code null} if the source code did * not specify a specific break label via "break <target>". */ public Name getBreakLabel() { return breakLabel; } /** * Sets the intended label of this break statement, e.g. 'foo' * in "break foo". Also sets the parent of the label to this node. * @param label the break label, or {@code null} if the statement is * just the "break" keyword by itself. */ public void setBreakLabel(Name label) { breakLabel = label; if (label != null) label.setParent(this); } /** * Returns the statement to break to * @return the break target. Only {@code null} if the source * code has an error in it. */ public AstNode getBreakTarget() { return target; } /** * Sets the statement to break to. * @param target the statement to break to * @throws IllegalArgumentException if target is {@code null} */ public void setBreakTarget(Jump target) { assertNotNull(target); this.target = target; setJumpStatement(target); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("break"); if (breakLabel != null) { sb.append(" "); sb.append(breakLabel.toSource(0)); } sb.append(";\n"); return sb.toString(); } /** * Visits this node, then visits the break label if non-{@code null}. */ @Override public void visit(NodeVisitor v) { if (v.visit(this) && breakLabel != null) { breakLabel.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ScriptNode.java0000644000175000017500000002453711314263504033622 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Bob Jervis * Norris Boyd * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Node; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Base type for {@link AstRoot} and {@link FunctionNode} nodes, which need to * collect much of the same information. */ public class ScriptNode extends Scope { private int encodedSourceStart = -1; private int encodedSourceEnd = -1; private String sourceName; private String encodedSource; private int endLineno = -1; private List functions; private List regexps; private List EMPTY_LIST = Collections.emptyList(); private List symbols = new ArrayList(4); private int paramCount = 0; private String[] variableNames; private boolean[] isConsts; private Object compilerData; private int tempNumber = 0; { // during parsing, a ScriptNode or FunctionNode's top scope is itself this.top = this; this.type = Token.SCRIPT; } public ScriptNode() { } public ScriptNode(int pos) { super(pos); } /** * Returns the URI, path or descriptive text indicating the origin * of this script's source code. */ public String getSourceName() { return sourceName; } /** * Sets the URI, path or descriptive text indicating the origin * of this script's source code. */ public void setSourceName(String sourceName) { this.sourceName = sourceName; } /** * Returns the start offset of the encoded source. * Only valid if {@link #getEncodedSource} returns non-{@code null}. */ public int getEncodedSourceStart() { return encodedSourceStart; } /** * Used by code generator. * @see #getEncodedSource */ public void setEncodedSourceStart(int start) { this.encodedSourceStart = start; } /** * Returns the end offset of the encoded source. * Only valid if {@link #getEncodedSource} returns non-{@code null}. */ public int getEncodedSourceEnd() { return encodedSourceEnd; } /** * Used by code generator. * @see #getEncodedSource */ public void setEncodedSourceEnd(int end) { this.encodedSourceEnd = end; } /** * Used by code generator. * @see #getEncodedSource */ public void setEncodedSourceBounds(int start, int end) { this.encodedSourceStart = start; this.encodedSourceEnd = end; } /** * Used by the code generator. * @see #getEncodedSource */ public void setEncodedSource(String encodedSource) { this.encodedSource = encodedSource; } /** * Returns a canonical version of the source for this script or function, * for use in implementing the {@code Object.toSource} method of * JavaScript objects. This source encoding is only recorded during code * generation. It must be passed back to * {@link org.mozilla.javascript.Decompiler#decompile} to construct the * human-readable source string.

* * Given a parsed AST, you can always convert it to source code using the * {@link AstNode#toSource} method, although it's not guaranteed to produce * exactly the same results as {@code Object.toSource} with respect to * formatting, parenthesization and other details. * * @return the encoded source, or {@code null} if it was not recorded. */ public String getEncodedSource() { return encodedSource; } public int getBaseLineno() { return lineno; } /** * Sets base (starting) line number for this script or function. * This is a one-time operation, and throws an exception if the * line number has already been set. */ public void setBaseLineno(int lineno) { if (lineno < 0 || this.lineno >= 0) codeBug(); this.lineno = lineno; } public int getEndLineno() { return endLineno; } public void setEndLineno(int lineno) { // One time action if (lineno < 0 || endLineno >= 0) codeBug(); endLineno = lineno; } public int getFunctionCount() { return functions == null ? 0 : functions.size(); } public FunctionNode getFunctionNode(int i) { return functions.get(i); } public List getFunctions() { return functions == null ? EMPTY_LIST : functions; } /** * Adds a {@link FunctionNode} to the functions table for codegen. * Does not set the parent of the node. * @return the index of the function within its parent */ public int addFunction(FunctionNode fnNode) { if (fnNode == null) codeBug(); if (functions == null) functions = new ArrayList(); functions.add(fnNode); return functions.size() - 1; } public int getRegexpCount() { return regexps == null ? 0 : regexps.size(); } public String getRegexpString(int index) { return regexps.get(index).getValue(); } public String getRegexpFlags(int index) { return regexps.get(index).getFlags(); } /** * Called by IRFactory to add a RegExp to the regexp table. */ public void addRegExp(RegExpLiteral re) { if (re == null) codeBug(); if (regexps == null) regexps = new ArrayList(); regexps.add(re); re.putIntProp(REGEXP_PROP, regexps.size() - 1); } public int getIndexForNameNode(Node nameNode) { if (variableNames == null) codeBug(); Scope node = nameNode.getScope(); Symbol symbol = node == null ? null : node.getSymbol(((Name)nameNode).getIdentifier()); return (symbol == null) ? -1 : symbol.getIndex(); } public String getParamOrVarName(int index) { if (variableNames == null) codeBug(); return variableNames[index]; } public int getParamCount() { return paramCount; } public int getParamAndVarCount() { if (variableNames == null) codeBug(); return symbols.size(); } public String[] getParamAndVarNames() { if (variableNames == null) codeBug(); return variableNames; } public boolean[] getParamAndVarConst() { if (variableNames == null) codeBug(); return isConsts; } void addSymbol(Symbol symbol) { if (variableNames != null) codeBug(); if (symbol.getDeclType() == Token.LP) { paramCount++; } symbols.add(symbol); } public List getSymbols() { return symbols; } public void setSymbols(List symbols) { this.symbols = symbols; } /** * Assign every symbol a unique integer index. Generate arrays of variable * names and constness that can be indexed by those indices. * * @param flattenAllTables if true, flatten all symbol tables, * included nested block scope symbol tables. If false, just flatten the * script's or function's symbol table. */ public void flattenSymbolTable(boolean flattenAllTables) { if (!flattenAllTables) { List newSymbols = new ArrayList(); if (this.symbolTable != null) { // Just replace "symbols" with the symbols in this object's // symbol table. Can't just work from symbolTable map since // we need to retain duplicate parameters. for (int i = 0; i < symbols.size(); i++) { Symbol symbol = symbols.get(i); if (symbol.getContainingTable() == this) { newSymbols.add(symbol); } } } symbols = newSymbols; } variableNames = new String[symbols.size()]; isConsts = new boolean[symbols.size()]; for (int i = 0; i < symbols.size(); i++) { Symbol symbol = symbols.get(i); variableNames[i] = symbol.getName(); isConsts[i] = symbol.getDeclType() == Token.CONST; symbol.setIndex(i); } } public Object getCompilerData() { return compilerData; } public void setCompilerData(Object data) { assertNotNull(data); // Can only call once if (compilerData != null) throw new IllegalStateException(); compilerData = data; } public String getNextTempName() { return "$" + tempNumber++; } @Override public void visit(NodeVisitor v) { if (v.visit(this)) { for (Node kid : this) { ((AstNode)kid).visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/Label.java0000644000175000017500000000620111314263504032553 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node representing a label. It is a distinct node type so it can * record its length and position for code-processing tools. * Node type is {@link Token#LABEL}.

*/ public class Label extends Jump { private String name; { type = Token.LABEL; } public Label() { } public Label(int pos) { this(pos, -1); } public Label(int pos, int len) { // can't call super (Jump) for historical reasons position = pos; length = len; } public Label(int pos, int len, String name) { this(pos, len); setName(name); } /** * Returns the label text */ public String getName() { return name; } /** * Sets the label text * @throws IllegalArgumentException if name is {@code null} or the * empty string. */ public void setName(String name) { name = name == null ? null : name.trim(); if (name == null || "".equals(name)) throw new IllegalArgumentException("invalid label name"); this.name = name; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(name); sb.append(":\n"); return sb.toString(); } /** * Visits this label. There are no children to visit. */ @Override public void visit(NodeVisitor v) { v.visit(this); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/TryStatement.java0000644000175000017500000001363211314263504034205 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Try/catch/finally statement. Node type is {@link Token#TRY}.

* *

TryStatement :
 *        try Block Catch
 *        try Block Finally
 *        try Block Catch Finally
 * Catch :
 *        catch ( Identifier ) Block
 * Finally :
 *        finally Block
*/ public class TryStatement extends AstNode { private static final List NO_CATCHES = Collections.unmodifiableList(new ArrayList()); private AstNode tryBlock; private List catchClauses; private AstNode finallyBlock; private int finallyPosition = -1; { type = Token.TRY; } public TryStatement() { } public TryStatement(int pos) { super(pos); } public TryStatement(int pos, int len) { super(pos, len); } public AstNode getTryBlock() { return tryBlock; } /** * Sets try block. Also sets its parent to this node. * @throws IllegalArgumentException} if {@code tryBlock} is {@code null} */ public void setTryBlock(AstNode tryBlock) { assertNotNull(tryBlock); this.tryBlock = tryBlock; tryBlock.setParent(this); } /** * Returns list of {@link CatchClause} nodes. If there are no catch * clauses, returns an immutable empty list. */ public List getCatchClauses() { return catchClauses != null ? catchClauses : NO_CATCHES; } /** * Sets list of {@link CatchClause} nodes. Also sets their parents * to this node. May be {@code null}. Replaces any existing catch * clauses for this node. */ public void setCatchClauses(List catchClauses) { if (catchClauses == null) { this.catchClauses = null; } else { if (this.catchClauses != null) this.catchClauses.clear(); for (CatchClause cc : catchClauses) { addCatchClause(cc); } } } /** * Add a catch-clause to the end of the list, and sets its parent to * this node. * @throws IllegalArgumentException} if {@code clause} is {@code null} */ public void addCatchClause(CatchClause clause) { assertNotNull(clause); if (catchClauses == null) { catchClauses = new ArrayList(); } catchClauses.add(clause); clause.setParent(this); } /** * Returns finally block, or {@code null} if not present */ public AstNode getFinallyBlock() { return finallyBlock; } /** * Sets finally block, and sets its parent to this node. * May be {@code null}. */ public void setFinallyBlock(AstNode finallyBlock) { this.finallyBlock = finallyBlock; if (finallyBlock != null) finallyBlock.setParent(this); } /** * Returns position of {@code finally} keyword, if present, or -1 */ public int getFinallyPosition() { return finallyPosition; } /** * Sets position of {@code finally} keyword, if present, or -1 */ public void setFinallyPosition(int finallyPosition) { this.finallyPosition = finallyPosition; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(250); sb.append(makeIndent(depth)); sb.append("try "); sb.append(tryBlock.toSource(depth).trim()); for (CatchClause cc : getCatchClauses()) { sb.append(cc.toSource(depth)); } if (finallyBlock != null) { sb.append(" finally "); sb.append(finallyBlock.toSource(depth)); } return sb.toString(); } /** * Visits this node, then the try-block, then any catch clauses, * and then any finally block. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { tryBlock.visit(v); for (CatchClause cc : getCatchClauses()) { cc.visit(v); } if (finallyBlock != null) { finallyBlock.visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ErrorCollector.java0000644000175000017500000001024711314263504034501 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.EvaluatorException; import java.util.ArrayList; import java.util.List; /** * An error reporter that gathers the errors and warnings for later display. * This a useful {@link org.mozilla.javascript.ErrorReporter} when the * {@link org.mozilla.javascript.CompilerEnvirons} is set to * ide-mode (for IDEs). * * @author Steve Yegge */ public class ErrorCollector implements IdeErrorReporter { private List errors = new ArrayList(); /** * This is not called during AST generation. * {@link #warning(String,String,int,int)} is used instead. * @throws UnsupportedOperationException */ public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) { throw new UnsupportedOperationException(); } /** * @inheritDoc */ public void warning(String message, String sourceName, int offset, int length) { errors.add(new ParseProblem(ParseProblem.Type.Warning, message, sourceName, offset, length)); } /** * This is not called during AST generation. * {@link #warning(String,String,int,int)} is used instead. * @throws UnsupportedOperationException */ public void error(String message, String sourceName, int line, String lineSource, int lineOffset) { throw new UnsupportedOperationException(); } /** * @inheritDoc */ public void error(String message, String sourceName, int fileOffset, int length) { errors.add(new ParseProblem(ParseProblem.Type.Error, message, sourceName, fileOffset, length)); } /** * @inheritDoc */ public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) { throw new UnsupportedOperationException(); } /** * Returns the list of errors and warnings produced during parsing. */ public List getErrors() { return errors; } @Override public String toString() { StringBuilder sb = new StringBuilder(errors.size() * 100); for (ParseProblem pp : errors) { sb.append(pp.toString()).append("\n"); } return sb.toString(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/IdeErrorReporter.java0000644000175000017500000000775111314263504035005 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript.ast; import org.mozilla.javascript.ErrorReporter; /** * This is interface defines a protocol for the reporting of * errors during JavaScript translation in IDE-mode. * If the {@link org.mozilla.javascript.Parser}'s error reporter is * set to an instance of this interface, then this interface's * {@link #warning} and {@link #error} methods are called instead * of the {@link org.mozilla.javascript.ErrorReporter} versions.

* * These methods take a source char offset and a length. The * rationale is that in interactive IDE-type environments, the source * is available and the IDE will want to indicate where the error * occurred and how much code participates in it. The start and length * are generally chosen to fit within a single line, for readability, * but the client is free to use the AST to determine the affected * node(s) from the start position and change the error or warning's * display bounds.

* * @author Steve Yegge */ public interface IdeErrorReporter extends ErrorReporter { /** * Report a warning.

* * The implementing class may choose to ignore the warning * if it desires. * * @param message a {@code String} describing the warning * @param sourceName a {@code String} describing the JavaScript source * where the warning occured; typically a filename or URL * @param offset the warning's 0-indexed char position in the input stream * @param length the length of the region contributing to the warning */ void warning(String message, String sourceName, int offset, int length); /** * Report an error.

* * The implementing class is free to throw an exception if * it desires.

* * If execution has not yet begun, the JavaScript engine is * free to find additional errors rather than terminating * the translation. It will not execute a script that had * errors, however.

* * @param message a String describing the error * @param sourceName a String describing the JavaScript source * where the error occured; typically a filename or URL * @param offset 0-indexed char position of the error in the input stream * @param length the length of the region contributing to the error */ void error(String message, String sourceName, int offset, int length); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/DestructuringForm.java0000644000175000017500000000445311314263504035231 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; /** * Common interface for {@link ArrayLiteral} and {@link ObjectLiteral} * node types, both of which may appear in "destructuring" expressions or * contexts. */ public interface DestructuringForm { /** * Marks this node as being a destructuring form - that is, appearing * in a context such as {@code for ([a, b] in ...)} where it's the * target of a destructuring assignment. */ void setIsDestructuring(boolean destructuring); /** * Returns true if this node is in a destructuring position: * a function parameter, the target of a variable initializer, the * iterator of a for..in loop, etc. */ boolean isDestructuring(); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/ForInLoop.java0000644000175000017500000001231611314263504033407 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * For-in or for-each-in statement. Node type is {@link Token#FOR}.

* *

for [each] ( LeftHandSideExpression in Expression ) Statement
*
for [each] ( var VariableDeclarationNoIn in Expression ) Statement
*/ public class ForInLoop extends Loop { protected AstNode iterator; protected AstNode iteratedObject; protected int inPosition = -1; protected int eachPosition = -1; protected boolean isForEach; { type = Token.FOR; } public ForInLoop() { } public ForInLoop(int pos) { super(pos); } public ForInLoop(int pos, int len) { super(pos, len); } /** * Returns loop iterator expression */ public AstNode getIterator() { return iterator; } /** * Sets loop iterator expression: the part before the "in" keyword. * Also sets its parent to this node. * @throws IllegalArgumentException if {@code iterator} is {@code null} */ public void setIterator(AstNode iterator) { assertNotNull(iterator); this.iterator = iterator; iterator.setParent(this); } /** * Returns object being iterated over */ public AstNode getIteratedObject() { return iteratedObject; } /** * Sets object being iterated over, and sets its parent to this node. * @throws IllegalArgumentException if {@code object} is {@code null} */ public void setIteratedObject(AstNode object) { assertNotNull(object); this.iteratedObject = object; object.setParent(this); } /** * Returns whether the loop is a for-each loop */ public boolean isForEach() { return isForEach; } /** * Sets whether the loop is a for-each loop */ public void setIsForEach(boolean isForEach) { this.isForEach = isForEach; } /** * Returns position of "in" keyword */ public int getInPosition() { return inPosition; } /** * Sets position of "in" keyword * @param inPosition position of "in" keyword, * or -1 if not present (e.g. in presence of a syntax error) */ public void setInPosition(int inPosition) { this.inPosition = inPosition; } /** * Returns position of "each" keyword */ public int getEachPosition() { return eachPosition; } /** * Sets position of "each" keyword * @param eachPosition position of "each" keyword, * or -1 if not present. */ public void setEachPosition(int eachPosition) { this.eachPosition = eachPosition; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("for "); if (isForEach()) { sb.append("each "); } sb.append("("); sb.append(iterator.toSource(0)); sb.append(" in "); sb.append(iteratedObject.toSource(0)); sb.append(") "); if (body instanceof Block) { sb.append(body.toSource(depth).trim()).append("\n"); } else { sb.append("\n").append(body.toSource(depth+1)); } return sb.toString(); } /** * Visits this node, the iterator, the iterated object, and the body. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { iterator.visit(v); iteratedObject.visit(v); body.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/WithStatement.java0000644000175000017500000001032311314263504034334 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * With statement. Node type is {@link Token#WITH}.

* *

WithStatement :
 *      with ( Expression ) Statement ;
*/ public class WithStatement extends AstNode { private AstNode expression; private AstNode statement; private int lp = -1; private int rp = -1; { type = Token.WITH; } public WithStatement() { } public WithStatement(int pos) { super(pos); } public WithStatement(int pos, int len) { super(pos, len); } /** * Returns object expression */ public AstNode getExpression() { return expression; } /** * Sets object expression (and its parent link) * @throws IllegalArgumentException} if expression is {@code null} */ public void setExpression(AstNode expression) { assertNotNull(expression); this.expression = expression; expression.setParent(this); } /** * Returns the statement or block */ public AstNode getStatement() { return statement; } /** * Sets the statement (and sets its parent link) * @throws IllegalArgumentException} if statement is {@code null} */ public void setStatement(AstNode statement) { assertNotNull(statement); this.statement = statement; statement.setParent(this); } /** * Returns left paren offset */ public int getLp() { return lp; } /** * Sets left paren offset */ public void setLp(int lp) { this.lp = lp; } /** * Returns right paren offset */ public int getRp() { return rp; } /** * Sets right paren offset */ public void setRp(int rp) { this.rp = rp; } /** * Sets both paren positions */ public void setParens(int lp, int rp) { this.lp = lp; this.rp = rp; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("with ("); sb.append(expression.toSource(0)); sb.append(") "); sb.append(statement.toSource(depth+1)); if (!(statement instanceof Block)) { sb.append(";\n"); } return sb.toString(); } /** * Visits this node, then the with-object, then the body statement. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { expression.visit(v); statement.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/SwitchStatement.java0000644000175000017500000001330611314263504034666 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Switch statement AST node type. * Node type is {@link Token#SWITCH}.

* *

SwitchStatement :
 *        switch ( Expression ) CaseBlock
 * CaseBlock :
 *        { [CaseClauses] }
 *        { [CaseClauses] DefaultClause [CaseClauses] }
 * CaseClauses :
 *        CaseClause
 *        CaseClauses CaseClause
 * CaseClause :
 *        case Expression : [StatementList]
 * DefaultClause :
 *        default : [StatementList]
*/ public class SwitchStatement extends Jump { private static final List NO_CASES = Collections.unmodifiableList(new ArrayList()); private AstNode expression; private List cases; private int lp = -1; private int rp = -1; { type = Token.SWITCH; } public SwitchStatement() { } public SwitchStatement(int pos) { // can't call super (Jump) for historical reasons position = pos; } public SwitchStatement(int pos, int len) { position = pos; length = len; } /** * Returns the switch discriminant expression */ public AstNode getExpression() { return expression; } /** * Sets the switch discriminant expression, and sets its parent * to this node. * @throws IllegalArgumentException} if expression is {@code null} */ public void setExpression(AstNode expression) { assertNotNull(expression); this.expression = expression; expression.setParent(this); } /** * Returns case statement list. If there are no cases, * returns an immutable empty list. */ public List getCases() { return cases != null ? cases : NO_CASES; } /** * Sets case statement list, and sets the parent of each child * case to this node. * @param cases list, which may be {@code null} to remove all the cases */ public void setCases(List cases) { if (cases == null) { this.cases = null; } else { if (this.cases != null) this.cases.clear(); for (SwitchCase sc : cases) addCase(sc); } } /** * Adds a switch case statement to the end of the list. * @throws IllegalArgumentException} if switchCase is {@code null} */ public void addCase(SwitchCase switchCase) { assertNotNull(switchCase); if (cases == null) { cases = new ArrayList(); } cases.add(switchCase); switchCase.setParent(this); } /** * Returns left paren position, -1 if missing */ public int getLp() { return lp; } /** * Sets left paren position */ public void setLp(int lp) { this.lp = lp; } /** * Returns right paren position, -1 if missing */ public int getRp() { return rp; } /** * Sets right paren position */ public void setRp(int rp) { this.rp = rp; } /** * Sets both paren positions */ public void setParens(int lp, int rp) { this.lp = lp; this.rp = rp; } @Override public String toSource(int depth) { String pad = makeIndent(depth); StringBuilder sb = new StringBuilder(); sb.append(pad); sb.append("switch ("); sb.append(expression.toSource(0)); sb.append(") {\n"); for (SwitchCase sc : cases) { sb.append(sc.toSource(depth + 1)); } sb.append(pad); sb.append("}\n"); return sb.toString(); } /** * Visits this node, then the switch-expression, then the cases * in lexical order. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { expression.visit(v); for (SwitchCase sc: getCases()) { sc.visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/XmlRef.java0000644000175000017500000001050211314263504032730 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; /** * Base class for E4X XML attribute-access or property-get expressions. * Such expressions can take a variety of forms. The general syntax has * three parts:

* *

    *
  1. optional: an {@code @}
  2. (specifying an attribute access) *
  3. optional: a namespace (a {@code Name}) and double-colon
  4. *
  5. required: either a {@code Name} or a bracketed [expression]
  6. *
* * The property-name expressions (examples: {@code ns::name}, {@code @name}) * are represented as {@link XmlPropRef} nodes. The bracketed-expression * versions (examples: {@code ns::[name]}, {@code @[name]}) become * {@link XmlElemRef} nodes.

* * This node type (or more specifically, its subclasses) will * sometimes be the right-hand child of a {@link PropertyGet} node or * an {@link XmlMemberGet} node. The {@code XmlRef} node may also * be a standalone primary expression with no explicit target, which * is valid in certain expression contexts such as * {@code company..employee.(@id < 100)} - in this case, the {@code @id} * is an {@code XmlRef} that is part of an infix '<' expression * whose parent is an {@code XmlDotQuery} node.

*/ public abstract class XmlRef extends AstNode { protected Name namespace; protected int atPos = -1; protected int colonPos = -1; public XmlRef() { } public XmlRef(int pos) { super(pos); } public XmlRef(int pos, int len) { super(pos, len); } /** * Return the namespace. May be {@code @null}. */ public Name getNamespace() { return namespace; } /** * Sets namespace, and sets its parent to this node. * Can be {@code null}. */ public void setNamespace(Name namespace) { this.namespace = namespace; if (namespace != null) namespace.setParent(this); } /** * Returns {@code true} if this expression began with an {@code @}-token. */ public boolean isAttributeAccess() { return atPos >= 0; } /** * Returns position of {@code @}-token, or -1 if this is not * an attribute-access expression. */ public int getAtPos() { return atPos; } /** * Sets position of {@code @}-token, or -1 */ public void setAtPos(int atPos) { this.atPos = atPos; } /** * Returns position of {@code ::} token, or -1 if not present. * It will only be present if the namespace node is non-{@code null}. */ public int getColonPos() { return colonPos; } /** * Sets position of {@code ::} token, or -1 if not present */ public void setColonPos(int colonPos) { this.colonPos = colonPos; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/Symbol.java0000644000175000017500000001070411314263504033004 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Roger Lawrence * Mike McCabe * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Node; import org.mozilla.javascript.Token; /** * Represents a symbol-table entry. */ public class Symbol { // One of Token.FUNCTION, Token.LP (for parameters), Token.VAR, // Token.LET, or Token.CONST private int declType; private int index = -1; private String name; private Node node; private Scope containingTable; public Symbol() { } /** * Constructs a new Symbol with a specific name and declaration type * @param declType {@link Token#FUNCTION}, {@link Token#LP} * (for params), {@link Token#VAR}, {@link Token#LET} or {@link Token#CONST} */ public Symbol(int declType, String name) { setName(name); setDeclType(declType); } /** * Returns symbol declaration type */ public int getDeclType() { return declType; } /** * Sets symbol declaration type */ public void setDeclType(int declType) { if (!(declType == Token.FUNCTION || declType == Token.LP || declType == Token.VAR || declType == Token.LET || declType == Token.CONST)) throw new IllegalArgumentException("Invalid declType: " + declType); this.declType = declType; } /** * Returns symbol name */ public String getName() { return name; } /** * Sets symbol name */ public void setName(String name) { this.name = name; } /** * Returns the node associated with this identifier */ public Node getNode() { return node; } /** * Returns symbol's index in its scope */ public int getIndex() { return index; } /** * Sets symbol's index in its scope */ public void setIndex(int index) { this.index = index; } /** * Sets the node associated with this identifier */ public void setNode(Node node) { this.node = node; } /** * Returns the Scope in which this symbol is entered */ public Scope getContainingTable() { return containingTable; } /** * Sets this symbol's Scope */ public void setContainingTable(Scope containingTable) { this.containingTable = containingTable; } public String getDeclTypeName() { return Token.typeToName(declType); } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("Symbol ("); result.append(getDeclTypeName()); result.append(") name="); result.append(name); if (node != null) { result.append(" line="); result.append(node.getLineno()); } return result.toString(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/FunctionCall.java0000644000175000017500000001242011314263504034115 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * AST node for a function call. Node type is {@link Token#CALL}.

*/ public class FunctionCall extends AstNode { protected static final List NO_ARGS = Collections.unmodifiableList(new ArrayList()); protected AstNode target; protected List arguments; protected int lp = -1; protected int rp = -1; { type = Token.CALL; } public FunctionCall() { } public FunctionCall(int pos) { super(pos); } public FunctionCall(int pos, int len) { super(pos, len); } /** * Returns node evaluating to the function to call */ public AstNode getTarget() { return target; } /** * Sets node evaluating to the function to call, and sets * its parent to this node. * @param target node evaluating to the function to call. * @throws IllegalArgumentException} if target is {@code null} */ public void setTarget(AstNode target) { assertNotNull(target); this.target = target; target.setParent(this); } /** * Returns function argument list * @return function argument list, or an empty immutable list if * there are no arguments. */ public List getArguments() { return arguments != null ? arguments : NO_ARGS; } /** * Sets function argument list * @param arguments function argument list. Can be {@code null}, * in which case any existing args are removed. */ public void setArguments(List arguments) { if (arguments == null) { this.arguments = null; } else { if (this.arguments != null) this.arguments.clear(); for (AstNode arg : arguments) { addArgument(arg); } } } /** * Adds an argument to the list, and sets its parent to this node. * @param arg the argument node to add to the list * @throws IllegalArgumentException} if arg is {@code null} */ public void addArgument(AstNode arg) { assertNotNull(arg); if (arguments == null) { arguments = new ArrayList(); } arguments.add(arg); arg.setParent(this); } /** * Returns left paren position, -1 if missing */ public int getLp() { return lp; } /** * Sets left paren position * @param lp left paren position */ public void setLp(int lp) { this.lp = lp; } /** * Returns right paren position, -1 if missing */ public int getRp() { return rp; } /** * Sets right paren position */ public void setRp(int rp) { this.rp = rp; } /** * Sets both paren positions */ public void setParens(int lp, int rp) { this.lp = lp; this.rp = rp; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(target.toSource(0)); sb.append("("); if (arguments != null) { printList(arguments, sb); } sb.append(")"); return sb.toString(); } /** * Visits this node, the target object, and the arguments. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { target.visit(v); for (AstNode arg : getArguments()) { arg.visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/XmlLiteral.java0000644000175000017500000000762411314263504033623 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; import java.util.ArrayList; import java.util.List; /** * AST node for an E4X (Ecma-357) embedded XML literal. Node type is * {@link Token#XML}. The parser generates a simple list of strings and * expressions. In the future we may parse the XML and produce a richer set of * nodes, but for now it's just a set of expressions evaluated to produce a * string to pass to the {@code XML} constructor function.

*/ public class XmlLiteral extends AstNode { private List fragments = new ArrayList(); { type = Token.XML; } public XmlLiteral() { } public XmlLiteral(int pos) { super(pos); } public XmlLiteral(int pos, int len) { super(pos, len); } /** * Returns fragment list - a list of expression nodes. */ public List getFragments() { return fragments; } /** * Sets fragment list, removing any existing fragments first. * Sets the parent pointer for each fragment in the list to this node. * @param fragments fragment list. Replaces any existing fragments. * @throws IllegalArgumentException} if {@code fragments} is {@code null} */ public void setFragments(List fragments) { assertNotNull(fragments); this.fragments.clear(); for (XmlFragment fragment : fragments) addFragment(fragment); } /** * Adds a fragment to the fragment list. Sets its parent to this node. * @throws IllegalArgumentException} if {@code fragment} is {@code null} */ public void addFragment(XmlFragment fragment) { assertNotNull(fragment); fragments.add(fragment); fragment.setParent(this); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(250); for (XmlFragment frag : fragments) { sb.append(frag.toSource(0)); } return sb.toString(); } /** * Visits this node, then visits each child fragment in lexical order. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { for (XmlFragment frag : fragments) { frag.visit(v); } } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/EmptyExpression.java0000644000175000017500000000453411314263504034721 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for an empty expression. Node type is {@link Token#EMPTY}.

* * To create an empty statement, wrap it with an {@link ExpressionStatement}. */ public class EmptyExpression extends AstNode { { type = Token.EMPTY; } public EmptyExpression() { } public EmptyExpression(int pos) { super(pos); } public EmptyExpression(int pos, int len) { super(pos, len); } @Override public String toSource(int depth) { return makeIndent(depth); } /** * Visits this node. There are no children. */ @Override public void visit(NodeVisitor v) { v.visit(this); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/XmlMemberGet.java0000644000175000017500000000751611314263504034076 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for E4X ".@" and ".." expressions, such as * {@code foo..bar}, {@code foo..@bar}, {@code @foo.@bar}, and * {@code foo..@ns::*}. The right-hand node is always an * {@link XmlRef}.

* * Node type is {@link Token#DOT} or {@link Token#DOTDOT}. */ public class XmlMemberGet extends InfixExpression { { type = Token.DOTDOT; } public XmlMemberGet() { } public XmlMemberGet(int pos) { super(pos); } public XmlMemberGet(int pos, int len) { super(pos, len); } public XmlMemberGet(int pos, int len, AstNode target, XmlRef ref) { super(pos, len, target, ref); } /** * Constructs a new {@code XmlMemberGet} node. * Updates bounds to include {@code target} and {@code ref} nodes. */ public XmlMemberGet(AstNode target, XmlRef ref) { super(target, ref); } public XmlMemberGet(AstNode target, XmlRef ref, int opPos) { super(Token.DOTDOT, target, ref, opPos); } /** * Returns the object on which the XML member-ref expression * is being evaluated. Should never be {@code null}. */ public AstNode getTarget() { return getLeft(); } /** * Sets target object, and sets its parent to this node. * @throws IllegalArgumentException if {@code target} is {@code null} */ public void setTarget(AstNode target) { setLeft(target); } /** * Returns the right-side XML member ref expression. * Should never be {@code null} unless the code is malformed. */ public XmlRef getMemberRef() { return (XmlRef)getRight(); } /** * Sets the XML member-ref expression, and sets its parent * to this node. * @throws IllegalArgumentException if property is {@code null} */ public void setProperty(XmlRef ref) { setRight(ref); } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(getLeft().toSource(0)); sb.append(operatorToString(getType())); sb.append(getRight().toSource(0)); return sb.toString(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/NumberLiteral.java0000644000175000017500000000700411314263504034303 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node for a Number literal. Node type is {@link Token#NUMBER}.

*/ public class NumberLiteral extends AstNode { private String value; private double number; { type = Token.NUMBER; } public NumberLiteral() { } public NumberLiteral(int pos) { super(pos); } public NumberLiteral(int pos, int len) { super(pos, len); } /** * Constructor. Sets the length to the length of the {@code value} string. */ public NumberLiteral(int pos, String value) { super(pos); setValue(value); setLength(value.length()); } /** * Constructor. Sets the length to the length of the {@code value} string. */ public NumberLiteral(int pos, String value, double number) { this(pos, value); setDouble(number); } public NumberLiteral(double number) { setDouble(number); setValue(Double.toString(number)); } /** * Returns the node's string value (the original source token) */ public String getValue() { return value; } /** * Sets the node's value * @throws IllegalArgumentException} if value is {@code null} */ public void setValue(String value) { assertNotNull(value); this.value = value; } /** * Gets the {@code double} value. */ public double getNumber() { return number; } /** * Sets the node's {@code double} value. */ public void setNumber(double value) { number = value; } @Override public String toSource(int depth) { return makeIndent(depth) + (value == null ? "" : value); } /** * Visits this node. There are no children to visit. */ @Override public void visit(NodeVisitor v) { v.visit(this); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/InfixExpression.java0000644000175000017500000001462511314263504034702 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * AST node representing an infix (binary operator) expression. * The operator is the node's {@link Token} type. */ public class InfixExpression extends AstNode { protected AstNode left; protected AstNode right; protected int operatorPosition = -1; public InfixExpression() { } public InfixExpression(int pos) { super(pos); } public InfixExpression(int pos, int len) { super(pos, len); } public InfixExpression(int pos, int len, AstNode left, AstNode right) { super(pos, len); setLeft(left); setRight(right); } /** * Constructs a new {@code InfixExpression}. Updates bounds to include * left and right nodes. */ public InfixExpression(AstNode left, AstNode right) { setLeftAndRight(left, right); } /** * Constructs a new {@code InfixExpression}. * @param operatorPos the absolute position of the operator */ public InfixExpression(int operator, AstNode left, AstNode right, int operatorPos) { setType(operator); setOperatorPosition(operatorPos - left.getPosition()); setLeftAndRight(left, right); } public void setLeftAndRight(AstNode left, AstNode right) { assertNotNull(left); assertNotNull(right); // compute our bounds while children have absolute positions int beg = left.getPosition(); int end = right.getPosition() + right.getLength(); setBounds(beg, end); // this updates their positions to be parent-relative setLeft(left); setRight(right); } /** * Returns operator token – alias for {@link #getType} */ public int getOperator() { return getType(); } /** * Sets operator token – like {@link #setType}, but throws * an exception if the operator is invalid. * @throws IllegalArgumentException if operator is not a valid token * code */ public void setOperator(int operator) { if (!Token.isValidToken(operator)) throw new IllegalArgumentException("Invalid token: " + operator); setType(operator); } /** * Returns the left-hand side of the expression */ public AstNode getLeft() { return left; } /** * Sets the left-hand side of the expression, and sets its * parent to this node. * @param left the left-hand side of the expression * @throws IllegalArgumentException} if left is {@code null} */ public void setLeft(AstNode left) { assertNotNull(left); this.left = left; left.setParent(this); } /** * Returns the right-hand side of the expression * @return the right-hand side. It's usually an * {@link AstNode} node, but can also be a {@link FunctionNode} * representing Function expressions. */ public AstNode getRight() { return right; } /** * Sets the right-hand side of the expression, and sets its parent to this * node. * @throws IllegalArgumentException} if right is {@code null} */ public void setRight(AstNode right) { assertNotNull(right); this.right = right; right.setParent(this); } /** * Returns relative offset of operator token */ public int getOperatorPosition() { return operatorPosition; } /** * Sets operator token's relative offset * @param operatorPosition offset in parent of operator token */ public void setOperatorPosition(int operatorPosition) { this.operatorPosition = operatorPosition; } @Override public boolean hasSideEffects() { // the null-checks are for malformed expressions in IDE-mode switch (getType()) { case Token.COMMA: return right != null && right.hasSideEffects(); case Token.AND: case Token.OR: return left != null && left.hasSideEffects() || (right != null && right.hasSideEffects()); default: return super.hasSideEffects(); } } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(left.toSource()); sb.append(" "); sb.append(operatorToString(getType())); sb.append(" "); sb.append(right.toSource()); return sb.toString(); } /** * Visits this node, the left operand, and the right operand. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { left.visit(v); right.visit(v); } } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/ast/XmlFragment.java0000644000175000017500000000407311314263504033765 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.ast; import org.mozilla.javascript.Token; /** * Abstract base type for components that comprise an {@link XmlLiteral} * object. Node type is {@link Token#XML}.

*/ public abstract class XmlFragment extends AstNode { { type = Token.XML; } public XmlFragment() { } public XmlFragment(int pos) { super(pos); } public XmlFragment(int pos, int len) { super(pos, len); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/NativeBoolean.java0000644000175000017500000001314311314263504033476 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Mike McCabe * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; /** * This class implements the Boolean native object. * See ECMA 15.6. * @author Norris Boyd */ final class NativeBoolean extends IdScriptableObject { static final long serialVersionUID = -3716996899943880933L; private static final Object BOOLEAN_TAG = "Boolean"; static void init(Scriptable scope, boolean sealed) { NativeBoolean obj = new NativeBoolean(false); obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed); } private NativeBoolean(boolean b) { booleanValue = b; } @Override public String getClassName() { return "Boolean"; } @Override public Object getDefaultValue(Class typeHint) { // This is actually non-ECMA, but will be proposed // as a change in round 2. if (typeHint == ScriptRuntime.BooleanClass) return ScriptRuntime.wrapBoolean(booleanValue); return super.getDefaultValue(typeHint); } @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=1; s="constructor"; break; case Id_toString: arity=0; s="toString"; break; case Id_toSource: arity=0; s="toSource"; break; case Id_valueOf: arity=0; s="valueOf"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(BOOLEAN_TAG, id, s, arity); } @Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(BOOLEAN_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); if (id == Id_constructor) { boolean b; if (args.length == 0) { b = false; } else { b = args[0] instanceof ScriptableObject && ((ScriptableObject) args[0]).avoidObjectDetection() ? true : ScriptRuntime.toBoolean(args[0]); } if (thisObj == null) { // new Boolean(val) creates a new boolean object. return new NativeBoolean(b); } // Boolean(val) converts val to a boolean. return ScriptRuntime.wrapBoolean(b); } // The rest of Boolean.prototype methods require thisObj to be Boolean if (!(thisObj instanceof NativeBoolean)) throw incompatibleCallError(f); boolean value = ((NativeBoolean)thisObj).booleanValue; switch (id) { case Id_toString: return value ? "true" : "false"; case Id_toSource: return value ? "(new Boolean(true))" : "(new Boolean(false))"; case Id_valueOf: return ScriptRuntime.wrapBoolean(value); } throw new IllegalArgumentException(String.valueOf(id)); } // #string_id_map# @Override protected int findPrototypeId(String s) { int id; // #generated# Last update: 2007-05-09 08:15:31 EDT L0: { id = 0; String X = null; int c; int s_length = s.length(); if (s_length==7) { X="valueOf";id=Id_valueOf; } else if (s_length==8) { c=s.charAt(3); if (c=='o') { X="toSource";id=Id_toSource; } else if (c=='t') { X="toString";id=Id_toString; } } else if (s_length==11) { X="constructor";id=Id_constructor; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# return id; } private static final int Id_constructor = 1, Id_toString = 2, Id_toSource = 3, Id_valueOf = 4, MAX_PROTOTYPE_ID = 4; // #/string_id_map# private boolean booleanValue; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/JavaAdapter.java0000644000175000017500000012662411314263504033143 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Patrick Beard * Norris Boyd * Igor Bukanov * Mike McCabe * Matthias Radestock * Andi Vajda * Andrew Wason * Kemal Bayram * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import org.mozilla.classfile.*; import java.lang.reflect.*; import java.io.*; import java.security.*; import java.util.*; public final class JavaAdapter implements IdFunctionCall { /** * Provides a key with which to distinguish previously generated * adapter classes stored in a hash table. */ static class JavaAdapterSignature { Class superClass; Class[] interfaces; ObjToIntMap names; JavaAdapterSignature(Class superClass, Class[] interfaces, ObjToIntMap names) { this.superClass = superClass; this.interfaces = interfaces; this.names = names; } @Override public boolean equals(Object obj) { if (!(obj instanceof JavaAdapterSignature)) return false; JavaAdapterSignature sig = (JavaAdapterSignature) obj; if (superClass != sig.superClass) return false; if (interfaces != sig.interfaces) { if (interfaces.length != sig.interfaces.length) return false; for (int i=0; i < interfaces.length; i++) if (interfaces[i] != sig.interfaces[i]) return false; } if (names.size() != sig.names.size()) return false; ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(names); for (iter.start(); !iter.done(); iter.next()) { String name = (String)iter.getKey(); int arity = iter.getValue(); if (arity != names.get(name, arity + 1)) return false; } return true; } @Override public int hashCode() { return superClass.hashCode() | (0x9e3779b9 * (names.size() | (interfaces.length << 16))); } } public static void init(Context cx, Scriptable scope, boolean sealed) { JavaAdapter obj = new JavaAdapter(); IdFunctionObject ctor = new IdFunctionObject(obj, FTAG, Id_JavaAdapter, "JavaAdapter", 1, scope); ctor.markAsConstructor(null); if (sealed) { ctor.sealObject(); } ctor.exportAsScopeProperty(); } public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (f.hasTag(FTAG)) { if (f.methodId() == Id_JavaAdapter) { return js_createAdapter(cx, scope, args); } } throw f.unknown(); } public static Object convertResult(Object result, Class c) { if (result == Undefined.instance && (c != ScriptRuntime.ObjectClass && c != ScriptRuntime.StringClass)) { // Avoid an error for an undefined value; return null instead. return null; } return Context.jsToJava(result, c); } public static Scriptable createAdapterWrapper(Scriptable obj, Object adapter) { Scriptable scope = ScriptableObject.getTopLevelScope(obj); NativeJavaObject res = new NativeJavaObject(scope, adapter, null, true); res.setPrototype(obj); return res; } public static Object getAdapterSelf(Class adapterClass, Object adapter) throws NoSuchFieldException, IllegalAccessException { Field self = adapterClass.getDeclaredField("self"); return self.get(adapter); } static Object js_createAdapter(Context cx, Scriptable scope, Object[] args) { int N = args.length; if (N == 0) { throw ScriptRuntime.typeError0("msg.adapter.zero.args"); } Class superClass = null; Class[] intfs = new Class[N - 1]; int interfaceCount = 0; for (int i = 0; i != N - 1; ++i) { Object arg = args[i]; if (!(arg instanceof NativeJavaClass)) { throw ScriptRuntime.typeError2("msg.not.java.class.arg", String.valueOf(i), ScriptRuntime.toString(arg)); } Class c = ((NativeJavaClass) arg).getClassObject(); if (!c.isInterface()) { if (superClass != null) { throw ScriptRuntime.typeError2("msg.only.one.super", superClass.getName(), c.getName()); } superClass = c; } else { intfs[interfaceCount++] = c; } } if (superClass == null) superClass = ScriptRuntime.ObjectClass; Class[] interfaces = new Class[interfaceCount]; System.arraycopy(intfs, 0, interfaces, 0, interfaceCount); Scriptable obj = ScriptRuntime.toObject(cx, scope, args[N - 1]); Class adapterClass = getAdapterClass(scope, superClass, interfaces, obj); Class[] ctorParms = { ScriptRuntime.ContextFactoryClass, ScriptRuntime.ScriptableClass }; Object[] ctorArgs = { cx.getFactory(), obj }; try { Object adapter = adapterClass.getConstructor(ctorParms). newInstance(ctorArgs); Object self = getAdapterSelf(adapterClass, adapter); // Return unwrapped JavaAdapter if it implements Scriptable if (self instanceof Wrapper) { Object unwrapped = ((Wrapper) self).unwrap(); if (unwrapped instanceof Scriptable) { return unwrapped; } } return self; } catch (Exception ex) { throw Context.throwAsScriptRuntimeEx(ex); } } // Needed by NativeJavaObject serializer public static void writeAdapterObject(Object javaObject, ObjectOutputStream out) throws IOException { Class cl = javaObject.getClass(); out.writeObject(cl.getSuperclass().getName()); Class[] interfaces = cl.getInterfaces(); String[] interfaceNames = new String[interfaces.length]; for (int i=0; i < interfaces.length; i++) interfaceNames[i] = interfaces[i].getName(); out.writeObject(interfaceNames); try { Object delegee = cl.getField("delegee").get(javaObject); out.writeObject(delegee); return; } catch (IllegalAccessException e) { } catch (NoSuchFieldException e) { } throw new IOException(); } // Needed by NativeJavaObject de-serializer public static Object readAdapterObject(Scriptable self, ObjectInputStream in) throws IOException, ClassNotFoundException { ContextFactory factory; Context cx = Context.getCurrentContext(); if (cx != null) { factory = cx.getFactory(); } else { factory = null; } Class superClass = Class.forName((String)in.readObject()); String[] interfaceNames = (String[])in.readObject(); Class[] interfaces = new Class[interfaceNames.length]; for (int i=0; i < interfaceNames.length; i++) interfaces[i] = Class.forName(interfaceNames[i]); Scriptable delegee = (Scriptable)in.readObject(); Class adapterClass = getAdapterClass(self, superClass, interfaces, delegee); Class[] ctorParms = { ScriptRuntime.ContextFactoryClass, ScriptRuntime.ScriptableClass, ScriptRuntime.ScriptableClass }; Object[] ctorArgs = { factory, delegee, self }; try { return adapterClass.getConstructor(ctorParms).newInstance(ctorArgs); } catch(InstantiationException e) { } catch(IllegalAccessException e) { } catch(InvocationTargetException e) { } catch(NoSuchMethodException e) { } throw new ClassNotFoundException("adapter"); } private static ObjToIntMap getObjectFunctionNames(Scriptable obj) { Object[] ids = ScriptableObject.getPropertyIds(obj); ObjToIntMap map = new ObjToIntMap(ids.length); for (int i = 0; i != ids.length; ++i) { if (!(ids[i] instanceof String)) continue; String id = (String) ids[i]; Object value = ScriptableObject.getProperty(obj, id); if (value instanceof Function) { Function f = (Function)value; int length = ScriptRuntime.toInt32( ScriptableObject.getProperty(f, "length")); if (length < 0) { length = 0; } map.put(id, length); } } return map; } private static Class getAdapterClass(Scriptable scope, Class superClass, Class[] interfaces, Scriptable obj) { ClassCache cache = ClassCache.get(scope); Map> generated = cache.getInterfaceAdapterCacheMap(); ObjToIntMap names = getObjectFunctionNames(obj); JavaAdapterSignature sig; sig = new JavaAdapterSignature(superClass, interfaces, names); Class adapterClass = generated.get(sig); if (adapterClass == null) { String adapterName = "adapter" + cache.newClassSerialNumber(); byte[] code = createAdapterCode(names, adapterName, superClass, interfaces, null); adapterClass = loadAdapterClass(adapterName, code); if (cache.isCachingEnabled()) { generated.put(sig, adapterClass); } } return adapterClass; } public static byte[] createAdapterCode(ObjToIntMap functionNames, String adapterName, Class superClass, Class[] interfaces, String scriptClassName) { ClassFileWriter cfw = new ClassFileWriter(adapterName, superClass.getName(), ""); cfw.addField("factory", "Lorg/mozilla/javascript/ContextFactory;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); cfw.addField("delegee", "Lorg/mozilla/javascript/Scriptable;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); cfw.addField("self", "Lorg/mozilla/javascript/Scriptable;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); int interfacesCount = interfaces == null ? 0 : interfaces.length; for (int i=0; i < interfacesCount; i++) { if (interfaces[i] != null) cfw.addInterface(interfaces[i].getName()); } String superName = superClass.getName().replace('.', '/'); generateCtor(cfw, adapterName, superName); generateSerialCtor(cfw, adapterName, superName); if (scriptClassName != null) generateEmptyCtor(cfw, adapterName, superName, scriptClassName); ObjToIntMap generatedOverrides = new ObjToIntMap(); ObjToIntMap generatedMethods = new ObjToIntMap(); // generate methods to satisfy all specified interfaces. for (int i = 0; i < interfacesCount; i++) { Method[] methods = interfaces[i].getMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int mods = method.getModifiers(); if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) { continue; } String methodName = method.getName(); Class[] argTypes = method.getParameterTypes(); if (!functionNames.has(methodName)) { try { superClass.getMethod(methodName, argTypes); // The class we're extending implements this method and // the JavaScript object doesn't have an override. See // bug 61226. continue; } catch (NoSuchMethodException e) { // Not implemented by superclass; fall through } } // make sure to generate only one instance of a particular // method/signature. String methodSignature = getMethodSignature(method, argTypes); String methodKey = methodName + methodSignature; if (! generatedOverrides.has(methodKey)) { generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType()); generatedOverrides.put(methodKey, 0); generatedMethods.put(methodName, 0); } } } // Now, go through the superclass's methods, checking for abstract // methods or additional methods to override. // generate any additional overrides that the object might contain. Method[] methods = getOverridableMethods(superClass); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int mods = method.getModifiers(); // if a method is marked abstract, must implement it or the // resulting class won't be instantiable. otherwise, if the object // has a property of the same name, then an override is intended. boolean isAbstractMethod = Modifier.isAbstract(mods); String methodName = method.getName(); if (isAbstractMethod || functionNames.has(methodName)) { // make sure to generate only one instance of a particular // method/signature. Class[] argTypes = method.getParameterTypes(); String methodSignature = getMethodSignature(method, argTypes); String methodKey = methodName + methodSignature; if (! generatedOverrides.has(methodKey)) { generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType()); generatedOverrides.put(methodKey, 0); generatedMethods.put(methodName, 0); // if a method was overridden, generate a "super$method" // which lets the delegate call the superclass' version. if (!isAbstractMethod) { generateSuper(cfw, adapterName, superName, methodName, methodSignature, argTypes, method.getReturnType()); } } } } // Generate Java methods for remaining properties that are not // overrides. ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(functionNames); for (iter.start(); !iter.done(); iter.next()) { String functionName = (String)iter.getKey(); if (generatedMethods.has(functionName)) continue; int length = iter.getValue(); Class[] parms = new Class[length]; for (int k=0; k < length; k++) parms[k] = ScriptRuntime.ObjectClass; generateMethod(cfw, adapterName, functionName, parms, ScriptRuntime.ObjectClass); } return cfw.toByteArray(); } static Method[] getOverridableMethods(Class c) { ArrayList list = new ArrayList(); HashSet skip = new HashSet(); while (c != null) { appendOverridableMethods(c, list, skip); for (Class intf: c.getInterfaces()) appendOverridableMethods(intf, list, skip); c = c.getSuperclass(); } return list.toArray(new Method[list.size()]); } private static void appendOverridableMethods(Class c, ArrayList list, HashSet skip) { Method[] methods = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { String methodKey = methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes()); if (skip.contains(methodKey)) continue; // skip this method int mods = methods[i].getModifiers(); if (Modifier.isStatic(mods)) continue; if (Modifier.isFinal(mods)) { // Make sure we don't add a final method to the list // of overridable methods. skip.add(methodKey); continue; } if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) { list.add(methods[i]); skip.add(methodKey); } } } static Class loadAdapterClass(String className, byte[] classBytes) { Object staticDomain; Class domainClass = SecurityController.getStaticSecurityDomainClass(); if(domainClass == CodeSource.class || domainClass == ProtectionDomain.class) { ProtectionDomain protectionDomain = JavaAdapter.class.getProtectionDomain(); if(domainClass == CodeSource.class) { staticDomain = protectionDomain == null ? null : protectionDomain.getCodeSource(); } else { staticDomain = protectionDomain; } } else { staticDomain = null; } GeneratedClassLoader loader = SecurityController.createLoader(null, staticDomain); Class result = loader.defineClass(className, classBytes); loader.linkClass(result); return result; } public static Function getFunction(Scriptable obj, String functionName) { Object x = ScriptableObject.getProperty(obj, functionName); if (x == Scriptable.NOT_FOUND) { // This method used to swallow the exception from calling // an undefined method. People have come to depend on this // somewhat dubious behavior. It allows people to avoid // implementing listener methods that they don't care about, // for instance. return null; } if (!(x instanceof Function)) throw ScriptRuntime.notFunctionError(x, functionName); return (Function)x; } /** * Utility method which dynamically binds a Context to the current thread, * if none already exists. */ public static Object callMethod(ContextFactory factory, final Scriptable thisObj, final Function f, final Object[] args, final long argsToWrap) { if (f == null) { // See comments in getFunction return Undefined.instance; } if (factory == null) { factory = ContextFactory.getGlobal(); } final Scriptable scope = f.getParentScope(); if (argsToWrap == 0) { return Context.call(factory, f, scope, thisObj, args); } Context cx = Context.getCurrentContext(); if (cx != null) { return doCall(cx, scope, thisObj, f, args, argsToWrap); } else { return factory.call(new ContextAction() { public Object run(Context cx) { return doCall(cx, scope, thisObj, f, args, argsToWrap); } }); } } private static Object doCall(Context cx, Scriptable scope, Scriptable thisObj, Function f, Object[] args, long argsToWrap) { // Wrap the rest of objects for (int i = 0; i != args.length; ++i) { if (0 != (argsToWrap & (1 << i))) { Object arg = args[i]; if (!(arg instanceof Scriptable)) { args[i] = cx.getWrapFactory().wrap(cx, scope, arg, null); } } } return f.call(cx, scope, thisObj, args); } public static Scriptable runScript(final Script script) { return (Scriptable)ContextFactory.getGlobal().call( new ContextAction() { public Object run(Context cx) { ScriptableObject global = ScriptRuntime.getGlobal(cx); script.exec(cx, global); return global; } }); } private static void generateCtor(ClassFileWriter cfw, String adapterName, String superName) { cfw.startMethod("", "(Lorg/mozilla/javascript/ContextFactory;" +"Lorg/mozilla/javascript/Scriptable;)V", ClassFileWriter.ACC_PUBLIC); // Invoke base class constructor cfw.add(ByteCode.ALOAD_0); // this cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "", "()V"); // Save parameter in instance variable "factory" cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_1); // first arg: ContextFactory instance cfw.add(ByteCode.PUTFIELD, adapterName, "factory", "Lorg/mozilla/javascript/ContextFactory;"); // Save parameter in instance variable "delegee" cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_2); // second arg: Scriptable delegee cfw.add(ByteCode.PUTFIELD, adapterName, "delegee", "Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.ALOAD_0); // this for the following PUTFIELD for self // create a wrapper object to be used as "this" in method calls cfw.add(ByteCode.ALOAD_2); // the Scriptable delegee cfw.add(ByteCode.ALOAD_0); // this cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "createAdapterWrapper", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.PUTFIELD, adapterName, "self", "Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.RETURN); cfw.stopMethod((short)3); // 3: this + factory + delegee } private static void generateSerialCtor(ClassFileWriter cfw, String adapterName, String superName) { cfw.startMethod("", "(Lorg/mozilla/javascript/ContextFactory;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +")V", ClassFileWriter.ACC_PUBLIC); // Invoke base class constructor cfw.add(ByteCode.ALOAD_0); // this cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "", "()V"); // Save parameter in instance variable "factory" cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_1); // first arg: ContextFactory instance cfw.add(ByteCode.PUTFIELD, adapterName, "factory", "Lorg/mozilla/javascript/ContextFactory;"); // Save parameter in instance variable "delegee" cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_2); // second arg: Scriptable delegee cfw.add(ByteCode.PUTFIELD, adapterName, "delegee", "Lorg/mozilla/javascript/Scriptable;"); // save self cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_3); // second arg: Scriptable self cfw.add(ByteCode.PUTFIELD, adapterName, "self", "Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.RETURN); cfw.stopMethod((short)4); // 4: this + factory + delegee + self } private static void generateEmptyCtor(ClassFileWriter cfw, String adapterName, String superName, String scriptClassName) { cfw.startMethod("", "()V", ClassFileWriter.ACC_PUBLIC); // Invoke base class constructor cfw.add(ByteCode.ALOAD_0); // this cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "", "()V"); // Set factory to null to use current global when necessary cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.ACONST_NULL); cfw.add(ByteCode.PUTFIELD, adapterName, "factory", "Lorg/mozilla/javascript/ContextFactory;"); // Load script class cfw.add(ByteCode.NEW, scriptClassName); cfw.add(ByteCode.DUP); cfw.addInvoke(ByteCode.INVOKESPECIAL, scriptClassName, "", "()V"); // Run script and save resulting scope cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "runScript", "(Lorg/mozilla/javascript/Script;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.ASTORE_1); // Save the Scriptable in instance variable "delegee" cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_1); // the Scriptable cfw.add(ByteCode.PUTFIELD, adapterName, "delegee", "Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.ALOAD_0); // this for the following PUTFIELD for self // create a wrapper object to be used as "this" in method calls cfw.add(ByteCode.ALOAD_1); // the Scriptable cfw.add(ByteCode.ALOAD_0); // this cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "createAdapterWrapper", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.PUTFIELD, adapterName, "self", "Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.RETURN); cfw.stopMethod((short)2); // this + delegee } /** * Generates code to wrap Java arguments into Object[]. * Non-primitive Java types are left as-is pending conversion * in the helper method. Leaves the array object on the top of the stack. */ static void generatePushWrappedArgs(ClassFileWriter cfw, Class[] argTypes, int arrayLength) { // push arguments cfw.addPush(arrayLength); cfw.add(ByteCode.ANEWARRAY, "java/lang/Object"); int paramOffset = 1; for (int i = 0; i != argTypes.length; ++i) { cfw.add(ByteCode.DUP); // duplicate array reference cfw.addPush(i); paramOffset += generateWrapArg(cfw, paramOffset, argTypes[i]); cfw.add(ByteCode.AASTORE); } } /** * Generates code to wrap Java argument into Object. * Non-primitive Java types are left unconverted pending conversion * in the helper method. Leaves the wrapper object on the top of the stack. */ private static int generateWrapArg(ClassFileWriter cfw, int paramOffset, Class argType) { int size = 1; if (!argType.isPrimitive()) { cfw.add(ByteCode.ALOAD, paramOffset); } else if (argType == Boolean.TYPE) { // wrap boolean values with java.lang.Boolean. cfw.add(ByteCode.NEW, "java/lang/Boolean"); cfw.add(ByteCode.DUP); cfw.add(ByteCode.ILOAD, paramOffset); cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Boolean", "", "(Z)V"); } else if (argType == Character.TYPE) { // Create a string of length 1 using the character parameter. cfw.add(ByteCode.ILOAD, paramOffset); cfw.addInvoke(ByteCode.INVOKESTATIC, "java/lang/String", "valueOf", "(C)Ljava/lang/String;"); } else { // convert all numeric values to java.lang.Double. cfw.add(ByteCode.NEW, "java/lang/Double"); cfw.add(ByteCode.DUP); String typeName = argType.getName(); switch (typeName.charAt(0)) { case 'b': case 's': case 'i': // load an int value, convert to double. cfw.add(ByteCode.ILOAD, paramOffset); cfw.add(ByteCode.I2D); break; case 'l': // load a long, convert to double. cfw.add(ByteCode.LLOAD, paramOffset); cfw.add(ByteCode.L2D); size = 2; break; case 'f': // load a float, convert to double. cfw.add(ByteCode.FLOAD, paramOffset); cfw.add(ByteCode.F2D); break; case 'd': cfw.add(ByteCode.DLOAD, paramOffset); size = 2; break; } cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Double", "", "(D)V"); } return size; } /** * Generates code to convert a wrapped value type to a primitive type. * Handles unwrapping java.lang.Boolean, and java.lang.Number types. * Generates the appropriate RETURN bytecode. */ static void generateReturnResult(ClassFileWriter cfw, Class retType, boolean callConvertResult) { // wrap boolean values with java.lang.Boolean, convert all other // primitive values to java.lang.Double. if (retType == Void.TYPE) { cfw.add(ByteCode.POP); cfw.add(ByteCode.RETURN); } else if (retType == Boolean.TYPE) { cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/Context", "toBoolean", "(Ljava/lang/Object;)Z"); cfw.add(ByteCode.IRETURN); } else if (retType == Character.TYPE) { // characters are represented as strings in JavaScript. // return the first character. // first convert the value to a string if possible. cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/Context", "toString", "(Ljava/lang/Object;)Ljava/lang/String;"); cfw.add(ByteCode.ICONST_0); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/String", "charAt", "(I)C"); cfw.add(ByteCode.IRETURN); } else if (retType.isPrimitive()) { cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/Context", "toNumber", "(Ljava/lang/Object;)D"); String typeName = retType.getName(); switch (typeName.charAt(0)) { case 'b': case 's': case 'i': cfw.add(ByteCode.D2I); cfw.add(ByteCode.IRETURN); break; case 'l': cfw.add(ByteCode.D2L); cfw.add(ByteCode.LRETURN); break; case 'f': cfw.add(ByteCode.D2F); cfw.add(ByteCode.FRETURN); break; case 'd': cfw.add(ByteCode.DRETURN); break; default: throw new RuntimeException("Unexpected return type " + retType.toString()); } } else { String retTypeStr = retType.getName(); if (callConvertResult) { cfw.addLoadConstant(retTypeStr); cfw.addInvoke(ByteCode.INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "convertResult", "(Ljava/lang/Object;" +"Ljava/lang/Class;" +")Ljava/lang/Object;"); } // Now cast to return type cfw.add(ByteCode.CHECKCAST, retTypeStr); cfw.add(ByteCode.ARETURN); } } private static void generateMethod(ClassFileWriter cfw, String genName, String methodName, Class[] parms, Class returnType) { StringBuffer sb = new StringBuffer(); int paramsEnd = appendMethodSignature(parms, returnType, sb); String methodSignature = sb.toString(); cfw.startMethod(methodName, methodSignature, ClassFileWriter.ACC_PUBLIC); // Prepare stack to call method // push factory cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, genName, "factory", "Lorg/mozilla/javascript/ContextFactory;"); // push self cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, genName, "self", "Lorg/mozilla/javascript/Scriptable;"); // push function cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, genName, "delegee", "Lorg/mozilla/javascript/Scriptable;"); cfw.addPush(methodName); cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "getFunction", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Lorg/mozilla/javascript/Function;"); // push arguments generatePushWrappedArgs(cfw, parms, parms.length); // push bits to indicate which parameters should be wrapped if (parms.length > 64) { // If it will be an issue, then passing a static boolean array // can be an option, but for now using simple bitmask throw Context.reportRuntimeError0( "JavaAdapter can not subclass methods with more then" +" 64 arguments."); } long convertionMask = 0; for (int i = 0; i != parms.length; ++i) { if (!parms[i].isPrimitive()) { convertionMask |= (1 << i); } } cfw.addPush(convertionMask); // go through utility method, which creates a Context to run the // method in. cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "callMethod", "(Lorg/mozilla/javascript/ContextFactory;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Function;" +"[Ljava/lang/Object;" +"J" +")Ljava/lang/Object;"); generateReturnResult(cfw, returnType, true); cfw.stopMethod((short)paramsEnd); } /** * Generates code to push typed parameters onto the operand stack * prior to a direct Java method call. */ private static int generatePushParam(ClassFileWriter cfw, int paramOffset, Class paramType) { if (!paramType.isPrimitive()) { cfw.addALoad(paramOffset); return 1; } String typeName = paramType.getName(); switch (typeName.charAt(0)) { case 'z': case 'b': case 'c': case 's': case 'i': // load an int value, convert to double. cfw.addILoad(paramOffset); return 1; case 'l': // load a long, convert to double. cfw.addLLoad(paramOffset); return 2; case 'f': // load a float, convert to double. cfw.addFLoad(paramOffset); return 1; case 'd': cfw.addDLoad(paramOffset); return 2; } throw Kit.codeBug(); } /** * Generates code to return a Java type, after calling a Java method * that returns the same type. * Generates the appropriate RETURN bytecode. */ private static void generatePopResult(ClassFileWriter cfw, Class retType) { if (retType.isPrimitive()) { String typeName = retType.getName(); switch (typeName.charAt(0)) { case 'b': case 'c': case 's': case 'i': case 'z': cfw.add(ByteCode.IRETURN); break; case 'l': cfw.add(ByteCode.LRETURN); break; case 'f': cfw.add(ByteCode.FRETURN); break; case 'd': cfw.add(ByteCode.DRETURN); break; } } else { cfw.add(ByteCode.ARETURN); } } /** * Generates a method called "super$methodName()" which can be called * from JavaScript that is equivalent to calling "super.methodName()" * from Java. Eventually, this may be supported directly in JavaScript. */ private static void generateSuper(ClassFileWriter cfw, String genName, String superName, String methodName, String methodSignature, Class[] parms, Class returnType) { cfw.startMethod("super$" + methodName, methodSignature, ClassFileWriter.ACC_PUBLIC); // push "this" cfw.add(ByteCode.ALOAD, 0); // push the rest of the parameters. int paramOffset = 1; for (int i = 0; i < parms.length; i++) { paramOffset += generatePushParam(cfw, paramOffset, parms[i]); } // call the superclass implementation of the method. cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, methodName, methodSignature); // now, handle the return type appropriately. Class retType = returnType; if (!retType.equals(Void.TYPE)) { generatePopResult(cfw, retType); } else { cfw.add(ByteCode.RETURN); } cfw.stopMethod((short)(paramOffset + 1)); } /** * Returns a fully qualified method name concatenated with its signature. */ private static String getMethodSignature(Method method, Class[] argTypes) { StringBuffer sb = new StringBuffer(); appendMethodSignature(argTypes, method.getReturnType(), sb); return sb.toString(); } static int appendMethodSignature(Class[] argTypes, Class returnType, StringBuffer sb) { sb.append('('); int firstLocal = 1 + argTypes.length; // includes this. for (int i = 0; i < argTypes.length; i++) { Class type = argTypes[i]; appendTypeString(sb, type); if (type == Long.TYPE || type == Double.TYPE) { // adjust for duble slot ++firstLocal; } } sb.append(')'); appendTypeString(sb, returnType); return firstLocal; } private static StringBuffer appendTypeString(StringBuffer sb, Class type) { while (type.isArray()) { sb.append('['); type = type.getComponentType(); } if (type.isPrimitive()) { char typeLetter; if (type == Boolean.TYPE) { typeLetter = 'Z'; } else if (type == Long.TYPE) { typeLetter = 'J'; } else { String typeName = type.getName(); typeLetter = Character.toUpperCase(typeName.charAt(0)); } sb.append(typeLetter); } else { sb.append('L'); sb.append(type.getName().replace('.', '/')); sb.append(';'); } return sb; } static int[] getArgsToConvert(Class[] argTypes) { int count = 0; for (int i = 0; i != argTypes.length; ++i) { if (!argTypes[i].isPrimitive()) ++count; } if (count == 0) return null; int[] array = new int[count]; count = 0; for (int i = 0; i != argTypes.length; ++i) { if (!argTypes[i].isPrimitive()) array[count++] = i; } return array; } private static final Object FTAG = "JavaAdapter"; private static final int Id_JavaAdapter = 1; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/Token.java0000644000175000017500000004414111314263504032032 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Roger Lawrence * Mike McCabe * Igor Bukanov * Bob Jervis * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; /** * This class implements the JavaScript scanner. * * It is based on the C source files jsscan.c and jsscan.h * in the jsref package. * * @see org.mozilla.javascript.Parser * * @author Mike McCabe * @author Brendan Eich */ public class Token { public static enum CommentType { LINE, BLOCK, JSDOC, HTML } // debug flags public static final boolean printTrees = false; static final boolean printICode = false; static final boolean printNames = printTrees || printICode; /** * Token types. These values correspond to JSTokenType values in * jsscan.c. */ public final static int // start enum ERROR = -1, // well-known as the only code < EOF EOF = 0, // end of file token - (not EOF_CHAR) EOL = 1, // end of line // Interpreter reuses the following as bytecodes FIRST_BYTECODE_TOKEN = 2, ENTERWITH = 2, LEAVEWITH = 3, RETURN = 4, GOTO = 5, IFEQ = 6, IFNE = 7, SETNAME = 8, BITOR = 9, BITXOR = 10, BITAND = 11, EQ = 12, NE = 13, LT = 14, LE = 15, GT = 16, GE = 17, LSH = 18, RSH = 19, URSH = 20, ADD = 21, SUB = 22, MUL = 23, DIV = 24, MOD = 25, NOT = 26, BITNOT = 27, POS = 28, NEG = 29, NEW = 30, DELPROP = 31, TYPEOF = 32, GETPROP = 33, GETPROPNOWARN = 34, SETPROP = 35, GETELEM = 36, SETELEM = 37, CALL = 38, NAME = 39, NUMBER = 40, STRING = 41, NULL = 42, THIS = 43, FALSE = 44, TRUE = 45, SHEQ = 46, // shallow equality (===) SHNE = 47, // shallow inequality (!==) REGEXP = 48, BINDNAME = 49, THROW = 50, RETHROW = 51, // rethrow caught exception: catch (e if ) use it IN = 52, INSTANCEOF = 53, LOCAL_LOAD = 54, GETVAR = 55, SETVAR = 56, CATCH_SCOPE = 57, ENUM_INIT_KEYS = 58, ENUM_INIT_VALUES = 59, ENUM_INIT_ARRAY= 60, ENUM_NEXT = 61, ENUM_ID = 62, THISFN = 63, RETURN_RESULT = 64, // to return previously stored return result ARRAYLIT = 65, // array literal OBJECTLIT = 66, // object literal GET_REF = 67, // *reference SET_REF = 68, // *reference = something DEL_REF = 69, // delete reference REF_CALL = 70, // f(args) = something or f(args)++ REF_SPECIAL = 71, // reference for special properties like __proto YIELD = 72, // JS 1.7 yield pseudo keyword // For XML support: DEFAULTNAMESPACE = 73, // default xml namespace = ESCXMLATTR = 74, ESCXMLTEXT = 75, REF_MEMBER = 76, // Reference for x.@y, x..y etc. REF_NS_MEMBER = 77, // Reference for x.ns::y, x..ns::y etc. REF_NAME = 78, // Reference for @y, @[y] etc. REF_NS_NAME = 79; // Reference for ns::y, @ns::y@[y] etc. // End of interpreter bytecodes public final static int LAST_BYTECODE_TOKEN = REF_NS_NAME, TRY = 80, SEMI = 81, // semicolon LB = 82, // left and right brackets RB = 83, LC = 84, // left and right curlies (braces) RC = 85, LP = 86, // left and right parentheses RP = 87, COMMA = 88, // comma operator ASSIGN = 89, // simple assignment (=) ASSIGN_BITOR = 90, // |= ASSIGN_BITXOR = 91, // ^= ASSIGN_BITAND = 92, // |= ASSIGN_LSH = 93, // <<= ASSIGN_RSH = 94, // >>= ASSIGN_URSH = 95, // >>>= ASSIGN_ADD = 96, // += ASSIGN_SUB = 97, // -= ASSIGN_MUL = 98, // *= ASSIGN_DIV = 99, // /= ASSIGN_MOD = 100; // %= public final static int FIRST_ASSIGN = ASSIGN, LAST_ASSIGN = ASSIGN_MOD, HOOK = 101, // conditional (?:) COLON = 102, OR = 103, // logical or (||) AND = 104, // logical and (&&) INC = 105, // increment/decrement (++ --) DEC = 106, DOT = 107, // member operator (.) FUNCTION = 108, // function keyword EXPORT = 109, // export keyword IMPORT = 110, // import keyword IF = 111, // if keyword ELSE = 112, // else keyword SWITCH = 113, // switch keyword CASE = 114, // case keyword DEFAULT = 115, // default keyword WHILE = 116, // while keyword DO = 117, // do keyword FOR = 118, // for keyword BREAK = 119, // break keyword CONTINUE = 120, // continue keyword VAR = 121, // var keyword WITH = 122, // with keyword CATCH = 123, // catch keyword FINALLY = 124, // finally keyword VOID = 125, // void keyword RESERVED = 126, // reserved keywords EMPTY = 127, /* types used for the parse tree - these never get returned * by the scanner. */ BLOCK = 128, // statement block LABEL = 129, // label TARGET = 130, LOOP = 131, EXPR_VOID = 132, // expression statement in functions EXPR_RESULT = 133, // expression statement in scripts JSR = 134, SCRIPT = 135, // top-level node for entire script TYPEOFNAME = 136, // for typeof(simple-name) USE_STACK = 137, SETPROP_OP = 138, // x.y op= something SETELEM_OP = 139, // x[y] op= something LOCAL_BLOCK = 140, SET_REF_OP = 141, // *reference op= something // For XML support: DOTDOT = 142, // member operator (..) COLONCOLON = 143, // namespace::name XML = 144, // XML type DOTQUERY = 145, // .() -- e.g., x.emps.emp.(name == "terry") XMLATTR = 146, // @ XMLEND = 147, // Optimizer-only-tokens TO_OBJECT = 148, TO_DOUBLE = 149, GET = 150, // JS 1.5 get pseudo keyword SET = 151, // JS 1.5 set pseudo keyword LET = 152, // JS 1.7 let pseudo keyword CONST = 153, SETCONST = 154, SETCONSTVAR = 155, ARRAYCOMP = 156, // array comprehension LETEXPR = 157, WITHEXPR = 158, DEBUGGER = 159, COMMENT = 160, LAST_TOKEN = 160; /** * Returns a name for the token. If Rhino is compiled with certain * hardcoded debugging flags in this file, it calls {@code #typeToName}; * otherwise it returns a string whose value is the token number. */ public static String name(int token) { if (!printNames) { return String.valueOf(token); } return typeToName(token); } /** * Always returns a human-readable string for the token name. * For instance, {@link #FINALLY} has the name "FINALLY". * @param token the token code * @return the actual name for the token code */ public static String typeToName(int token) { switch (token) { case ERROR: return "ERROR"; case EOF: return "EOF"; case EOL: return "EOL"; case ENTERWITH: return "ENTERWITH"; case LEAVEWITH: return "LEAVEWITH"; case RETURN: return "RETURN"; case GOTO: return "GOTO"; case IFEQ: return "IFEQ"; case IFNE: return "IFNE"; case SETNAME: return "SETNAME"; case BITOR: return "BITOR"; case BITXOR: return "BITXOR"; case BITAND: return "BITAND"; case EQ: return "EQ"; case NE: return "NE"; case LT: return "LT"; case LE: return "LE"; case GT: return "GT"; case GE: return "GE"; case LSH: return "LSH"; case RSH: return "RSH"; case URSH: return "URSH"; case ADD: return "ADD"; case SUB: return "SUB"; case MUL: return "MUL"; case DIV: return "DIV"; case MOD: return "MOD"; case NOT: return "NOT"; case BITNOT: return "BITNOT"; case POS: return "POS"; case NEG: return "NEG"; case NEW: return "NEW"; case DELPROP: return "DELPROP"; case TYPEOF: return "TYPEOF"; case GETPROP: return "GETPROP"; case GETPROPNOWARN: return "GETPROPNOWARN"; case SETPROP: return "SETPROP"; case GETELEM: return "GETELEM"; case SETELEM: return "SETELEM"; case CALL: return "CALL"; case NAME: return "NAME"; case NUMBER: return "NUMBER"; case STRING: return "STRING"; case NULL: return "NULL"; case THIS: return "THIS"; case FALSE: return "FALSE"; case TRUE: return "TRUE"; case SHEQ: return "SHEQ"; case SHNE: return "SHNE"; case REGEXP: return "REGEXP"; case BINDNAME: return "BINDNAME"; case THROW: return "THROW"; case RETHROW: return "RETHROW"; case IN: return "IN"; case INSTANCEOF: return "INSTANCEOF"; case LOCAL_LOAD: return "LOCAL_LOAD"; case GETVAR: return "GETVAR"; case SETVAR: return "SETVAR"; case CATCH_SCOPE: return "CATCH_SCOPE"; case ENUM_INIT_KEYS: return "ENUM_INIT_KEYS"; case ENUM_INIT_VALUES:return "ENUM_INIT_VALUES"; case ENUM_INIT_ARRAY: return "ENUM_INIT_ARRAY"; case ENUM_NEXT: return "ENUM_NEXT"; case ENUM_ID: return "ENUM_ID"; case THISFN: return "THISFN"; case RETURN_RESULT: return "RETURN_RESULT"; case ARRAYLIT: return "ARRAYLIT"; case OBJECTLIT: return "OBJECTLIT"; case GET_REF: return "GET_REF"; case SET_REF: return "SET_REF"; case DEL_REF: return "DEL_REF"; case REF_CALL: return "REF_CALL"; case REF_SPECIAL: return "REF_SPECIAL"; case DEFAULTNAMESPACE:return "DEFAULTNAMESPACE"; case ESCXMLTEXT: return "ESCXMLTEXT"; case ESCXMLATTR: return "ESCXMLATTR"; case REF_MEMBER: return "REF_MEMBER"; case REF_NS_MEMBER: return "REF_NS_MEMBER"; case REF_NAME: return "REF_NAME"; case REF_NS_NAME: return "REF_NS_NAME"; case TRY: return "TRY"; case SEMI: return "SEMI"; case LB: return "LB"; case RB: return "RB"; case LC: return "LC"; case RC: return "RC"; case LP: return "LP"; case RP: return "RP"; case COMMA: return "COMMA"; case ASSIGN: return "ASSIGN"; case ASSIGN_BITOR: return "ASSIGN_BITOR"; case ASSIGN_BITXOR: return "ASSIGN_BITXOR"; case ASSIGN_BITAND: return "ASSIGN_BITAND"; case ASSIGN_LSH: return "ASSIGN_LSH"; case ASSIGN_RSH: return "ASSIGN_RSH"; case ASSIGN_URSH: return "ASSIGN_URSH"; case ASSIGN_ADD: return "ASSIGN_ADD"; case ASSIGN_SUB: return "ASSIGN_SUB"; case ASSIGN_MUL: return "ASSIGN_MUL"; case ASSIGN_DIV: return "ASSIGN_DIV"; case ASSIGN_MOD: return "ASSIGN_MOD"; case HOOK: return "HOOK"; case COLON: return "COLON"; case OR: return "OR"; case AND: return "AND"; case INC: return "INC"; case DEC: return "DEC"; case DOT: return "DOT"; case FUNCTION: return "FUNCTION"; case EXPORT: return "EXPORT"; case IMPORT: return "IMPORT"; case IF: return "IF"; case ELSE: return "ELSE"; case SWITCH: return "SWITCH"; case CASE: return "CASE"; case DEFAULT: return "DEFAULT"; case WHILE: return "WHILE"; case DO: return "DO"; case FOR: return "FOR"; case BREAK: return "BREAK"; case CONTINUE: return "CONTINUE"; case VAR: return "VAR"; case WITH: return "WITH"; case CATCH: return "CATCH"; case FINALLY: return "FINALLY"; case VOID: return "VOID"; case RESERVED: return "RESERVED"; case EMPTY: return "EMPTY"; case BLOCK: return "BLOCK"; case LABEL: return "LABEL"; case TARGET: return "TARGET"; case LOOP: return "LOOP"; case EXPR_VOID: return "EXPR_VOID"; case EXPR_RESULT: return "EXPR_RESULT"; case JSR: return "JSR"; case SCRIPT: return "SCRIPT"; case TYPEOFNAME: return "TYPEOFNAME"; case USE_STACK: return "USE_STACK"; case SETPROP_OP: return "SETPROP_OP"; case SETELEM_OP: return "SETELEM_OP"; case LOCAL_BLOCK: return "LOCAL_BLOCK"; case SET_REF_OP: return "SET_REF_OP"; case DOTDOT: return "DOTDOT"; case COLONCOLON: return "COLONCOLON"; case XML: return "XML"; case DOTQUERY: return "DOTQUERY"; case XMLATTR: return "XMLATTR"; case XMLEND: return "XMLEND"; case TO_OBJECT: return "TO_OBJECT"; case TO_DOUBLE: return "TO_DOUBLE"; case GET: return "GET"; case SET: return "SET"; case LET: return "LET"; case YIELD: return "YIELD"; case CONST: return "CONST"; case SETCONST: return "SETCONST"; case ARRAYCOMP: return "ARRAYCOMP"; case WITHEXPR: return "WITHEXPR"; case LETEXPR: return "LETEXPR"; case DEBUGGER: return "DEBUGGER"; case COMMENT: return "COMMENT"; } // Token without name throw new IllegalStateException(String.valueOf(token)); } /** * Return true if the passed code is a valid Token constant. * @param code a potential token code * @return true if it's a known token */ public static boolean isValidToken(int code) { return code >= ERROR && code <= LAST_TOKEN; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/xml/0000755000175000017500000000000011537630013030703 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/xml/XMLObject.java0000644000175000017500000001107211314263504033336 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Ethan Hugg * Terry Lucas * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml; import org.mozilla.javascript.*; /** * This Interface describes what all XML objects (XML, XMLList) should have in common. * */ public abstract class XMLObject extends IdScriptableObject { public XMLObject() { } public XMLObject(Scriptable scope, Scriptable prototype) { super(scope, prototype); } /** * Implementation of ECMAScript [[Has]]. */ public abstract boolean ecmaHas(Context cx, Object id); /** * Implementation of ECMAScript [[Get]]. */ public abstract Object ecmaGet(Context cx, Object id); /** * Implementation of ECMAScript [[Put]]. */ public abstract void ecmaPut(Context cx, Object id, Object value); /** * Implementation of ECMAScript [[Delete]]. */ public abstract boolean ecmaDelete(Context cx, Object id); /** * Return an additional object to look for methods that runtime should * consider during method search. Return null if no such object available. */ public abstract Scriptable getExtraMethodSource(Context cx); /** * Generic reference to implement x.@y, x..y etc. */ public abstract Ref memberRef(Context cx, Object elem, int memberTypeFlags); /** * Generic reference to implement x::ns, x.@ns::y, x..@ns::y etc. */ public abstract Ref memberRef(Context cx, Object namespace, Object elem, int memberTypeFlags); /** * Wrap this object into NativeWith to implement the with statement. */ public abstract NativeWith enterWith(Scriptable scope); /** * Wrap this object into NativeWith to implement the .() query. */ public abstract NativeWith enterDotQuery(Scriptable scope); /** * Custom + operator. * Should return {@link Scriptable#NOT_FOUND} if this object does not have * custom addition operator for the given value, * or the result of the addition operation. *

* The default implementation returns {@link Scriptable#NOT_FOUND} * to indicate no custom addition operation. * * @param cx the Context object associated with the current thread. * @param thisIsLeft if true, the object should calculate this + value * if false, the object should calculate value + this. * @param value the second argument for addition operation. */ public Object addValues(Context cx, boolean thisIsLeft, Object value) { return Scriptable.NOT_FOUND; } /** * Gets the value returned by calling the typeof operator on this object. * @see org.mozilla.javascript.ScriptableObject#getTypeOf() * @return "xml" or "undefined" if {@link #avoidObjectDetection()} returns true */ @Override public String getTypeOf() { return avoidObjectDetection() ? "undefined" : "xml"; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/xml/XMLLib.java0000644000175000017500000001300111314263504032630 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xml; import org.mozilla.javascript.*; public abstract class XMLLib { private static final Object XML_LIB_KEY = new Object(); /** An object which specifies an XMLLib implementation to be used at runtime. This interface should be considered experimental. It may be better (and certainly more flexible) to write an interface that returns an XMLLib object rather than a class name, for example. But that would cause many more ripple effects in the code, all the way back to {@link ScriptRuntime}. */ public static abstract class Factory { public static Factory create(final String className) { return new Factory() { @Override public String getImplementationClassName() { return className; } }; } public abstract String getImplementationClassName(); } public static XMLLib extractFromScopeOrNull(Scriptable scope) { ScriptableObject so = ScriptRuntime.getLibraryScopeOrNull(scope); if (so == null) { // If library is not yet initialized, return null return null; } // Ensure lazily initialization of real XML library instance // which is done on first access to XML property ScriptableObject.getProperty(so, "XML"); return (XMLLib)so.getAssociatedValue(XML_LIB_KEY); } public static XMLLib extractFromScope(Scriptable scope) { XMLLib lib = extractFromScopeOrNull(scope); if (lib != null) { return lib; } String msg = ScriptRuntime.getMessage0("msg.XML.not.available"); throw Context.reportRuntimeError(msg); } protected final XMLLib bindToScope(Scriptable scope) { ScriptableObject so = ScriptRuntime.getLibraryScopeOrNull(scope); if (so == null) { // standard library should be initialized at this point throw new IllegalStateException(); } return (XMLLib)so.associateValue(XML_LIB_KEY, this); } public abstract boolean isXMLName(Context cx, Object name); public abstract Ref nameRef(Context cx, Object name, Scriptable scope, int memberTypeFlags); public abstract Ref nameRef(Context cx, Object namespace, Object name, Scriptable scope, int memberTypeFlags); /** * Escapes the reserved characters in a value of an attribute. * * @param value Unescaped text * @return The escaped text */ public abstract String escapeAttributeValue(Object value); /** * Escapes the reserved characters in a value of a text node. * * @param value Unescaped text * @return The escaped text */ public abstract String escapeTextValue(Object value); /** * Construct namespace for default xml statement. */ public abstract Object toDefaultXmlNamespace(Context cx, Object uriValue); public void setIgnoreComments(boolean b) { throw new UnsupportedOperationException(); } public void setIgnoreWhitespace(boolean b) { throw new UnsupportedOperationException(); } public void setIgnoreProcessingInstructions(boolean b) { throw new UnsupportedOperationException(); } public void setPrettyPrinting(boolean b) { throw new UnsupportedOperationException(); } public void setPrettyIndent(int i) { throw new UnsupportedOperationException(); } public boolean isIgnoreComments() { throw new UnsupportedOperationException(); } public boolean isIgnoreProcessingInstructions() { throw new UnsupportedOperationException(); } public boolean isIgnoreWhitespace() { throw new UnsupportedOperationException(); } public boolean isPrettyPrinting() { throw new UnsupportedOperationException(); } public int getPrettyIndent() { throw new UnsupportedOperationException(); } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/Kit.java0000644000175000017500000003707111314263504031505 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov, igor@fastmail.fm * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Method; import java.util.Map; /** * Collection of utilities */ public class Kit { /** * Reflection of Throwable.initCause(Throwable) from JDK 1.4 * or nul if it is not available. */ private static Method Throwable_initCause = null; static { // Are we running on a JDK 1.4 or later system? try { Class ThrowableClass = Kit.classOrNull("java.lang.Throwable"); Class[] signature = { ThrowableClass }; Throwable_initCause = ThrowableClass.getMethod("initCause", signature); } catch (Exception ex) { // Assume any exceptions means the method does not exist. } } public static Class classOrNull(String className) { try { return Class.forName(className); } catch (ClassNotFoundException ex) { } catch (SecurityException ex) { } catch (LinkageError ex) { } catch (IllegalArgumentException e) { // Can be thrown if name has characters that a class name // can not contain } return null; } /** * Attempt to load the class of the given name. Note that the type parameter * isn't checked. */ public static Class classOrNull(ClassLoader loader, String className) { try { return loader.loadClass(className); } catch (ClassNotFoundException ex) { } catch (SecurityException ex) { } catch (LinkageError ex) { } catch (IllegalArgumentException e) { // Can be thrown if name has characters that a class name // can not contain } return null; } static Object newInstanceOrNull(Class cl) { try { return cl.newInstance(); } catch (SecurityException x) { } catch (LinkageError ex) { } catch (InstantiationException x) { } catch (IllegalAccessException x) { } return null; } /** * Check that testClass is accessible from the given loader. */ static boolean testIfCanLoadRhinoClasses(ClassLoader loader) { Class testClass = ScriptRuntime.ContextFactoryClass; Class x = Kit.classOrNull(loader, testClass.getName()); if (x != testClass) { // The check covers the case when x == null => // loader does not know about testClass or the case // when x != null && x != testClass => // loader loads a class unrelated to testClass return false; } return true; } /** * If initCause methods exists in Throwable, call * ex.initCause(cause) or otherwise do nothing. * @return The ex argument. */ public static RuntimeException initCause(RuntimeException ex, Throwable cause) { if (Throwable_initCause != null) { Object[] args = { cause }; try { Throwable_initCause.invoke(ex, args); } catch (Exception e) { // Ignore any exceptions } } return ex; } /** * If character c is a hexadecimal digit, return * accumulator * 16 plus corresponding * number. Otherise return -1. */ public static int xDigitToInt(int c, int accumulator) { check: { // Use 0..9 < A..Z < a..z if (c <= '9') { c -= '0'; if (0 <= c) { break check; } } else if (c <= 'F') { if ('A' <= c) { c -= ('A' - 10); break check; } } else if (c <= 'f') { if ('a' <= c) { c -= ('a' - 10); break check; } } return -1; } return (accumulator << 4) | c; } /** * Add listener to bag of listeners. * The function does not modify bag and return a new collection * containing listener and all listeners from bag. * Bag without listeners always represented as the null value. *

* Usage example: *

     *     private volatile Object changeListeners;
     *
     *     public void addMyListener(PropertyChangeListener l)
     *     {
     *         synchronized (this) {
     *             changeListeners = Kit.addListener(changeListeners, l);
     *         }
     *     }
     *
     *     public void removeTextListener(PropertyChangeListener l)
     *     {
     *         synchronized (this) {
     *             changeListeners = Kit.removeListener(changeListeners, l);
     *         }
     *     }
     *
     *     public void fireChangeEvent(Object oldValue, Object newValue)
     *     {
     *     // Get immune local copy
     *         Object listeners = changeListeners;
     *         if (listeners != null) {
     *             PropertyChangeEvent e = new PropertyChangeEvent(
     *                 this, "someProperty" oldValue, newValue);
     *             for (int i = 0; ; ++i) {
     *                 Object l = Kit.getListener(listeners, i);
     *                 if (l == null)
     *                     break;
     *                 ((PropertyChangeListener)l).propertyChange(e);
     *             }
     *         }
     *     }
     * 
* * @param listener Listener to add to bag * @param bag Current collection of listeners. * @return A new bag containing all listeners from bag and * listener. * @see #removeListener(Object bag, Object listener) * @see #getListener(Object bag, int index) */ public static Object addListener(Object bag, Object listener) { if (listener == null) throw new IllegalArgumentException(); if (listener instanceof Object[]) throw new IllegalArgumentException(); if (bag == null) { bag = listener; } else if (!(bag instanceof Object[])) { bag = new Object[] { bag, listener }; } else { Object[] array = (Object[])bag; int L = array.length; // bag has at least 2 elements if it is array if (L < 2) throw new IllegalArgumentException(); Object[] tmp = new Object[L + 1]; System.arraycopy(array, 0, tmp, 0, L); tmp[L] = listener; bag = tmp; } return bag; } /** * Remove listener from bag of listeners. * The function does not modify bag and return a new collection * containing all listeners from bag except listener. * If bag does not contain listener, the function returns * bag. *

* For usage example, see {@link #addListener(Object bag, Object listener)}. * * @param listener Listener to remove from bag * @param bag Current collection of listeners. * @return A new bag containing all listeners from bag except * listener. * @see #addListener(Object bag, Object listener) * @see #getListener(Object bag, int index) */ public static Object removeListener(Object bag, Object listener) { if (listener == null) throw new IllegalArgumentException(); if (listener instanceof Object[]) throw new IllegalArgumentException(); if (bag == listener) { bag = null; } else if (bag instanceof Object[]) { Object[] array = (Object[])bag; int L = array.length; // bag has at least 2 elements if it is array if (L < 2) throw new IllegalArgumentException(); if (L == 2) { if (array[1] == listener) { bag = array[0]; } else if (array[0] == listener) { bag = array[1]; } } else { int i = L; do { --i; if (array[i] == listener) { Object[] tmp = new Object[L - 1]; System.arraycopy(array, 0, tmp, 0, i); System.arraycopy(array, i + 1, tmp, i, L - (i + 1)); bag = tmp; break; } } while (i != 0); } } return bag; } /** * Get listener at index position in bag or null if * index equals to number of listeners in bag. *

* For usage example, see {@link #addListener(Object bag, Object listener)}. * * @param bag Current collection of listeners. * @param index Index of the listener to access. * @return Listener at the given index or null. * @see #addListener(Object bag, Object listener) * @see #removeListener(Object bag, Object listener) */ public static Object getListener(Object bag, int index) { if (index == 0) { if (bag == null) return null; if (!(bag instanceof Object[])) return bag; Object[] array = (Object[])bag; // bag has at least 2 elements if it is array if (array.length < 2) throw new IllegalArgumentException(); return array[0]; } else if (index == 1) { if (!(bag instanceof Object[])) { if (bag == null) throw new IllegalArgumentException(); return null; } Object[] array = (Object[])bag; // the array access will check for index on its own return array[1]; } else { // bag has to array Object[] array = (Object[])bag; int L = array.length; if (L < 2) throw new IllegalArgumentException(); if (index == L) return null; return array[index]; } } static Object initHash(Map h, Object key, Object initialValue) { synchronized (h) { Object current = h.get(key); if (current == null) { h.put(key, initialValue); } else { initialValue = current; } } return initialValue; } private final static class ComplexKey { private Object key1; private Object key2; private int hash; ComplexKey(Object key1, Object key2) { this.key1 = key1; this.key2 = key2; } @Override public boolean equals(Object anotherObj) { if (!(anotherObj instanceof ComplexKey)) return false; ComplexKey another = (ComplexKey)anotherObj; return key1.equals(another.key1) && key2.equals(another.key2); } @Override public int hashCode() { if (hash == 0) { hash = key1.hashCode() ^ key2.hashCode(); } return hash; } } public static Object makeHashKeyFromPair(Object key1, Object key2) { if (key1 == null) throw new IllegalArgumentException(); if (key2 == null) throw new IllegalArgumentException(); return new ComplexKey(key1, key2); } public static String readReader(Reader r) throws IOException { char[] buffer = new char[512]; int cursor = 0; for (;;) { int n = r.read(buffer, cursor, buffer.length - cursor); if (n < 0) { break; } cursor += n; if (cursor == buffer.length) { char[] tmp = new char[buffer.length * 2]; System.arraycopy(buffer, 0, tmp, 0, cursor); buffer = tmp; } } return new String(buffer, 0, cursor); } public static byte[] readStream(InputStream is, int initialBufferCapacity) throws IOException { if (initialBufferCapacity <= 0) { throw new IllegalArgumentException( "Bad initialBufferCapacity: "+initialBufferCapacity); } byte[] buffer = new byte[initialBufferCapacity]; int cursor = 0; for (;;) { int n = is.read(buffer, cursor, buffer.length - cursor); if (n < 0) { break; } cursor += n; if (cursor == buffer.length) { byte[] tmp = new byte[buffer.length * 2]; System.arraycopy(buffer, 0, tmp, 0, cursor); buffer = tmp; } } if (cursor != buffer.length) { byte[] tmp = new byte[cursor]; System.arraycopy(buffer, 0, tmp, 0, cursor); buffer = tmp; } return buffer; } /** * Throws RuntimeException to indicate failed assertion. * The function never returns and its return type is RuntimeException * only to be able to write throw Kit.codeBug() if plain * Kit.codeBug() triggers unreachable code error. */ public static RuntimeException codeBug() throws RuntimeException { RuntimeException ex = new IllegalStateException("FAILED ASSERTION"); // Print stack trace ASAP ex.printStackTrace(System.err); throw ex; } /** * Throws RuntimeException to indicate failed assertion. * The function never returns and its return type is RuntimeException * only to be able to write throw Kit.codeBug() if plain * Kit.codeBug() triggers unreachable code error. */ public static RuntimeException codeBug(String msg) throws RuntimeException { msg = "FAILED ASSERTION: " + msg; RuntimeException ex = new IllegalStateException(msg); // Print stack trace ASAP ex.printStackTrace(System.err); throw ex; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/RefCallable.java0000644000175000017500000000451711314263504033111 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov, igor@mir2.org * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; /** * Object that can allows assignments to the result of function calls. */ public interface RefCallable extends Callable { /** * Perform function call in reference context. * The args array reference should not be stored in any object that is * can be GC-reachable after this method returns. If this is necessary, * for example, to implement {@link Ref} methods, then store args.clone(), * not args array itself. * * @param cx the current Context for this thread * @param thisObj the JavaScript this object * @param args the array of arguments */ public Ref refCall(Context cx, Scriptable thisObj, Object[] args); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/UniqueTag.java0000644000175000017500000000732611314263504032660 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.io.Serializable; /** * Class instances represent serializable tags to mark special Object values. *

* Compatibility note: under jdk 1.1 use * org.mozilla.javascript.serialize.ScriptableInputStream to read serialized * instances of UniqueTag as under this JDK version the default * ObjectInputStream would not restore them correctly as it lacks support * for readResolve method */ public final class UniqueTag implements Serializable { static final long serialVersionUID = -4320556826714577259L; private static final int ID_NOT_FOUND = 1; private static final int ID_NULL_VALUE = 2; private static final int ID_DOUBLE_MARK = 3; /** * Tag to mark non-existing values. */ public static final UniqueTag NOT_FOUND = new UniqueTag(ID_NOT_FOUND); /** * Tag to distinguish between uninitialized and null values. */ public static final UniqueTag NULL_VALUE = new UniqueTag(ID_NULL_VALUE); /** * Tag to indicate that a object represents "double" with the real value * stored somewhere else. */ public static final UniqueTag DOUBLE_MARK = new UniqueTag(ID_DOUBLE_MARK); private final int tagId; private UniqueTag(int tagId) { this.tagId = tagId; } public Object readResolve() { switch (tagId) { case ID_NOT_FOUND: return NOT_FOUND; case ID_NULL_VALUE: return NULL_VALUE; case ID_DOUBLE_MARK: return DOUBLE_MARK; } throw new IllegalStateException(String.valueOf(tagId)); } // Overridden for better debug printouts @Override public String toString() { String name; switch (tagId) { case ID_NOT_FOUND: name = "NOT_FOUND"; break; case ID_NULL_VALUE: name = "NULL_VALUE"; break; case ID_DOUBLE_MARK: name = "DOUBLE_MARK"; break; default: throw Kit.codeBug(); } return super.toString()+": "+name; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/NativeArray.java0000644000175000017500000017213311314263504033202 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Mike McCabe * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.Set; /** * This class implements the Array native object. * @author Norris Boyd * @author Mike McCabe */ public class NativeArray extends IdScriptableObject { static final long serialVersionUID = 7331366857676127338L; /* * Optimization possibilities and open issues: * - Long vs. double schizophrenia. I suspect it might be better * to use double throughout. * * - Functions that need a new Array call "new Array" in the * current scope rather than using a hardwired constructor; * "Array" could be redefined. It turns out that js calls the * equivalent of "new Array" in the current scope, except that it * always gets at least an object back, even when Array == null. */ private static final Object ARRAY_TAG = "Array"; private static final Integer NEGATIVE_ONE = Integer.valueOf(-1); static void init(Scriptable scope, boolean sealed) { NativeArray obj = new NativeArray(0); obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed); } static int getMaximumInitialCapacity() { return maximumInitialCapacity; } static void setMaximumInitialCapacity(int maximumInitialCapacity) { NativeArray.maximumInitialCapacity = maximumInitialCapacity; } public NativeArray(long lengthArg) { denseOnly = lengthArg <= maximumInitialCapacity; if (denseOnly) { int intLength = (int) lengthArg; if (intLength < DEFAULT_INITIAL_CAPACITY) intLength = DEFAULT_INITIAL_CAPACITY; dense = new Object[intLength]; Arrays.fill(dense, Scriptable.NOT_FOUND); } length = lengthArg; } public NativeArray(Object[] array) { denseOnly = true; dense = array; length = array.length; } @Override public String getClassName() { return "Array"; } private static final int Id_length = 1, MAX_INSTANCE_ID = 1; @Override protected int getMaxInstanceId() { return MAX_INSTANCE_ID; } @Override protected int findInstanceIdInfo(String s) { if (s.equals("length")) { return instanceIdInfo(DONTENUM | PERMANENT, Id_length); } return super.findInstanceIdInfo(s); } @Override protected String getInstanceIdName(int id) { if (id == Id_length) { return "length"; } return super.getInstanceIdName(id); } @Override protected Object getInstanceIdValue(int id) { if (id == Id_length) { return ScriptRuntime.wrapNumber(length); } return super.getInstanceIdValue(id); } @Override protected void setInstanceIdValue(int id, Object value) { if (id == Id_length) { setLength(value); return; } super.setInstanceIdValue(id, value); } @Override protected void fillConstructorProperties(IdFunctionObject ctor) { addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_join, "join", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reverse, "reverse", 1); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_sort, "sort", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_push, "push", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_pop, "pop", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_shift, "shift", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_unshift, "unshift", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_splice, "splice", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_concat, "concat", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_slice, "slice", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_indexOf, "indexOf", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_lastIndexOf, "lastIndexOf", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_every, "every", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_filter, "filter", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_forEach, "forEach", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_map, "map", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_some, "some", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reduce, "reduce", 2); addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reduceRight, "reduceRight", 2); super.fillConstructorProperties(ctor); } @Override protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_constructor: arity=1; s="constructor"; break; case Id_toString: arity=0; s="toString"; break; case Id_toLocaleString: arity=1; s="toLocaleString"; break; case Id_toSource: arity=0; s="toSource"; break; case Id_join: arity=1; s="join"; break; case Id_reverse: arity=0; s="reverse"; break; case Id_sort: arity=1; s="sort"; break; case Id_push: arity=1; s="push"; break; case Id_pop: arity=1; s="pop"; break; case Id_shift: arity=1; s="shift"; break; case Id_unshift: arity=1; s="unshift"; break; case Id_splice: arity=1; s="splice"; break; case Id_concat: arity=1; s="concat"; break; case Id_slice: arity=1; s="slice"; break; case Id_indexOf: arity=1; s="indexOf"; break; case Id_lastIndexOf: arity=1; s="lastIndexOf"; break; case Id_every: arity=1; s="every"; break; case Id_filter: arity=1; s="filter"; break; case Id_forEach: arity=1; s="forEach"; break; case Id_map: arity=1; s="map"; break; case Id_some: arity=1; s="some"; break; case Id_reduce: arity=1; s="reduce"; break; case Id_reduceRight: arity=1; s="reduceRight"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(ARRAY_TAG, id, s, arity); } @Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(ARRAY_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); again: for (;;) { switch (id) { case ConstructorId_join: case ConstructorId_reverse: case ConstructorId_sort: case ConstructorId_push: case ConstructorId_pop: case ConstructorId_shift: case ConstructorId_unshift: case ConstructorId_splice: case ConstructorId_concat: case ConstructorId_slice: case ConstructorId_indexOf: case ConstructorId_lastIndexOf: case ConstructorId_every: case ConstructorId_filter: case ConstructorId_forEach: case ConstructorId_map: case ConstructorId_some: case ConstructorId_reduce: case ConstructorId_reduceRight: { if (args.length > 0) { thisObj = ScriptRuntime.toObject(scope, args[0]); Object[] newArgs = new Object[args.length-1]; for (int i=0; i < newArgs.length; i++) newArgs[i] = args[i+1]; args = newArgs; } id = -id; continue again; } case Id_constructor: { boolean inNewExpr = (thisObj == null); if (!inNewExpr) { // IdFunctionObject.construct will set up parent, proto return f.construct(cx, scope, args); } return jsConstructor(cx, scope, args); } case Id_toString: return toStringHelper(cx, scope, thisObj, cx.hasFeature(Context.FEATURE_TO_STRING_AS_SOURCE), false); case Id_toLocaleString: return toStringHelper(cx, scope, thisObj, false, true); case Id_toSource: return toStringHelper(cx, scope, thisObj, true, false); case Id_join: return js_join(cx, thisObj, args); case Id_reverse: return js_reverse(cx, thisObj, args); case Id_sort: return js_sort(cx, scope, thisObj, args); case Id_push: return js_push(cx, thisObj, args); case Id_pop: return js_pop(cx, thisObj, args); case Id_shift: return js_shift(cx, thisObj, args); case Id_unshift: return js_unshift(cx, thisObj, args); case Id_splice: return js_splice(cx, scope, thisObj, args); case Id_concat: return js_concat(cx, scope, thisObj, args); case Id_slice: return js_slice(cx, thisObj, args); case Id_indexOf: return indexOfHelper(cx, thisObj, args, false); case Id_lastIndexOf: return indexOfHelper(cx, thisObj, args, true); case Id_every: case Id_filter: case Id_forEach: case Id_map: case Id_some: return iterativeMethod(cx, id, scope, thisObj, args); case Id_reduce: case Id_reduceRight: return reduceMethod(cx, id, scope, thisObj, args); } throw new IllegalArgumentException(String.valueOf(id)); } } @Override public Object get(int index, Scriptable start) { if (!denseOnly && isGetterOrSetter(null, index, false)) return super.get(index, start); if (dense != null && 0 <= index && index < dense.length) return dense[index]; return super.get(index, start); } @Override public boolean has(int index, Scriptable start) { if (!denseOnly && isGetterOrSetter(null, index, false)) return super.has(index, start); if (dense != null && 0 <= index && index < dense.length) return dense[index] != NOT_FOUND; return super.has(index, start); } // if id is an array index (ECMA 15.4.0), return the number, // otherwise return -1L private static long toArrayIndex(String id) { double d = ScriptRuntime.toNumber(id); if (d == d) { long index = ScriptRuntime.toUint32(d); if (index == d && index != 4294967295L) { // Assume that ScriptRuntime.toString(index) is the same // as java.lang.Long.toString(index) for long if (Long.toString(index).equals(id)) { return index; } } } return -1; } @Override public void put(String id, Scriptable start, Object value) { super.put(id, start, value); if (start == this) { // If the object is sealed, super will throw exception long index = toArrayIndex(id); if (index >= length) { length = index + 1; denseOnly = false; } } } private boolean ensureCapacity(int capacity) { if (capacity > dense.length) { if (capacity > MAX_PRE_GROW_SIZE) { denseOnly = false; return false; } capacity = Math.max(capacity, (int)(dense.length * GROW_FACTOR)); Object[] newDense = new Object[capacity]; System.arraycopy(dense, 0, newDense, 0, dense.length); Arrays.fill(newDense, dense.length, newDense.length, Scriptable.NOT_FOUND); dense = newDense; } return true; } @Override public void put(int index, Scriptable start, Object value) { if (start == this && !isSealed() && dense != null && 0 <= index && (denseOnly || !isGetterOrSetter(null, index, true))) { if (index < dense.length) { dense[index] = value; if (this.length <= index) this.length = (long)index + 1; return; } else if (denseOnly && index < dense.length * GROW_FACTOR && ensureCapacity(index+1)) { dense[index] = value; this.length = (long)index + 1; return; } else { denseOnly = false; } } super.put(index, start, value); if (start == this) { // only set the array length if given an array index (ECMA 15.4.0) if (this.length <= index) { // avoid overflowing index! this.length = (long)index + 1; } } } @Override public void delete(int index) { if (dense != null && 0 <= index && index < dense.length && !isSealed() && (denseOnly || !isGetterOrSetter(null, index, true))) { dense[index] = NOT_FOUND; } else { super.delete(index); } } @Override public Object[] getIds() { Object[] superIds = super.getIds(); if (dense == null) { return superIds; } int N = dense.length; long currentLength = length; if (N > currentLength) { N = (int)currentLength; } if (N == 0) { return superIds; } int superLength = superIds.length; Object[] ids = new Object[N + superLength]; int presentCount = 0; for (int i = 0; i != N; ++i) { // Replace existing elements by their indexes if (dense[i] != NOT_FOUND) { ids[presentCount] = Integer.valueOf(i); ++presentCount; } } if (presentCount != N) { // dense contains deleted elems, need to shrink the result Object[] tmp = new Object[presentCount + superLength]; System.arraycopy(ids, 0, tmp, 0, presentCount); ids = tmp; } System.arraycopy(superIds, 0, ids, presentCount, superLength); return ids; } @Override public Object[] getAllIds() { Set allIds = new LinkedHashSet( Arrays.asList(this.getIds())); allIds.addAll(Arrays.asList(super.getAllIds())); return allIds.toArray(); } @Override public Object getDefaultValue(Class hint) { if (hint == ScriptRuntime.NumberClass) { Context cx = Context.getContext(); if (cx.getLanguageVersion() == Context.VERSION_1_2) return Long.valueOf(length); } return super.getDefaultValue(hint); } /** * See ECMA 15.4.1,2 */ private static Object jsConstructor(Context cx, Scriptable scope, Object[] args) { if (args.length == 0) return new NativeArray(0); // Only use 1 arg as first element for version 1.2; for // any other version (including 1.3) follow ECMA and use it as // a length. if (cx.getLanguageVersion() == Context.VERSION_1_2) { return new NativeArray(args); } else { Object arg0 = args[0]; if (args.length > 1 || !(arg0 instanceof Number)) { return new NativeArray(args); } else { long len = ScriptRuntime.toUint32(arg0); if (len != ((Number)arg0).doubleValue()) throw Context.reportRuntimeError0("msg.arraylength.bad"); return new NativeArray(len); } } } public long getLength() { return length; } /** @deprecated Use {@link #getLength()} instead. */ public long jsGet_length() { return getLength(); } /** * Change the value of the internal flag that determines whether all * storage is handed by a dense backing array rather than an associative * store. * @param denseOnly new value for denseOnly flag * @throws IllegalArgumentException if an attempt is made to enable * denseOnly after it was disabled; NativeArray code is not written * to handle switching back to a dense representation */ void setDenseOnly(boolean denseOnly) { if (denseOnly && !this.denseOnly) throw new IllegalArgumentException(); this.denseOnly = denseOnly; } private void setLength(Object val) { /* XXX do we satisfy this? * 15.4.5.1 [[Put]](P, V): * 1. Call the [[CanPut]] method of A with name P. * 2. If Result(1) is false, return. * ? */ double d = ScriptRuntime.toNumber(val); long longVal = ScriptRuntime.toUint32(d); if (longVal != d) throw Context.reportRuntimeError0("msg.arraylength.bad"); if (denseOnly) { if (longVal < length) { // downcast okay because denseOnly Arrays.fill(dense, (int) longVal, dense.length, NOT_FOUND); length = longVal; return; } else if (longVal < MAX_PRE_GROW_SIZE && longVal < (length * GROW_FACTOR) && ensureCapacity((int)longVal)) { length = longVal; return; } else { denseOnly = false; } } if (longVal < length) { // remove all properties between longVal and length if (length - longVal > 0x1000) { // assume that the representation is sparse Object[] e = getIds(); // will only find in object itself for (int i=0; i < e.length; i++) { Object id = e[i]; if (id instanceof String) { // > MAXINT will appear as string String strId = (String)id; long index = toArrayIndex(strId); if (index >= longVal) delete(strId); } else { int index = ((Integer)id).intValue(); if (index >= longVal) delete(index); } } } else { // assume a dense representation for (long i = longVal; i < length; i++) { deleteElem(this, i); } } } length = longVal; } /* Support for generic Array-ish objects. Most of the Array * functions try to be generic; anything that has a length * property is assumed to be an array. * getLengthProperty returns 0 if obj does not have the length property * or its value is not convertible to a number. */ static long getLengthProperty(Context cx, Scriptable obj) { // These will both give numeric lengths within Uint32 range. if (obj instanceof NativeString) { return ((NativeString)obj).getLength(); } else if (obj instanceof NativeArray) { return ((NativeArray)obj).getLength(); } return ScriptRuntime.toUint32( ScriptRuntime.getObjectProp(obj, "length", cx)); } private static Object setLengthProperty(Context cx, Scriptable target, long length) { return ScriptRuntime.setObjectProp( target, "length", ScriptRuntime.wrapNumber(length), cx); } /* Utility functions to encapsulate index > Integer.MAX_VALUE * handling. Also avoids unnecessary object creation that would * be necessary to use the general ScriptRuntime.get/setElem * functions... though this is probably premature optimization. */ private static void deleteElem(Scriptable target, long index) { int i = (int)index; if (i == index) { target.delete(i); } else { target.delete(Long.toString(index)); } } private static Object getElem(Context cx, Scriptable target, long index) { if (index > Integer.MAX_VALUE) { String id = Long.toString(index); return ScriptRuntime.getObjectProp(target, id, cx); } else { return ScriptRuntime.getObjectIndex(target, (int)index, cx); } } // same as getElem, but without converting NOT_FOUND to undefined private static Object getRawElem(Scriptable target, long index) { if (index > Integer.MAX_VALUE) { return ScriptableObject.getProperty(target, Long.toString(index)); } else { return ScriptableObject.getProperty(target, (int) index); } } private static void setElem(Context cx, Scriptable target, long index, Object value) { if (index > Integer.MAX_VALUE) { String id = Long.toString(index); ScriptRuntime.setObjectProp(target, id, value, cx); } else { ScriptRuntime.setObjectIndex(target, (int)index, value, cx); } } private static String toStringHelper(Context cx, Scriptable scope, Scriptable thisObj, boolean toSource, boolean toLocale) { /* It's probably redundant to handle long lengths in this * function; StringBuilders are limited to 2^31 in java. */ long length = getLengthProperty(cx, thisObj); StringBuilder result = new StringBuilder(256); // whether to return '4,unquoted,5' or '[4, "quoted", 5]' String separator; if (toSource) { result.append('['); separator = ", "; } else { separator = ","; } boolean haslast = false; long i = 0; boolean toplevel, iterating; if (cx.iterating == null) { toplevel = true; iterating = false; cx.iterating = new ObjToIntMap(31); } else { toplevel = false; iterating = cx.iterating.has(thisObj); } // Make sure cx.iterating is set to null when done // so we don't leak memory try { if (!iterating) { cx.iterating.put(thisObj, 0); // stop recursion. for (i = 0; i < length; i++) { if (i > 0) result.append(separator); Object elem = getElem(cx, thisObj, i); if (elem == null || elem == Undefined.instance) { haslast = false; continue; } haslast = true; if (toSource) { result.append(ScriptRuntime.uneval(cx, scope, elem)); } else if (elem instanceof String) { String s = (String)elem; if (toSource) { result.append('\"'); result.append(ScriptRuntime.escapeString(s)); result.append('\"'); } else { result.append(s); } } else { if (toLocale) { Callable fun; Scriptable funThis; fun = ScriptRuntime.getPropFunctionAndThis( elem, "toLocaleString", cx); funThis = ScriptRuntime.lastStoredScriptable(cx); elem = fun.call(cx, scope, funThis, ScriptRuntime.emptyArgs); } result.append(ScriptRuntime.toString(elem)); } } } } finally { if (toplevel) { cx.iterating = null; } } if (toSource) { //for [,,].length behavior; we want toString to be symmetric. if (!haslast && i > 0) result.append(", ]"); else result.append(']'); } return result.toString(); } /** * See ECMA 15.4.4.3 */ private static String js_join(Context cx, Scriptable thisObj, Object[] args) { long llength = getLengthProperty(cx, thisObj); int length = (int)llength; if (llength != length) { throw Context.reportRuntimeError1( "msg.arraylength.too.big", String.valueOf(llength)); } // if no args, use "," as separator String separator = (args.length < 1 || args[0] == Undefined.instance) ? "," : ScriptRuntime.toString(args[0]); if (thisObj instanceof NativeArray) { NativeArray na = (NativeArray) thisObj; if (na.denseOnly) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i != 0) { sb.append(separator); } if (i < na.dense.length) { Object temp = na.dense[i]; if (temp != null && temp != Undefined.instance && temp != Scriptable.NOT_FOUND) { sb.append(ScriptRuntime.toString(temp)); } } } return sb.toString(); } } if (length == 0) { return ""; } String[] buf = new String[length]; int total_size = 0; for (int i = 0; i != length; i++) { Object temp = getElem(cx, thisObj, i); if (temp != null && temp != Undefined.instance) { String str = ScriptRuntime.toString(temp); total_size += str.length(); buf[i] = str; } } total_size += (length - 1) * separator.length(); StringBuilder sb = new StringBuilder(total_size); for (int i = 0; i != length; i++) { if (i != 0) { sb.append(separator); } String str = buf[i]; if (str != null) { // str == null for undefined or null sb.append(str); } } return sb.toString(); } /** * See ECMA 15.4.4.4 */ private static Scriptable js_reverse(Context cx, Scriptable thisObj, Object[] args) { if (thisObj instanceof NativeArray) { NativeArray na = (NativeArray) thisObj; if (na.denseOnly) { for (int i=0, j=((int)na.length)-1; i < j; i++,j--) { Object temp = na.dense[i]; na.dense[i] = na.dense[j]; na.dense[j] = temp; } return thisObj; } } long len = getLengthProperty(cx, thisObj); long half = len / 2; for(long i=0; i < half; i++) { long j = len - i - 1; Object temp1 = getElem(cx, thisObj, i); Object temp2 = getElem(cx, thisObj, j); setElem(cx, thisObj, i, temp2); setElem(cx, thisObj, j, temp1); } return thisObj; } /** * See ECMA 15.4.4.5 */ private static Scriptable js_sort(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args) { final Comparator comparator; if (args.length > 0 && Undefined.instance != args[0]) { final Callable jsCompareFunction = ScriptRuntime .getValueFunctionAndThis(args[0], cx); final Scriptable funThis = ScriptRuntime.lastStoredScriptable(cx); final Object[] cmpBuf = new Object[2]; // Buffer for cmp arguments comparator = new Comparator() { public int compare(final Object x, final Object y) { // sort undefined to end if (x == y) { return 0; } else if (y == Undefined.instance || y == Scriptable.NOT_FOUND) { return -1; } else if (x == Undefined.instance || x == Scriptable.NOT_FOUND) { return 1; } cmpBuf[0] = x; cmpBuf[1] = y; Object ret = jsCompareFunction.call(cx, scope, funThis, cmpBuf); final double d = ScriptRuntime.toNumber(ret); if (d < 0) { return -1; } else if (d > 0) { return +1; } return 0; // ??? double and 0??? } }; } else { comparator = new Comparator() { public int compare(final Object x, final Object y) { // sort undefined to end if (x == y) return 0; else if (y == Undefined.instance || y == Scriptable.NOT_FOUND) { return -1; } else if (x == Undefined.instance || x == Scriptable.NOT_FOUND) { return 1; } final String a = ScriptRuntime.toString(x); final String b = ScriptRuntime.toString(y); return a.compareTo(b); } }; } final int length = (int) getLengthProperty(cx, thisObj); // copy the JS array into a working array, so it can be // sorted cheaply. final Object[] working = new Object[length]; for (int i = 0; i != length; ++i) { working[i] = getElem(cx, thisObj, i); } Arrays.sort(working, comparator); // copy the working array back into thisObj for (int i = 0; i < length; ++i) { setElem(cx, thisObj, i, working[i]); } return thisObj; } /** * Non-ECMA methods. */ private static Object js_push(Context cx, Scriptable thisObj, Object[] args) { if (thisObj instanceof NativeArray) { NativeArray na = (NativeArray) thisObj; if (na.denseOnly && na.ensureCapacity((int) na.length + args.length)) { for (int i = 0; i < args.length; i++) { na.dense[(int)na.length++] = args[i]; } return ScriptRuntime.wrapNumber(na.length); } } long length = getLengthProperty(cx, thisObj); for (int i = 0; i < args.length; i++) { setElem(cx, thisObj, length + i, args[i]); } length += args.length; Object lengthObj = setLengthProperty(cx, thisObj, length); /* * If JS1.2, follow Perl4 by returning the last thing pushed. * Otherwise, return the new array length. */ if (cx.getLanguageVersion() == Context.VERSION_1_2) // if JS1.2 && no arguments, return undefined. return args.length == 0 ? Undefined.instance : args[args.length - 1]; else return lengthObj; } private static Object js_pop(Context cx, Scriptable thisObj, Object[] args) { Object result; if (thisObj instanceof NativeArray) { NativeArray na = (NativeArray) thisObj; if (na.denseOnly && na.length > 0) { na.length--; result = na.dense[(int)na.length]; na.dense[(int)na.length] = NOT_FOUND; return result; } } long length = getLengthProperty(cx, thisObj); if (length > 0) { length--; // Get the to-be-deleted property's value. result = getElem(cx, thisObj, length); // We don't need to delete the last property, because // setLength does that for us. } else { result = Undefined.instance; } // necessary to match js even when length < 0; js pop will give a // length property to any target it is called on. setLengthProperty(cx, thisObj, length); return result; } private static Object js_shift(Context cx, Scriptable thisObj, Object[] args) { if (thisObj instanceof NativeArray) { NativeArray na = (NativeArray) thisObj; if (na.denseOnly && na.length > 0) { na.length--; Object result = na.dense[0]; System.arraycopy(na.dense, 1, na.dense, 0, (int)na.length); na.dense[(int)na.length] = NOT_FOUND; return result; } } Object result; long length = getLengthProperty(cx, thisObj); if (length > 0) { long i = 0; length--; // Get the to-be-deleted property's value. result = getElem(cx, thisObj, i); /* * Slide down the array above the first element. Leave i * set to point to the last element. */ if (length > 0) { for (i = 1; i <= length; i++) { Object temp = getElem(cx, thisObj, i); setElem(cx, thisObj, i - 1, temp); } } // We don't need to delete the last property, because // setLength does that for us. } else { result = Undefined.instance; } setLengthProperty(cx, thisObj, length); return result; } private static Object js_unshift(Context cx, Scriptable thisObj, Object[] args) { if (thisObj instanceof NativeArray) { NativeArray na = (NativeArray) thisObj; if (na.denseOnly && na.ensureCapacity((int)na.length + args.length)) { System.arraycopy(na.dense, 0, na.dense, args.length, (int) na.length); for (int i = 0; i < args.length; i++) { na.dense[i] = args[i]; } na.length += args.length; return ScriptRuntime.wrapNumber(na.length); } } long length = getLengthProperty(cx, thisObj); int argc = args.length; if (args.length > 0) { /* Slide up the array to make room for args at the bottom */ if (length > 0) { for (long last = length - 1; last >= 0; last--) { Object temp = getElem(cx, thisObj, last); setElem(cx, thisObj, last + argc, temp); } } /* Copy from argv to the bottom of the array. */ for (int i = 0; i < args.length; i++) { setElem(cx, thisObj, i, args[i]); } /* Follow Perl by returning the new array length. */ length += args.length; return setLengthProperty(cx, thisObj, length); } return ScriptRuntime.wrapNumber(length); } private static Object js_splice(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { NativeArray na = null; boolean denseMode = false; if (thisObj instanceof NativeArray) { na = (NativeArray) thisObj; denseMode = na.denseOnly; } /* create an empty Array to return. */ scope = getTopLevelScope(scope); int argc = args.length; if (argc == 0) return ScriptRuntime.newObject(cx, scope, "Array", null); long length = getLengthProperty(cx, thisObj); /* Convert the first argument into a starting index. */ long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length); argc--; /* Convert the second argument into count */ long count; if (args.length == 1) { count = length - begin; } else { double dcount = ScriptRuntime.toInteger(args[1]); if (dcount < 0) { count = 0; } else if (dcount > (length - begin)) { count = length - begin; } else { count = (long)dcount; } argc--; } long end = begin + count; /* If there are elements to remove, put them into the return value. */ Object result; if (count != 0) { if (count == 1 && (cx.getLanguageVersion() == Context.VERSION_1_2)) { /* * JS lacks "list context", whereby in Perl one turns the * single scalar that's spliced out into an array just by * assigning it to @single instead of $single, or by using it * as Perl push's first argument, for instance. * * JS1.2 emulated Perl too closely and returned a non-Array for * the single-splice-out case, requiring callers to test and * wrap in [] if necessary. So JS1.3, default, and other * versions all return an array of length 1 for uniformity. */ result = getElem(cx, thisObj, begin); } else { if (denseMode) { int intLen = (int) (end - begin); Object[] copy = new Object[intLen]; System.arraycopy(na.dense, (int) begin, copy, 0, intLen); result = cx.newArray(scope, copy); } else { Scriptable resultArray = ScriptRuntime.newObject(cx, scope, "Array", null); for (long last = begin; last != end; last++) { Object temp = getElem(cx, thisObj, last); setElem(cx, resultArray, last - begin, temp); } result = resultArray; } } } else { // (count == 0) if (cx.getLanguageVersion() == Context.VERSION_1_2) { /* Emulate C JS1.2; if no elements are removed, return undefined. */ result = Undefined.instance; } else { result = ScriptRuntime.newObject(cx, scope, "Array", null); } } /* Find the direction (up or down) to copy and make way for argv. */ long delta = argc - count; if (denseMode && length + delta < Integer.MAX_VALUE && na.ensureCapacity((int) (length + delta))) { System.arraycopy(na.dense, (int) end, na.dense, (int) (begin + argc), (int) (length - end)); if (argc > 0) { System.arraycopy(args, 2, na.dense, (int) begin, argc); } if (delta < 0) { Arrays.fill(na.dense, (int) (length + delta), (int) length, NOT_FOUND); } na.length = length + delta; return result; } if (delta > 0) { for (long last = length - 1; last >= end; last--) { Object temp = getElem(cx, thisObj, last); setElem(cx, thisObj, last + delta, temp); } } else if (delta < 0) { for (long last = end; last < length; last++) { Object temp = getElem(cx, thisObj, last); setElem(cx, thisObj, last + delta, temp); } } /* Copy from argv into the hole to complete the splice. */ int argoffset = args.length - argc; for (int i = 0; i < argc; i++) { setElem(cx, thisObj, begin + i, args[i + argoffset]); } /* Update length in case we deleted elements from the end. */ setLengthProperty(cx, thisObj, length + delta); return result; } /* * See Ecma 262v3 15.4.4.4 */ private static Scriptable js_concat(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { // create an empty Array to return. scope = getTopLevelScope(scope); Function ctor = ScriptRuntime.getExistingCtor(cx, scope, "Array"); Scriptable result = ctor.construct(cx, scope, ScriptRuntime.emptyArgs); if (thisObj instanceof NativeArray && result instanceof NativeArray) { NativeArray denseThis = (NativeArray) thisObj; NativeArray denseResult = (NativeArray) result; if (denseThis.denseOnly && denseResult.denseOnly) { // First calculate length of resulting array boolean canUseDense = true; int length = (int) denseThis.length; for (int i = 0; i < args.length && canUseDense; i++) { if (args[i] instanceof NativeArray) { // only try to use dense approach for Array-like // objects that are actually NativeArrays final NativeArray arg = (NativeArray) args[i]; canUseDense = arg.denseOnly; length += arg.length; } else { length++; } } if (canUseDense && denseResult.ensureCapacity(length)) { System.arraycopy(denseThis.dense, 0, denseResult.dense, 0, (int) denseThis.length); int cursor = (int) denseThis.length; for (int i = 0; i < args.length && canUseDense; i++) { if (args[i] instanceof NativeArray) { NativeArray arg = (NativeArray) args[i]; System.arraycopy(arg.dense, 0, denseResult.dense, cursor, (int)arg.length); cursor += (int)arg.length; } else { denseResult.dense[cursor++] = args[i]; } } denseResult.length = length; return result; } } } long length; long slot = 0; /* Put the target in the result array; only add it as an array * if it looks like one. */ if (ScriptRuntime.instanceOf(thisObj, ctor, cx)) { length = getLengthProperty(cx, thisObj); // Copy from the target object into the result for (slot = 0; slot < length; slot++) { Object temp = getElem(cx, thisObj, slot); setElem(cx, result, slot, temp); } } else { setElem(cx, result, slot++, thisObj); } /* Copy from the arguments into the result. If any argument * has a numeric length property, treat it as an array and add * elements separately; otherwise, just copy the argument. */ for (int i = 0; i < args.length; i++) { if (ScriptRuntime.instanceOf(args[i], ctor, cx)) { // ScriptRuntime.instanceOf => instanceof Scriptable Scriptable arg = (Scriptable)args[i]; length = getLengthProperty(cx, arg); for (long j = 0; j < length; j++, slot++) { Object temp = getElem(cx, arg, j); setElem(cx, result, slot, temp); } } else { setElem(cx, result, slot++, args[i]); } } return result; } private Scriptable js_slice(Context cx, Scriptable thisObj, Object[] args) { Scriptable scope = getTopLevelScope(this); Scriptable result = ScriptRuntime.newObject(cx, scope, "Array", null); long length = getLengthProperty(cx, thisObj); long begin, end; if (args.length == 0) { begin = 0; end = length; } else { begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length); if (args.length == 1) { end = length; } else { end = toSliceIndex(ScriptRuntime.toInteger(args[1]), length); } } for (long slot = begin; slot < end; slot++) { Object temp = getElem(cx, thisObj, slot); setElem(cx, result, slot - begin, temp); } return result; } private static long toSliceIndex(double value, long length) { long result; if (value < 0.0) { if (value + length < 0.0) { result = 0; } else { result = (long)(value + length); } } else if (value > length) { result = length; } else { result = (long)value; } return result; } /** * Implements the methods "indexOf" and "lastIndexOf". */ private Object indexOfHelper(Context cx, Scriptable thisObj, Object[] args, boolean isLast) { Object compareTo = args.length > 0 ? args[0] : Undefined.instance; long length = getLengthProperty(cx, thisObj); long start; if (isLast) { // lastIndexOf /* * From http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:lastIndexOf * The index at which to start searching backwards. Defaults to the * array's length, i.e. the whole array will be searched. If the * index is greater than or equal to the length of the array, the * whole array will be searched. If negative, it is taken as the * offset from the end of the array. Note that even when the index * is negative, the array is still searched from back to front. If * the calculated index is less than 0, -1 is returned, i.e. the * array will not be searched. */ if (args.length < 2) { // default start = length-1; } else { start = ScriptRuntime.toInt32(ScriptRuntime.toNumber(args[1])); if (start >= length) start = length-1; else if (start < 0) start += length; // Note that start may be negative, but that's okay // as the result of -1 will fall out from the code below } } else { // indexOf /* * From http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:indexOf * The index at which to begin the search. Defaults to 0, i.e. the * whole array will be searched. If the index is greater than or * equal to the length of the array, -1 is returned, i.e. the array * will not be searched. If negative, it is taken as the offset from * the end of the array. Note that even when the index is negative, * the array is still searched from front to back. If the calculated * index is less than 0, the whole array will be searched. */ if (args.length < 2) { // default start = 0; } else { start = ScriptRuntime.toInt32(ScriptRuntime.toNumber(args[1])); if (start < 0) { start += length; if (start < 0) start = 0; } // Note that start may be > length-1, but that's okay // as the result of -1 will fall out from the code below } } if (thisObj instanceof NativeArray) { NativeArray na = (NativeArray) thisObj; if (na.denseOnly) { if (isLast) { for (int i=(int)start; i >= 0; i--) { if (na.dense[i] != Scriptable.NOT_FOUND && ScriptRuntime.shallowEq(na.dense[i], compareTo)) { return Long.valueOf(i); } } } else { for (int i=(int)start; i < length; i++) { if (na.dense[i] != Scriptable.NOT_FOUND && ScriptRuntime.shallowEq(na.dense[i], compareTo)) { return Long.valueOf(i); } } } return NEGATIVE_ONE; } } if (isLast) { for (long i=start; i >= 0; i--) { if (ScriptRuntime.shallowEq(getElem(cx, thisObj, i), compareTo)) { return new Long(i); } } } else { for (long i=start; i < length; i++) { if (ScriptRuntime.shallowEq(getElem(cx, thisObj, i), compareTo)) { return new Long(i); } } } return NEGATIVE_ONE; } /** * Implements the methods "every", "filter", "forEach", "map", and "some". */ private Object iterativeMethod(Context cx, int id, Scriptable scope, Scriptable thisObj, Object[] args) { Object callbackArg = args.length > 0 ? args[0] : Undefined.instance; if (callbackArg == null || !(callbackArg instanceof Function)) { throw ScriptRuntime.notFunctionError(callbackArg); } Function f = (Function) callbackArg; Scriptable parent = ScriptableObject.getTopLevelScope(f); Scriptable thisArg; if (args.length < 2 || args[1] == null || args[1] == Undefined.instance) { thisArg = parent; } else { thisArg = ScriptRuntime.toObject(cx, scope, args[1]); } long length = getLengthProperty(cx, thisObj); Scriptable array = ScriptRuntime.newObject(cx, scope, "Array", null); long j=0; for (long i=0; i < length; i++) { Object[] innerArgs = new Object[3]; Object elem = getRawElem(thisObj, i); if (elem == Scriptable.NOT_FOUND) { continue; } innerArgs[0] = elem; innerArgs[1] = Long.valueOf(i); innerArgs[2] = thisObj; Object result = f.call(cx, parent, thisArg, innerArgs); switch (id) { case Id_every: if (!ScriptRuntime.toBoolean(result)) return Boolean.FALSE; break; case Id_filter: if (ScriptRuntime.toBoolean(result)) setElem(cx, array, j++, innerArgs[0]); break; case Id_forEach: break; case Id_map: setElem(cx, array, i, result); break; case Id_some: if (ScriptRuntime.toBoolean(result)) return Boolean.TRUE; break; } } switch (id) { case Id_every: return Boolean.TRUE; case Id_filter: case Id_map: return array; case Id_some: return Boolean.FALSE; case Id_forEach: default: return Undefined.instance; } } /** * Implements the methods "reduce" and "reduceRight". */ private Object reduceMethod(Context cx, int id, Scriptable scope, Scriptable thisObj, Object[] args) { Object callbackArg = args.length > 0 ? args[0] : Undefined.instance; if (callbackArg == null || !(callbackArg instanceof Function)) { throw ScriptRuntime.notFunctionError(callbackArg); } Function f = (Function) callbackArg; Scriptable parent = ScriptableObject.getTopLevelScope(f); long length = getLengthProperty(cx, thisObj); // offset hack to serve both reduce and reduceRight with the same loop long offset = id == Id_reduceRight ? length - 1 : 0; Object value = args.length > 1 ? args[1] : Scriptable.NOT_FOUND; for (long i = 0; i < length; i++) { Object elem = getRawElem(thisObj, Math.abs(i - offset)); if (elem == Scriptable.NOT_FOUND) { continue; } if (value == Scriptable.NOT_FOUND) { // no initial value passed, use first element found as inital value value = elem; } else { Object[] innerArgs = new Object[4]; innerArgs[0] = value; innerArgs[1] = elem; innerArgs[2] = new Long(i); innerArgs[3] = thisObj; value = f.call(cx, parent, parent, innerArgs); } } if (value == Scriptable.NOT_FOUND) { // reproduce spidermonkey error message throw Context.reportRuntimeError0("msg.empty.array.reduce"); } return value; } // #string_id_map# @Override protected int findPrototypeId(String s) { int id; // #generated# Last update: 2005-09-26 15:47:42 EDT L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 3: c=s.charAt(0); if (c=='m') { if (s.charAt(2)=='p' && s.charAt(1)=='a') {id=Id_map; break L0;} } else if (c=='p') { if (s.charAt(2)=='p' && s.charAt(1)=='o') {id=Id_pop; break L0;} } break L; case 4: switch (s.charAt(2)) { case 'i': X="join";id=Id_join; break L; case 'm': X="some";id=Id_some; break L; case 'r': X="sort";id=Id_sort; break L; case 's': X="push";id=Id_push; break L; } break L; case 5: c=s.charAt(1); if (c=='h') { X="shift";id=Id_shift; } else if (c=='l') { X="slice";id=Id_slice; } else if (c=='v') { X="every";id=Id_every; } break L; case 6: c=s.charAt(0); if (c=='c') { X="concat";id=Id_concat; } else if (c=='f') { X="filter";id=Id_filter; } else if (c=='s') { X="splice";id=Id_splice; } else if (c=='r') { X="reduce";id=Id_reduce; } break L; case 7: switch (s.charAt(0)) { case 'f': X="forEach";id=Id_forEach; break L; case 'i': X="indexOf";id=Id_indexOf; break L; case 'r': X="reverse";id=Id_reverse; break L; case 'u': X="unshift";id=Id_unshift; break L; } break L; case 8: c=s.charAt(3); if (c=='o') { X="toSource";id=Id_toSource; } else if (c=='t') { X="toString";id=Id_toString; } break L; case 11: c=s.charAt(0); if (c=='c') { X="constructor";id=Id_constructor; } else if (c=='l') { X="lastIndexOf";id=Id_lastIndexOf; } else if (c=='r') { X="reduceRight";id=Id_reduceRight; } break L; case 14: X="toLocaleString";id=Id_toLocaleString; break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# return id; } private static final int Id_constructor = 1, Id_toString = 2, Id_toLocaleString = 3, Id_toSource = 4, Id_join = 5, Id_reverse = 6, Id_sort = 7, Id_push = 8, Id_pop = 9, Id_shift = 10, Id_unshift = 11, Id_splice = 12, Id_concat = 13, Id_slice = 14, Id_indexOf = 15, Id_lastIndexOf = 16, Id_every = 17, Id_filter = 18, Id_forEach = 19, Id_map = 20, Id_some = 21, Id_reduce = 22, Id_reduceRight = 23, MAX_PROTOTYPE_ID = 23; // #/string_id_map# private static final int ConstructorId_join = -Id_join, ConstructorId_reverse = -Id_reverse, ConstructorId_sort = -Id_sort, ConstructorId_push = -Id_push, ConstructorId_pop = -Id_pop, ConstructorId_shift = -Id_shift, ConstructorId_unshift = -Id_unshift, ConstructorId_splice = -Id_splice, ConstructorId_concat = -Id_concat, ConstructorId_slice = -Id_slice, ConstructorId_indexOf = -Id_indexOf, ConstructorId_lastIndexOf = -Id_lastIndexOf, ConstructorId_every = -Id_every, ConstructorId_filter = -Id_filter, ConstructorId_forEach = -Id_forEach, ConstructorId_map = -Id_map, ConstructorId_some = -Id_some, ConstructorId_reduce = -Id_reduce, ConstructorId_reduceRight = -Id_reduceRight; /** * Internal representation of the JavaScript array's length property. */ private long length; /** * Fast storage for dense arrays. Sparse arrays will use the superclass's * hashtable storage scheme. */ private Object[] dense; /** * True if all numeric properties are stored in dense. */ private boolean denseOnly; /** * The maximum size of dense that will be allocated initially. */ private static int maximumInitialCapacity = 10000; /** * The default capacity for dense. */ private static final int DEFAULT_INITIAL_CAPACITY = 10; /** * The factor to grow dense by. */ private static final double GROW_FACTOR = 1.5; private static final int MAX_PRE_GROW_SIZE = (int)(Integer.MAX_VALUE / GROW_FACTOR); } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/javascript/LazilyLoadedCtor.java0000644000175000017500000001315111314263504034154 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.lang.reflect.*; import java.security.AccessController; import java.security.PrivilegedAction; /** * Avoid loading classes unless they are used. * *

This improves startup time and average memory usage. */ public final class LazilyLoadedCtor implements java.io.Serializable { private static final long serialVersionUID = 1L; private static final int STATE_BEFORE_INIT = 0; private static final int STATE_INITIALIZING = 1; private static final int STATE_WITH_VALUE = 2; private final ScriptableObject scope; private final String propertyName; private final String className; private final boolean sealed; private final boolean privileged; private Object initializedValue; private int state; public LazilyLoadedCtor(ScriptableObject scope, String propertyName, String className, boolean sealed) { this(scope, propertyName, className, sealed, false); } LazilyLoadedCtor(ScriptableObject scope, String propertyName, String className, boolean sealed, boolean privileged) { this.scope = scope; this.propertyName = propertyName; this.className = className; this.sealed = sealed; this.privileged = privileged; this.state = STATE_BEFORE_INIT; scope.addLazilyInitializedValue(propertyName, 0, this, ScriptableObject.DONTENUM); } void init() { synchronized (this) { if (state == STATE_INITIALIZING) throw new IllegalStateException( "Recursive initialization for "+propertyName); if (state == STATE_BEFORE_INIT) { state = STATE_INITIALIZING; // Set value now to have something to set in finally block if // buildValue throws. Object value = Scriptable.NOT_FOUND; try { value = buildValue(); } finally { initializedValue = value; state = STATE_WITH_VALUE; } } } } Object getValue() { if (state != STATE_WITH_VALUE) throw new IllegalStateException(propertyName); return initializedValue; } private Object buildValue() { if(privileged) { return AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return buildValue0(); } }); } else { return buildValue0(); } } private Object buildValue0() { Class cl = cast(Kit.classOrNull(className)); if (cl != null) { try { Object value = ScriptableObject.buildClassCtor(scope, cl, sealed, false); if (value != null) { return value; } else { // cl has own static initializer which is expected // to set the property on its own. value = scope.get(propertyName, scope); if (value != Scriptable.NOT_FOUND) return value; } } catch (InvocationTargetException ex) { Throwable target = ex.getTargetException(); if (target instanceof RuntimeException) { throw (RuntimeException)target; } } catch (RhinoException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (SecurityException ex) { } } return Scriptable.NOT_FOUND; } @SuppressWarnings({"unchecked"}) private Class cast(Class cl) { return (Class)cl; } } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/classfile/0000755000175000017500000000000011537630013027702 5ustar jamespagejamespage00000000000000jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/classfile/ByteCode.java0000644000175000017500000001560311314263504032250 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Roger Lawrence * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.classfile; /** * This class provides opcode values expected by the JVM in Java class files. * * It also provides tables for internal use by the ClassFileWriter. * * @author Roger Lawrence */ public class ByteCode { /** * The byte opcodes defined by the Java Virtual Machine. */ public static final int NOP = 0x00, ACONST_NULL = 0x01, ICONST_M1 = 0x02, ICONST_0 = 0x03, ICONST_1 = 0x04, ICONST_2 = 0x05, ICONST_3 = 0x06, ICONST_4 = 0x07, ICONST_5 = 0x08, LCONST_0 = 0x09, LCONST_1 = 0x0A, FCONST_0 = 0x0B, FCONST_1 = 0x0C, FCONST_2 = 0x0D, DCONST_0 = 0x0E, DCONST_1 = 0x0F, BIPUSH = 0x10, SIPUSH = 0x11, LDC = 0x12, LDC_W = 0x13, LDC2_W = 0x14, ILOAD = 0x15, LLOAD = 0x16, FLOAD = 0x17, DLOAD = 0x18, ALOAD = 0x19, ILOAD_0 = 0x1A, ILOAD_1 = 0x1B, ILOAD_2 = 0x1C, ILOAD_3 = 0x1D, LLOAD_0 = 0x1E, LLOAD_1 = 0x1F, LLOAD_2 = 0x20, LLOAD_3 = 0x21, FLOAD_0 = 0x22, FLOAD_1 = 0x23, FLOAD_2 = 0x24, FLOAD_3 = 0x25, DLOAD_0 = 0x26, DLOAD_1 = 0x27, DLOAD_2 = 0x28, DLOAD_3 = 0x29, ALOAD_0 = 0x2A, ALOAD_1 = 0x2B, ALOAD_2 = 0x2C, ALOAD_3 = 0x2D, IALOAD = 0x2E, LALOAD = 0x2F, FALOAD = 0x30, DALOAD = 0x31, AALOAD = 0x32, BALOAD = 0x33, CALOAD = 0x34, SALOAD = 0x35, ISTORE = 0x36, LSTORE = 0x37, FSTORE = 0x38, DSTORE = 0x39, ASTORE = 0x3A, ISTORE_0 = 0x3B, ISTORE_1 = 0x3C, ISTORE_2 = 0x3D, ISTORE_3 = 0x3E, LSTORE_0 = 0x3F, LSTORE_1 = 0x40, LSTORE_2 = 0x41, LSTORE_3 = 0x42, FSTORE_0 = 0x43, FSTORE_1 = 0x44, FSTORE_2 = 0x45, FSTORE_3 = 0x46, DSTORE_0 = 0x47, DSTORE_1 = 0x48, DSTORE_2 = 0x49, DSTORE_3 = 0x4A, ASTORE_0 = 0x4B, ASTORE_1 = 0x4C, ASTORE_2 = 0x4D, ASTORE_3 = 0x4E, IASTORE = 0x4F, LASTORE = 0x50, FASTORE = 0x51, DASTORE = 0x52, AASTORE = 0x53, BASTORE = 0x54, CASTORE = 0x55, SASTORE = 0x56, POP = 0x57, POP2 = 0x58, DUP = 0x59, DUP_X1 = 0x5A, DUP_X2 = 0x5B, DUP2 = 0x5C, DUP2_X1 = 0x5D, DUP2_X2 = 0x5E, SWAP = 0x5F, IADD = 0x60, LADD = 0x61, FADD = 0x62, DADD = 0x63, ISUB = 0x64, LSUB = 0x65, FSUB = 0x66, DSUB = 0x67, IMUL = 0x68, LMUL = 0x69, FMUL = 0x6A, DMUL = 0x6B, IDIV = 0x6C, LDIV = 0x6D, FDIV = 0x6E, DDIV = 0x6F, IREM = 0x70, LREM = 0x71, FREM = 0x72, DREM = 0x73, INEG = 0x74, LNEG = 0x75, FNEG = 0x76, DNEG = 0x77, ISHL = 0x78, LSHL = 0x79, ISHR = 0x7A, LSHR = 0x7B, IUSHR = 0x7C, LUSHR = 0x7D, IAND = 0x7E, LAND = 0x7F, IOR = 0x80, LOR = 0x81, IXOR = 0x82, LXOR = 0x83, IINC = 0x84, I2L = 0x85, I2F = 0x86, I2D = 0x87, L2I = 0x88, L2F = 0x89, L2D = 0x8A, F2I = 0x8B, F2L = 0x8C, F2D = 0x8D, D2I = 0x8E, D2L = 0x8F, D2F = 0x90, I2B = 0x91, I2C = 0x92, I2S = 0x93, LCMP = 0x94, FCMPL = 0x95, FCMPG = 0x96, DCMPL = 0x97, DCMPG = 0x98, IFEQ = 0x99, IFNE = 0x9A, IFLT = 0x9B, IFGE = 0x9C, IFGT = 0x9D, IFLE = 0x9E, IF_ICMPEQ = 0x9F, IF_ICMPNE = 0xA0, IF_ICMPLT = 0xA1, IF_ICMPGE = 0xA2, IF_ICMPGT = 0xA3, IF_ICMPLE = 0xA4, IF_ACMPEQ = 0xA5, IF_ACMPNE = 0xA6, GOTO = 0xA7, JSR = 0xA8, RET = 0xA9, TABLESWITCH = 0xAA, LOOKUPSWITCH = 0xAB, IRETURN = 0xAC, LRETURN = 0xAD, FRETURN = 0xAE, DRETURN = 0xAF, ARETURN = 0xB0, RETURN = 0xB1, GETSTATIC = 0xB2, PUTSTATIC = 0xB3, GETFIELD = 0xB4, PUTFIELD = 0xB5, INVOKEVIRTUAL = 0xB6, INVOKESPECIAL = 0xB7, INVOKESTATIC = 0xB8, INVOKEINTERFACE = 0xB9, NEW = 0xBB, NEWARRAY = 0xBC, ANEWARRAY = 0xBD, ARRAYLENGTH = 0xBE, ATHROW = 0xBF, CHECKCAST = 0xC0, INSTANCEOF = 0xC1, MONITORENTER = 0xC2, MONITOREXIT = 0xC3, WIDE = 0xC4, MULTIANEWARRAY = 0xC5, IFNULL = 0xC6, IFNONNULL = 0xC7, GOTO_W = 0xC8, JSR_W = 0xC9, BREAKPOINT = 0xCA, IMPDEP1 = 0xFE, IMPDEP2 = 0xFF; /** * Types for the NEWARRAY opcode. */ public static final byte T_BOOLEAN = 4, T_CHAR = 5, T_FLOAT = 6, T_DOUBLE = 7, T_BYTE = 8, T_SHORT = 9, T_INT = 10, T_LONG = 11; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/src/org/mozilla/classfile/ClassFileWriter.java0000644000175000017500000032663511314263504033626 0ustar jamespagejamespage00000000000000/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Roger Lawrence * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.classfile; import org.mozilla.javascript.ObjToIntMap; import org.mozilla.javascript.ObjArray; import org.mozilla.javascript.UintMap; import java.io.*; /** * ClassFileWriter * * A ClassFileWriter is used to write a Java class file. Methods are * provided to create fields and methods, and within methods to write * Java bytecodes. * * @author Roger Lawrence */ public class ClassFileWriter { /** * Thrown for cases where the error in generating the class file is * due to a program size constraints rather than a likely bug in the * compiler. */ public static class ClassFileFormatException extends RuntimeException { private static final long serialVersionUID = 1263998431033790599L; ClassFileFormatException(String message) { super(message); } } /** * Construct a ClassFileWriter for a class. * * @param className the name of the class to write, including * full package qualification. * @param superClassName the name of the superclass of the class * to write, including full package qualification. * @param sourceFileName the name of the source file to use for * producing debug information, or null if debug information * is not desired */ public ClassFileWriter(String className, String superClassName, String sourceFileName) { generatedClassName = className; itsConstantPool = new ConstantPool(this); itsThisClassIndex = itsConstantPool.addClass(className); itsSuperClassIndex = itsConstantPool.addClass(superClassName); if (sourceFileName != null) itsSourceFileNameIndex = itsConstantPool.addUtf8(sourceFileName); itsFlags = ACC_PUBLIC; } public final String getClassName() { return generatedClassName; } /** * Add an interface implemented by this class. * * This method may be called multiple times for classes that * implement multiple interfaces. * * @param interfaceName a name of an interface implemented * by the class being written, including full package * qualification. */ public void addInterface(String interfaceName) { short interfaceIndex = itsConstantPool.addClass(interfaceName); itsInterfaces.add(Short.valueOf(interfaceIndex)); } public static final short ACC_PUBLIC = 0x0001, ACC_PRIVATE = 0x0002, ACC_PROTECTED = 0x0004, ACC_STATIC = 0x0008, ACC_FINAL = 0x0010, ACC_SYNCHRONIZED = 0x0020, ACC_VOLATILE = 0x0040, ACC_TRANSIENT = 0x0080, ACC_NATIVE = 0x0100, ACC_ABSTRACT = 0x0400; /** * Set the class's flags. * * Flags must be a set of the following flags, bitwise or'd * together: * ACC_PUBLIC * ACC_PRIVATE * ACC_PROTECTED * ACC_FINAL * ACC_ABSTRACT * TODO: check that this is the appropriate set * @param flags the set of class flags to set */ public void setFlags(short flags) { itsFlags = flags; } static String getSlashedForm(String name) { return name.replace('.', '/'); } /** * Convert Java class name in dot notation into * "Lname-with-dots-replaced-by-slashes;" form suitable for use as * JVM type signatures. */ public static String classNameToSignature(String name) { int nameLength = name.length(); int colonPos = 1 + nameLength; char[] buf = new char[colonPos + 1]; buf[0] = 'L'; buf[colonPos] = ';'; name.getChars(0, nameLength, buf, 1); for (int i = 1; i != colonPos; ++i) { if (buf[i] == '.') { buf[i] = '/'; } } return new String(buf, 0, colonPos + 1); } /** * Add a field to the class. * * @param fieldName the name of the field * @param type the type of the field using ... * @param flags the attributes of the field, such as ACC_PUBLIC, etc. * bitwise or'd together */ public void addField(String fieldName, String type, short flags) { short fieldNameIndex = itsConstantPool.addUtf8(fieldName); short typeIndex = itsConstantPool.addUtf8(type); itsFields.add(new ClassFileField(fieldNameIndex, typeIndex, flags)); } /** * Add a field to the class. * * @param fieldName the name of the field * @param type the type of the field using ... * @param flags the attributes of the field, such as ACC_PUBLIC, etc. * bitwise or'd together * @param value an initial integral value */ public void addField(String fieldName, String type, short flags, int value) { short fieldNameIndex = itsConstantPool.addUtf8(fieldName); short typeIndex = itsConstantPool.addUtf8(type); ClassFileField field = new ClassFileField(fieldNameIndex, typeIndex, flags); field.setAttributes(itsConstantPool.addUtf8("ConstantValue"), (short)0, (short)0, itsConstantPool.addConstant(value)); itsFields.add(field); } /** * Add a field to the class. * * @param fieldName the name of the field * @param type the type of the field using ... * @param flags the attributes of the field, such as ACC_PUBLIC, etc. * bitwise or'd together * @param value an initial long value */ public void addField(String fieldName, String type, short flags, long value) { short fieldNameIndex = itsConstantPool.addUtf8(fieldName); short typeIndex = itsConstantPool.addUtf8(type); ClassFileField field = new ClassFileField(fieldNameIndex, typeIndex, flags); field.setAttributes(itsConstantPool.addUtf8("ConstantValue"), (short)0, (short)2, itsConstantPool.addConstant(value)); itsFields.add(field); } /** * Add a field to the class. * * @param fieldName the name of the field * @param type the type of the field using ... * @param flags the attributes of the field, such as ACC_PUBLIC, etc. * bitwise or'd together * @param value an initial double value */ public void addField(String fieldName, String type, short flags, double value) { short fieldNameIndex = itsConstantPool.addUtf8(fieldName); short typeIndex = itsConstantPool.addUtf8(type); ClassFileField field = new ClassFileField(fieldNameIndex, typeIndex, flags); field.setAttributes(itsConstantPool.addUtf8("ConstantValue"), (short)0, (short)2, itsConstantPool.addConstant(value)); itsFields.add(field); } /** * Add Information about java variable to use when generating the local * variable table. * * @param name variable name. * @param type variable type as bytecode descriptor string. * @param startPC the starting bytecode PC where this variable is live, * or -1 if it does not have a Java register. * @param register the Java register number of variable * or -1 if it does not have a Java register. */ public void addVariableDescriptor(String name, String type, int startPC, int register) { int nameIndex = itsConstantPool.addUtf8(name); int descriptorIndex = itsConstantPool.addUtf8(type); int [] chunk = { nameIndex, descriptorIndex, startPC, register }; if (itsVarDescriptors == null) { itsVarDescriptors = new ObjArray(); } itsVarDescriptors.add(chunk); } /** * Add a method and begin adding code. * * This method must be called before other methods for adding code, * exception tables, etc. can be invoked. * * @param methodName the name of the method * @param type a string representing the type * @param flags the attributes of the field, such as ACC_PUBLIC, etc. * bitwise or'd together */ public void startMethod(String methodName, String type, short flags) { short methodNameIndex = itsConstantPool.addUtf8(methodName); short typeIndex = itsConstantPool.addUtf8(type); itsCurrentMethod = new ClassFileMethod(methodNameIndex, typeIndex, flags); itsMethods.add(itsCurrentMethod); } /** * Complete generation of the method. * * After this method is called, no more code can be added to the * method begun with startMethod. * * @param maxLocals the maximum number of local variable slots * (a.k.a. Java registers) used by the method */ public void stopMethod(short maxLocals) { if (itsCurrentMethod == null) throw new IllegalStateException("No method to stop"); fixLabelGotos(); itsMaxLocals = maxLocals; int lineNumberTableLength = 0; if (itsLineNumberTable != null) { // 6 bytes for the attribute header // 2 bytes for the line number count // 4 bytes for each entry lineNumberTableLength = 6 + 2 + (itsLineNumberTableTop * 4); } int variableTableLength = 0; if (itsVarDescriptors != null) { // 6 bytes for the attribute header // 2 bytes for the variable count // 10 bytes for each entry variableTableLength = 6 + 2 + (itsVarDescriptors.size() * 10); } int attrLength = 2 + // attribute_name_index 4 + // attribute_length 2 + // max_stack 2 + // max_locals 4 + // code_length itsCodeBufferTop + 2 + // exception_table_length (itsExceptionTableTop * 8) + 2 + // attributes_count lineNumberTableLength + variableTableLength; if (attrLength > 65536) { // See http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html, // section 4.10, "The amount of code per non-native, non-abstract // method is limited to 65536 bytes... throw new ClassFileFormatException( "generated bytecode for method exceeds 64K limit."); } byte[] codeAttribute = new byte[attrLength]; int index = 0; int codeAttrIndex = itsConstantPool.addUtf8("Code"); index = putInt16(codeAttrIndex, codeAttribute, index); attrLength -= 6; // discount the attribute header index = putInt32(attrLength, codeAttribute, index); index = putInt16(itsMaxStack, codeAttribute, index); index = putInt16(itsMaxLocals, codeAttribute, index); index = putInt32(itsCodeBufferTop, codeAttribute, index); System.arraycopy(itsCodeBuffer, 0, codeAttribute, index, itsCodeBufferTop); index += itsCodeBufferTop; if (itsExceptionTableTop > 0) { index = putInt16(itsExceptionTableTop, codeAttribute, index); for (int i = 0; i < itsExceptionTableTop; i++) { ExceptionTableEntry ete = itsExceptionTable[i]; short startPC = (short)getLabelPC(ete.itsStartLabel); short endPC = (short)getLabelPC(ete.itsEndLabel); short handlerPC = (short)getLabelPC(ete.itsHandlerLabel); short catchType = ete.itsCatchType; if (startPC == -1) throw new IllegalStateException("start label not defined"); if (endPC == -1) throw new IllegalStateException("end label not defined"); if (handlerPC == -1) throw new IllegalStateException( "handler label not defined"); index = putInt16(startPC, codeAttribute, index); index = putInt16(endPC, codeAttribute, index); index = putInt16(handlerPC, codeAttribute, index); index = putInt16(catchType, codeAttribute, index); } } else { // write 0 as exception table length index = putInt16(0, codeAttribute, index); } int attributeCount = 0; if (itsLineNumberTable != null) attributeCount++; if (itsVarDescriptors != null) attributeCount++; index = putInt16(attributeCount, codeAttribute, index); if (itsLineNumberTable != null) { int lineNumberTableAttrIndex = itsConstantPool.addUtf8("LineNumberTable"); index = putInt16(lineNumberTableAttrIndex, codeAttribute, index); int tableAttrLength = 2 + (itsLineNumberTableTop * 4); index = putInt32(tableAttrLength, codeAttribute, index); index = putInt16(itsLineNumberTableTop, codeAttribute, index); for (int i = 0; i < itsLineNumberTableTop; i++) { index = putInt32(itsLineNumberTable[i], codeAttribute, index); } } if (itsVarDescriptors != null) { int variableTableAttrIndex = itsConstantPool.addUtf8("LocalVariableTable"); index = putInt16(variableTableAttrIndex, codeAttribute, index); int varCount = itsVarDescriptors.size(); int tableAttrLength = 2 + (varCount * 10); index = putInt32(tableAttrLength, codeAttribute, index); index = putInt16(varCount, codeAttribute, index); for (int i = 0; i < varCount; i++) { int[] chunk = (int[])itsVarDescriptors.get(i); int nameIndex = chunk[0]; int descriptorIndex = chunk[1]; int startPC = chunk[2]; int register = chunk[3]; int length = itsCodeBufferTop - startPC; index = putInt16(startPC, codeAttribute, index); index = putInt16(length, codeAttribute, index); index = putInt16(nameIndex, codeAttribute, index); index = putInt16(descriptorIndex, codeAttribute, index); index = putInt16(register, codeAttribute, index); } } itsCurrentMethod.setCodeAttribute(codeAttribute); itsExceptionTable = null; itsExceptionTableTop = 0; itsLineNumberTableTop = 0; itsCodeBufferTop = 0; itsCurrentMethod = null; itsMaxStack = 0; itsStackTop = 0; itsLabelTableTop = 0; itsFixupTableTop = 0; itsVarDescriptors = null; } /** * Add the single-byte opcode to the current method. * * @param theOpCode the opcode of the bytecode */ public void add(int theOpCode) { if (opcodeCount(theOpCode) != 0) throw new IllegalArgumentException("Unexpected operands"); int newStack = itsStackTop + stackChange(theOpCode); if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack); if (DEBUGCODE) System.out.println("Add " + bytecodeStr(theOpCode)); addToCodeBuffer(theOpCode); itsStackTop = (short)newStack; if (newStack > itsMaxStack) itsMaxStack = (short)newStack; if (DEBUGSTACK) { System.out.println("After "+bytecodeStr(theOpCode) +" stack = "+itsStackTop); } } /** * Add a single-operand opcode to the current method. * * @param theOpCode the opcode of the bytecode * @param theOperand the operand of the bytecode */ public void add(int theOpCode, int theOperand) { if (DEBUGCODE) { System.out.println("Add "+bytecodeStr(theOpCode) +", "+Integer.toHexString(theOperand)); } int newStack = itsStackTop + stackChange(theOpCode); if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack); switch (theOpCode) { case ByteCode.GOTO : // fallthru... case ByteCode.IFEQ : case ByteCode.IFNE : case ByteCode.IFLT : case ByteCode.IFGE : case ByteCode.IFGT : case ByteCode.IFLE : case ByteCode.IF_ICMPEQ : case ByteCode.IF_ICMPNE : case ByteCode.IF_ICMPLT : case ByteCode.IF_ICMPGE : case ByteCode.IF_ICMPGT : case ByteCode.IF_ICMPLE : case ByteCode.IF_ACMPEQ : case ByteCode.IF_ACMPNE : case ByteCode.JSR : case ByteCode.IFNULL : case ByteCode.IFNONNULL : { if ((theOperand & 0x80000000) != 0x80000000) { if ((theOperand < 0) || (theOperand > 65535)) throw new IllegalArgumentException( "Bad label for branch"); } int branchPC = itsCodeBufferTop; addToCodeBuffer(theOpCode); if ((theOperand & 0x80000000) != 0x80000000) { // hard displacement addToCodeInt16(theOperand); } else { // a label int targetPC = getLabelPC(theOperand); if (DEBUGLABELS) { int theLabel = theOperand & 0x7FFFFFFF; System.out.println("Fixing branch to " + theLabel + " at " + targetPC + " from " + branchPC); } if (targetPC != -1) { int offset = targetPC - branchPC; addToCodeInt16(offset); } else { addLabelFixup(theOperand, branchPC + 1); addToCodeInt16(0); } } } break; case ByteCode.BIPUSH : if ((byte)theOperand != theOperand) throw new IllegalArgumentException("out of range byte"); addToCodeBuffer(theOpCode); addToCodeBuffer((byte)theOperand); break; case ByteCode.SIPUSH : if ((short)theOperand != theOperand) throw new IllegalArgumentException("out of range short"); addToCodeBuffer(theOpCode); addToCodeInt16(theOperand); break; case ByteCode.NEWARRAY : if (!(0 <= theOperand && theOperand < 256)) throw new IllegalArgumentException("out of range index"); addToCodeBuffer(theOpCode); addToCodeBuffer(theOperand); break; case ByteCode.GETFIELD : case ByteCode.PUTFIELD : if (!(0 <= theOperand && theOperand < 65536)) throw new IllegalArgumentException("out of range field"); addToCodeBuffer(theOpCode); addToCodeInt16(theOperand); break; case ByteCode.LDC : case ByteCode.LDC_W : case ByteCode.LDC2_W : if (!(0 <= theOperand && theOperand < 65536)) throw new IllegalArgumentException("out of range index"); if (theOperand >= 256 || theOpCode == ByteCode.LDC_W || theOpCode == ByteCode.LDC2_W) { if (theOpCode == ByteCode.LDC) { addToCodeBuffer(ByteCode.LDC_W); } else { addToCodeBuffer(theOpCode); } addToCodeInt16(theOperand); } else { addToCodeBuffer(theOpCode); addToCodeBuffer(theOperand); } break; case ByteCode.RET : case ByteCode.ILOAD : case ByteCode.LLOAD : case ByteCode.FLOAD : case ByteCode.DLOAD : case ByteCode.ALOAD : case ByteCode.ISTORE : case ByteCode.LSTORE : case ByteCode.FSTORE : case ByteCode.DSTORE : case ByteCode.ASTORE : if (!(0 <= theOperand && theOperand < 65536)) throw new ClassFileFormatException("out of range variable"); if (theOperand >= 256) { addToCodeBuffer(ByteCode.WIDE); addToCodeBuffer(theOpCode); addToCodeInt16(theOperand); } else { addToCodeBuffer(theOpCode); addToCodeBuffer(theOperand); } break; default : throw new IllegalArgumentException( "Unexpected opcode for 1 operand"); } itsStackTop = (short)newStack; if (newStack > itsMaxStack) itsMaxStack = (short)newStack; if (DEBUGSTACK) { System.out.println("After "+bytecodeStr(theOpCode) +" stack = "+itsStackTop); } } /** * Generate the load constant bytecode for the given integer. * * @param k the constant */ public void addLoadConstant(int k) { switch (k) { case 0: add(ByteCode.ICONST_0); break; case 1: add(ByteCode.ICONST_1); break; case 2: add(ByteCode.ICONST_2); break; case 3: add(ByteCode.ICONST_3); break; case 4: add(ByteCode.ICONST_4); break; case 5: add(ByteCode.ICONST_5); break; default: add(ByteCode.LDC, itsConstantPool.addConstant(k)); break; } } /** * Generate the load constant bytecode for the given long. * * @param k the constant */ public void addLoadConstant(long k) { add(ByteCode.LDC2_W, itsConstantPool.addConstant(k)); } /** * Generate the load constant bytecode for the given float. * * @param k the constant */ public void addLoadConstant(float k) { add(ByteCode.LDC, itsConstantPool.addConstant(k)); } /** * Generate the load constant bytecode for the given double. * * @param k the constant */ public void addLoadConstant(double k) { add(ByteCode.LDC2_W, itsConstantPool.addConstant(k)); } /** * Generate the load constant bytecode for the given string. * * @param k the constant */ public void addLoadConstant(String k) { add(ByteCode.LDC, itsConstantPool.addConstant(k)); } /** * Add the given two-operand bytecode to the current method. * * @param theOpCode the opcode of the bytecode * @param theOperand1 the first operand of the bytecode * @param theOperand2 the second operand of the bytecode */ public void add(int theOpCode, int theOperand1, int theOperand2) { if (DEBUGCODE) { System.out.println("Add "+bytecodeStr(theOpCode) +", "+Integer.toHexString(theOperand1) +", "+Integer.toHexString(theOperand2)); } int newStack = itsStackTop + stackChange(theOpCode); if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack); if (theOpCode == ByteCode.IINC) { if (!(0 <= theOperand1 && theOperand1 < 65536)) throw new ClassFileFormatException("out of range variable"); if (!(0 <= theOperand2 && theOperand2 < 65536)) throw new ClassFileFormatException("out of range increment"); if (theOperand1 > 255 || theOperand2 < -128 || theOperand2 > 127) { addToCodeBuffer(ByteCode.WIDE); addToCodeBuffer(ByteCode.IINC); addToCodeInt16(theOperand1); addToCodeInt16(theOperand2); } else { addToCodeBuffer(ByteCode.WIDE); addToCodeBuffer(ByteCode.IINC); addToCodeBuffer(theOperand1); addToCodeBuffer(theOperand2); } } else if (theOpCode == ByteCode.MULTIANEWARRAY) { if (!(0 <= theOperand1 && theOperand1 < 65536)) throw new IllegalArgumentException("out of range index"); if (!(0 <= theOperand2 && theOperand2 < 256)) throw new IllegalArgumentException("out of range dimensions"); addToCodeBuffer(ByteCode.MULTIANEWARRAY); addToCodeInt16(theOperand1); addToCodeBuffer(theOperand2); } else { throw new IllegalArgumentException( "Unexpected opcode for 2 operands"); } itsStackTop = (short)newStack; if (newStack > itsMaxStack) itsMaxStack = (short)newStack; if (DEBUGSTACK) { System.out.println("After "+bytecodeStr(theOpCode) +" stack = "+itsStackTop); } } public void add(int theOpCode, String className) { if (DEBUGCODE) { System.out.println("Add "+bytecodeStr(theOpCode) +", "+className); } int newStack = itsStackTop + stackChange(theOpCode); if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack); switch (theOpCode) { case ByteCode.NEW : case ByteCode.ANEWARRAY : case ByteCode.CHECKCAST : case ByteCode.INSTANCEOF : { short classIndex = itsConstantPool.addClass(className); addToCodeBuffer(theOpCode); addToCodeInt16(classIndex); } break; default : throw new IllegalArgumentException( "bad opcode for class reference"); } itsStackTop = (short)newStack; if (newStack > itsMaxStack) itsMaxStack = (short)newStack; if (DEBUGSTACK) { System.out.println("After "+bytecodeStr(theOpCode) +" stack = "+itsStackTop); } } public void add(int theOpCode, String className, String fieldName, String fieldType) { if (DEBUGCODE) { System.out.println("Add "+bytecodeStr(theOpCode) +", "+className+", "+fieldName+", "+fieldType); } int newStack = itsStackTop + stackChange(theOpCode); char fieldTypeChar = fieldType.charAt(0); int fieldSize = (fieldTypeChar == 'J' || fieldTypeChar == 'D') ? 2 : 1; switch (theOpCode) { case ByteCode.GETFIELD : case ByteCode.GETSTATIC : newStack += fieldSize; break; case ByteCode.PUTSTATIC : case ByteCode.PUTFIELD : newStack -= fieldSize; break; default : throw new IllegalArgumentException( "bad opcode for field reference"); } if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack); short fieldRefIndex = itsConstantPool.addFieldRef(className, fieldName, fieldType); addToCodeBuffer(theOpCode); addToCodeInt16(fieldRefIndex); itsStackTop = (short)newStack; if (newStack > itsMaxStack) itsMaxStack = (short)newStack; if (DEBUGSTACK) { System.out.println("After "+bytecodeStr(theOpCode) +" stack = "+itsStackTop); } } public void addInvoke(int theOpCode, String className, String methodName, String methodType) { if (DEBUGCODE) { System.out.println("Add "+bytecodeStr(theOpCode) +", "+className+", "+methodName+", " +methodType); } int parameterInfo = sizeOfParameters(methodType); int parameterCount = parameterInfo >>> 16; int stackDiff = (short)parameterInfo; int newStack = itsStackTop + stackDiff; newStack += stackChange(theOpCode); // adjusts for 'this' if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack); switch (theOpCode) { case ByteCode.INVOKEVIRTUAL : case ByteCode.INVOKESPECIAL : case ByteCode.INVOKESTATIC : case ByteCode.INVOKEINTERFACE : { addToCodeBuffer(theOpCode); if (theOpCode == ByteCode.INVOKEINTERFACE) { short ifMethodRefIndex = itsConstantPool.addInterfaceMethodRef( className, methodName, methodType); addToCodeInt16(ifMethodRefIndex); addToCodeBuffer(parameterCount + 1); addToCodeBuffer(0); } else { short methodRefIndex = itsConstantPool.addMethodRef( className, methodName, methodType); addToCodeInt16(methodRefIndex); } } break; default : throw new IllegalArgumentException( "bad opcode for method reference"); } itsStackTop = (short)newStack; if (newStack > itsMaxStack) itsMaxStack = (short)newStack; if (DEBUGSTACK) { System.out.println("After "+bytecodeStr(theOpCode) +" stack = "+itsStackTop); } } /** * Generate code to load the given integer on stack. * * @param k the constant */ public void addPush(int k) { if ((byte)k == k) { if (k == -1) { add(ByteCode.ICONST_M1); } else if (0 <= k && k <= 5) { add((byte)(ByteCode.ICONST_0 + k)); } else { add(ByteCode.BIPUSH, (byte)k); } } else if ((short)k == k) { add(ByteCode.SIPUSH, (short)k); } else { addLoadConstant(k); } } public void addPush(boolean k) { add(k ? ByteCode.ICONST_1 : ByteCode.ICONST_0); } /** * Generate code to load the given long on stack. * * @param k the constant */ public void addPush(long k) { int ik = (int)k; if (ik == k) { addPush(ik); add(ByteCode.I2L); } else { addLoadConstant(k); } } /** * Generate code to load the given double on stack. * * @param k the constant */ public void addPush(double k) { if (k == 0.0) { // zero add(ByteCode.DCONST_0); if (1.0 / k < 0) { // Negative zero add(ByteCode.DNEG); } } else if (k == 1.0 || k == -1.0) { add(ByteCode.DCONST_1); if (k < 0) { add(ByteCode.DNEG); } } else { addLoadConstant(k); } } /** * Generate the code to leave on stack the given string even if the * string encoding exeeds the class file limit for single string constant * * @param k the constant */ public void addPush(String k) { int length = k.length(); int limit = itsConstantPool.getUtfEncodingLimit(k, 0, length); if (limit == length) { addLoadConstant(k); return; } // Split string into picies fitting the UTF limit and generate code for // StringBuffer sb = new StringBuffer(length); // sb.append(loadConstant(piece_1)); // ... // sb.append(loadConstant(piece_N)); // sb.toString(); final String SB = "java/lang/StringBuffer"; add(ByteCode.NEW, SB); add(ByteCode.DUP); addPush(length); addInvoke(ByteCode.INVOKESPECIAL, SB, "", "(I)V"); int cursor = 0; for (;;) { add(ByteCode.DUP); String s = k.substring(cursor, limit); addLoadConstant(s); addInvoke(ByteCode.INVOKEVIRTUAL, SB, "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;"); add(ByteCode.POP); if (limit == length) { break; } cursor = limit; limit = itsConstantPool.getUtfEncodingLimit(k, limit, length); } addInvoke(ByteCode.INVOKEVIRTUAL, SB, "toString", "()Ljava/lang/String;"); } /** * Check if k fits limit on string constant size imposed by class file * format. * * @param k the string constant */ public boolean isUnderStringSizeLimit(String k) { return itsConstantPool.isUnderUtfEncodingLimit(k); } /** * Store integer from stack top into the given local. * * @param local number of local register */ public void addIStore(int local) { xop(ByteCode.ISTORE_0, ByteCode.ISTORE, local); } /** * Store long from stack top into the given local. * * @param local number of local register */ public void addLStore(int local) { xop(ByteCode.LSTORE_0, ByteCode.LSTORE, local); } /** * Store float from stack top into the given local. * * @param local number of local register */ public void addFStore(int local) { xop(ByteCode.FSTORE_0, ByteCode.FSTORE, local); } /** * Store double from stack top into the given local. * * @param local number of local register */ public void addDStore(int local) { xop(ByteCode.DSTORE_0, ByteCode.DSTORE, local); } /** * Store object from stack top into the given local. * * @param local number of local register */ public void addAStore(int local) { xop(ByteCode.ASTORE_0, ByteCode.ASTORE, local); } /** * Load integer from the given local into stack. * * @param local number of local register */ public void addILoad(int local) { xop(ByteCode.ILOAD_0, ByteCode.ILOAD, local); } /** * Load long from the given local into stack. * * @param local number of local register */ public void addLLoad(int local) { xop(ByteCode.LLOAD_0, ByteCode.LLOAD, local); } /** * Load float from the given local into stack. * * @param local number of local register */ public void addFLoad(int local) { xop(ByteCode.FLOAD_0, ByteCode.FLOAD, local); } /** * Load double from the given local into stack. * * @param local number of local register */ public void addDLoad(int local) { xop(ByteCode.DLOAD_0, ByteCode.DLOAD, local); } /** * Load object from the given local into stack. * * @param local number of local register */ public void addALoad(int local) { xop(ByteCode.ALOAD_0, ByteCode.ALOAD, local); } /** * Load "this" into stack. */ public void addLoadThis() { add(ByteCode.ALOAD_0); } private void xop(int shortOp, int op, int local) { switch (local) { case 0: add(shortOp); break; case 1: add(shortOp + 1); break; case 2: add(shortOp + 2); break; case 3: add(shortOp + 3); break; default: add(op, local); } } public int addTableSwitch(int low, int high) { if (DEBUGCODE) { System.out.println("Add "+bytecodeStr(ByteCode.TABLESWITCH) +" "+low+" "+high); } if (low > high) throw new ClassFileFormatException("Bad bounds: "+low+' '+ high); int newStack = itsStackTop + stackChange(ByteCode.TABLESWITCH); if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack); int entryCount = high - low + 1; int padSize = 3 & ~itsCodeBufferTop; // == 3 - itsCodeBufferTop % 4 int N = addReservedCodeSpace(1 + padSize + 4 * (1 + 2 + entryCount)); int switchStart = N; itsCodeBuffer[N++] = (byte)ByteCode.TABLESWITCH; while (padSize != 0) { itsCodeBuffer[N++] = 0; --padSize; } N += 4; // skip default offset N = putInt32(low, itsCodeBuffer, N); putInt32(high, itsCodeBuffer, N); itsStackTop = (short)newStack; if (newStack > itsMaxStack) itsMaxStack = (short)newStack; if (DEBUGSTACK) { System.out.println("After "+bytecodeStr(ByteCode.TABLESWITCH) +" stack = "+itsStackTop); } return switchStart; } public final void markTableSwitchDefault(int switchStart) { setTableSwitchJump(switchStart, -1, itsCodeBufferTop); } public final void markTableSwitchCase(int switchStart, int caseIndex) { setTableSwitchJump(switchStart, caseIndex, itsCodeBufferTop); } public final void markTableSwitchCase(int switchStart, int caseIndex, int stackTop) { if (!(0 <= stackTop && stackTop <= itsMaxStack)) throw new IllegalArgumentException("Bad stack index: "+stackTop); itsStackTop = (short)stackTop; setTableSwitchJump(switchStart, caseIndex, itsCodeBufferTop); } public void setTableSwitchJump(int switchStart, int caseIndex, int jumpTarget) { if (!(0 <= jumpTarget && jumpTarget <= itsCodeBufferTop)) throw new IllegalArgumentException("Bad jump target: "+jumpTarget); if (!(caseIndex >= -1)) throw new IllegalArgumentException("Bad case index: "+caseIndex); int padSize = 3 & ~switchStart; // == 3 - switchStart % 4 int caseOffset; if (caseIndex < 0) { // default label caseOffset = switchStart + 1 + padSize; } else { caseOffset = switchStart + 1 + padSize + 4 * (3 + caseIndex); } if (!(0 <= switchStart && switchStart <= itsCodeBufferTop - 4 * 4 - padSize - 1)) { throw new IllegalArgumentException( switchStart+" is outside a possible range of tableswitch" +" in already generated code"); } if ((0xFF & itsCodeBuffer[switchStart]) != ByteCode.TABLESWITCH) { throw new IllegalArgumentException( switchStart+" is not offset of tableswitch statement"); } if (!(0 <= caseOffset && caseOffset + 4 <= itsCodeBufferTop)) { // caseIndex >= -1 does not guarantee that caseOffset >= 0 due // to a possible overflow. throw new ClassFileFormatException( "Too big case index: "+caseIndex); } // ALERT: perhaps check against case bounds? putInt32(jumpTarget - switchStart, itsCodeBuffer, caseOffset); } public int acquireLabel() { int top = itsLabelTableTop; if (itsLabelTable == null || top == itsLabelTable.length) { if (itsLabelTable == null) { itsLabelTable = new int[MIN_LABEL_TABLE_SIZE]; }else { int[] tmp = new int[itsLabelTable.length * 2]; System.arraycopy(itsLabelTable, 0, tmp, 0, top); itsLabelTable = tmp; } } itsLabelTableTop = top + 1; itsLabelTable[top] = -1; return top | 0x80000000; } public void markLabel(int label) { if (!(label < 0)) throw new IllegalArgumentException("Bad label, no biscuit"); label &= 0x7FFFFFFF; if (label > itsLabelTableTop) throw new IllegalArgumentException("Bad label"); if (itsLabelTable[label] != -1) { throw new IllegalStateException("Can only mark label once"); } itsLabelTable[label] = itsCodeBufferTop; } public void markLabel(int label, short stackTop) { markLabel(label); itsStackTop = stackTop; } public void markHandler(int theLabel) { itsStackTop = 1; markLabel(theLabel); } private int getLabelPC(int label) { if (!(label < 0)) throw new IllegalArgumentException("Bad label, no biscuit"); label &= 0x7FFFFFFF; if (!(label < itsLabelTableTop)) throw new IllegalArgumentException("Bad label"); return itsLabelTable[label]; } private void addLabelFixup(int label, int fixupSite) { if (!(label < 0)) throw new IllegalArgumentException("Bad label, no biscuit"); label &= 0x7FFFFFFF; if (!(label < itsLabelTableTop)) throw new IllegalArgumentException("Bad label"); int top = itsFixupTableTop; if (itsFixupTable == null || top == itsFixupTable.length) { if (itsFixupTable == null) { itsFixupTable = new long[MIN_FIXUP_TABLE_SIZE]; }else { long[] tmp = new long[itsFixupTable.length * 2]; System.arraycopy(itsFixupTable, 0, tmp, 0, top); itsFixupTable = tmp; } } itsFixupTableTop = top + 1; itsFixupTable[top] = ((long)label << 32) | fixupSite; } private void fixLabelGotos() { byte[] codeBuffer = itsCodeBuffer; for (int i = 0; i < itsFixupTableTop; i++) { long fixup = itsFixupTable[i]; int label = (int)(fixup >> 32); int fixupSite = (int)fixup; int pc = itsLabelTable[label]; if (pc == -1) { // Unlocated label throw new RuntimeException(); } // -1 to get delta from instruction start int offset = pc - (fixupSite - 1); if ((short)offset != offset) { throw new ClassFileFormatException ("Program too complex: too big jump offset"); } codeBuffer[fixupSite] = (byte)(offset >> 8); codeBuffer[fixupSite + 1] = (byte)offset; } itsFixupTableTop = 0; } /** * Get the current offset into the code of the current method. * * @return an integer representing the offset */ public int getCurrentCodeOffset() { return itsCodeBufferTop; } public short getStackTop() { return itsStackTop; } public void setStackTop(short n) { itsStackTop = n; } public void adjustStackTop(int delta) { int newStack = itsStackTop + delta; if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack); itsStackTop = (short)newStack; if (newStack > itsMaxStack) itsMaxStack = (short)newStack; if (DEBUGSTACK) { System.out.println("After "+"adjustStackTop("+delta+")" +" stack = "+itsStackTop); } } private void addToCodeBuffer(int b) { int N = addReservedCodeSpace(1); itsCodeBuffer[N] = (byte)b; } private void addToCodeInt16(int value) { int N = addReservedCodeSpace(2); putInt16(value, itsCodeBuffer, N); } private int addReservedCodeSpace(int size) { if (itsCurrentMethod == null) throw new IllegalArgumentException("No method to add to"); int oldTop = itsCodeBufferTop; int newTop = oldTop + size; if (newTop > itsCodeBuffer.length) { int newSize = itsCodeBuffer.length * 2; if (newTop > newSize) { newSize = newTop; } byte[] tmp = new byte[newSize]; System.arraycopy(itsCodeBuffer, 0, tmp, 0, oldTop); itsCodeBuffer = tmp; } itsCodeBufferTop = newTop; return oldTop; } public void addExceptionHandler(int startLabel, int endLabel, int handlerLabel, String catchClassName) { if ((startLabel & 0x80000000) != 0x80000000) throw new IllegalArgumentException("Bad startLabel"); if ((endLabel & 0x80000000) != 0x80000000) throw new IllegalArgumentException("Bad endLabel"); if ((handlerLabel & 0x80000000) != 0x80000000) throw new IllegalArgumentException("Bad handlerLabel"); /* * If catchClassName is null, use 0 for the catch_type_index; which * means catch everything. (Even when the verifier has let you throw * something other than a Throwable.) */ short catch_type_index = (catchClassName == null) ? 0 : itsConstantPool.addClass(catchClassName); ExceptionTableEntry newEntry = new ExceptionTableEntry( startLabel, endLabel, handlerLabel, catch_type_index); int N = itsExceptionTableTop; if (N == 0) { itsExceptionTable = new ExceptionTableEntry[ExceptionTableSize]; } else if (N == itsExceptionTable.length) { ExceptionTableEntry[] tmp = new ExceptionTableEntry[N * 2]; System.arraycopy(itsExceptionTable, 0, tmp, 0, N); itsExceptionTable = tmp; } itsExceptionTable[N] = newEntry; itsExceptionTableTop = N + 1; } public void addLineNumberEntry(short lineNumber) { if (itsCurrentMethod == null) throw new IllegalArgumentException("No method to stop"); int N = itsLineNumberTableTop; if (N == 0) { itsLineNumberTable = new int[LineNumberTableSize]; } else if (N == itsLineNumberTable.length) { int[] tmp = new int[N * 2]; System.arraycopy(itsLineNumberTable, 0, tmp, 0, N); itsLineNumberTable = tmp; } itsLineNumberTable[N] = (itsCodeBufferTop << 16) + lineNumber; itsLineNumberTableTop = N + 1; } /** * Write the class file to the OutputStream. * * @param oStream the stream to write to * @throws IOException if writing to the stream produces an exception */ public void write(OutputStream oStream) throws IOException { byte[] array = toByteArray(); oStream.write(array); } private int getWriteSize() { int size = 0; if (itsSourceFileNameIndex != 0) { itsConstantPool.addUtf8("SourceFile"); } size += 8; //writeLong(FileHeaderConstant); size += itsConstantPool.getWriteSize(); size += 2; //writeShort(itsFlags); size += 2; //writeShort(itsThisClassIndex); size += 2; //writeShort(itsSuperClassIndex); size += 2; //writeShort(itsInterfaces.size()); size += 2 * itsInterfaces.size(); size += 2; //writeShort(itsFields.size()); for (int i = 0; i < itsFields.size(); i++) { size += ((ClassFileField)(itsFields.get(i))).getWriteSize(); } size += 2; //writeShort(itsMethods.size()); for (int i = 0; i < itsMethods.size(); i++) { size += ((ClassFileMethod)(itsMethods.get(i))).getWriteSize(); } if (itsSourceFileNameIndex != 0) { size += 2; //writeShort(1); attributes count size += 2; //writeShort(sourceFileAttributeNameIndex); size += 4; //writeInt(2); size += 2; //writeShort(itsSourceFileNameIndex); }else { size += 2; //out.writeShort(0); no attributes } return size; } /** * Get the class file as array of bytesto the OutputStream. */ public byte[] toByteArray() { int dataSize = getWriteSize(); byte[] data = new byte[dataSize]; int offset = 0; short sourceFileAttributeNameIndex = 0; if (itsSourceFileNameIndex != 0) { sourceFileAttributeNameIndex = itsConstantPool.addUtf8( "SourceFile"); } offset = putInt64(FileHeaderConstant, data, offset); offset = itsConstantPool.write(data, offset); offset = putInt16(itsFlags, data, offset); offset = putInt16(itsThisClassIndex, data, offset); offset = putInt16(itsSuperClassIndex, data, offset); offset = putInt16(itsInterfaces.size(), data, offset); for (int i = 0; i < itsInterfaces.size(); i++) { int interfaceIndex = ((Short)(itsInterfaces.get(i))).shortValue(); offset = putInt16(interfaceIndex, data, offset); } offset = putInt16(itsFields.size(), data, offset); for (int i = 0; i < itsFields.size(); i++) { ClassFileField field = (ClassFileField)itsFields.get(i); offset = field.write(data, offset); } offset = putInt16(itsMethods.size(), data, offset); for (int i = 0; i < itsMethods.size(); i++) { ClassFileMethod method = (ClassFileMethod)itsMethods.get(i); offset = method.write(data, offset); } if (itsSourceFileNameIndex != 0) { offset = putInt16(1, data, offset); // attributes count offset = putInt16(sourceFileAttributeNameIndex, data, offset); offset = putInt32(2, data, offset); offset = putInt16(itsSourceFileNameIndex, data, offset); } else { offset = putInt16(0, data, offset); // no attributes } if (offset != dataSize) { // Check getWriteSize is consistent with write! throw new RuntimeException(); } return data; } static int putInt64(long value, byte[] array, int offset) { offset = putInt32((int)(value >>> 32), array, offset); return putInt32((int)value, array, offset); } private static void badStack(int value) { String s; if (value < 0) { s = "Stack underflow: "+value; } else { s = "Too big stack: "+value; } throw new IllegalStateException(s); } /* Really weird. Returns an int with # parameters in hi 16 bits, and stack difference removal of parameters from stack and pushing the result (it does not take into account removal of this in case of non-static methods). If Java really supported references we wouldn't have to be this perverted. */ private static int sizeOfParameters(String pString) { int length = pString.length(); int rightParenthesis = pString.lastIndexOf(')'); if (3 <= length /* minimal signature takes at least 3 chars: ()V */ && pString.charAt(0) == '(' && 1 <= rightParenthesis && rightParenthesis + 1 < length) { boolean ok = true; int index = 1; int stackDiff = 0; int count = 0; stringLoop: while (index != rightParenthesis) { switch (pString.charAt(index)) { default: ok = false; break stringLoop; case 'J' : case 'D' : --stackDiff; // fall thru case 'B' : case 'S' : case 'C' : case 'I' : case 'Z' : case 'F' : --stackDiff; ++count; ++index; continue; case '[' : ++index; int c = pString.charAt(index); while (c == '[') { ++index; c = pString.charAt(index); } switch (c) { default: ok = false; break stringLoop; case 'J' : case 'D' : case 'B' : case 'S' : case 'C' : case 'I' : case 'Z' : case 'F' : --stackDiff; ++count; ++index; continue; case 'L': // fall thru } // fall thru case 'L' : { --stackDiff; ++count; ++index; int semicolon = pString.indexOf(';', index); if (!(index + 1 <= semicolon && semicolon < rightParenthesis)) { ok = false; break stringLoop; } index = semicolon + 1; continue; } } } if (ok) { switch (pString.charAt(rightParenthesis + 1)) { default: ok = false; break; case 'J' : case 'D' : ++stackDiff; // fall thru case 'B' : case 'S' : case 'C' : case 'I' : case 'Z' : case 'F' : case 'L' : case '[' : ++stackDiff; // fall thru case 'V' : break; } if (ok) { return ((count << 16) | (0xFFFF & stackDiff)); } } } throw new IllegalArgumentException( "Bad parameter signature: "+pString); } static int putInt16(int value, byte[] array, int offset) { array[offset + 0] = (byte)(value >>> 8); array[offset + 1] = (byte)value; return offset + 2; } static int putInt32(int value, byte[] array, int offset) { array[offset + 0] = (byte)(value >>> 24); array[offset + 1] = (byte)(value >>> 16); array[offset + 2] = (byte)(value >>> 8); array[offset + 3] = (byte)value; return offset + 4; } /** * Number of operands accompanying the opcode. */ static int opcodeCount(int opcode) { switch (opcode) { case ByteCode.AALOAD: case ByteCode.AASTORE: case ByteCode.ACONST_NULL: case ByteCode.ALOAD_0: case ByteCode.ALOAD_1: case ByteCode.ALOAD_2: case ByteCode.ALOAD_3: case ByteCode.ARETURN: case ByteCode.ARRAYLENGTH: case ByteCode.ASTORE_0: case ByteCode.ASTORE_1: case ByteCode.ASTORE_2: case ByteCode.ASTORE_3: case ByteCode.ATHROW: case ByteCode.BALOAD: case ByteCode.BASTORE: case ByteCode.BREAKPOINT: case ByteCode.CALOAD: case ByteCode.CASTORE: case ByteCode.D2F: case ByteCode.D2I: case ByteCode.D2L: case ByteCode.DADD: case ByteCode.DALOAD: case ByteCode.DASTORE: case ByteCode.DCMPG: case ByteCode.DCMPL: case ByteCode.DCONST_0: case ByteCode.DCONST_1: case ByteCode.DDIV: case ByteCode.DLOAD_0: case ByteCode.DLOAD_1: case ByteCode.DLOAD_2: case ByteCode.DLOAD_3: case ByteCode.DMUL: case ByteCode.DNEG: case ByteCode.DREM: case ByteCode.DRETURN: case ByteCode.DSTORE_0: case ByteCode.DSTORE_1: case ByteCode.DSTORE_2: case ByteCode.DSTORE_3: case ByteCode.DSUB: case ByteCode.DUP: case ByteCode.DUP2: case ByteCode.DUP2_X1: case ByteCode.DUP2_X2: case ByteCode.DUP_X1: case ByteCode.DUP_X2: case ByteCode.F2D: case ByteCode.F2I: case ByteCode.F2L: case ByteCode.FADD: case ByteCode.FALOAD: case ByteCode.FASTORE: case ByteCode.FCMPG: case ByteCode.FCMPL: case ByteCode.FCONST_0: case ByteCode.FCONST_1: case ByteCode.FCONST_2: case ByteCode.FDIV: case ByteCode.FLOAD_0: case ByteCode.FLOAD_1: case ByteCode.FLOAD_2: case ByteCode.FLOAD_3: case ByteCode.FMUL: case ByteCode.FNEG: case ByteCode.FREM: case ByteCode.FRETURN: case ByteCode.FSTORE_0: case ByteCode.FSTORE_1: case ByteCode.FSTORE_2: case ByteCode.FSTORE_3: case ByteCode.FSUB: case ByteCode.I2B: case ByteCode.I2C: case ByteCode.I2D: case ByteCode.I2F: case ByteCode.I2L: case ByteCode.I2S: case ByteCode.IADD: case ByteCode.IALOAD: case ByteCode.IAND: case ByteCode.IASTORE: case ByteCode.ICONST_0: case ByteCode.ICONST_1: case ByteCode.ICONST_2: case ByteCode.ICONST_3: case ByteCode.ICONST_4: case ByteCode.ICONST_5: case ByteCode.ICONST_M1: case ByteCode.IDIV: case ByteCode.ILOAD_0: case ByteCode.ILOAD_1: case ByteCode.ILOAD_2: case ByteCode.ILOAD_3: case ByteCode.IMPDEP1: case ByteCode.IMPDEP2: case ByteCode.IMUL: case ByteCode.INEG: case ByteCode.IOR: case ByteCode.IREM: case ByteCode.IRETURN: case ByteCode.ISHL: case ByteCode.ISHR: case ByteCode.ISTORE_0: case ByteCode.ISTORE_1: case ByteCode.ISTORE_2: case ByteCode.ISTORE_3: case ByteCode.ISUB: case ByteCode.IUSHR: case ByteCode.IXOR: case ByteCode.L2D: case ByteCode.L2F: case ByteCode.L2I: case ByteCode.LADD: case ByteCode.LALOAD: case ByteCode.LAND: case ByteCode.LASTORE: case ByteCode.LCMP: case ByteCode.LCONST_0: case ByteCode.LCONST_1: case ByteCode.LDIV: case ByteCode.LLOAD_0: case ByteCode.LLOAD_1: case ByteCode.LLOAD_2: case ByteCode.LLOAD_3: case ByteCode.LMUL: case ByteCode.LNEG: case ByteCode.LOR: case ByteCode.LREM: case ByteCode.LRETURN: case ByteCode.LSHL: case ByteCode.LSHR: case ByteCode.LSTORE_0: case ByteCode.LSTORE_1: case ByteCode.LSTORE_2: case ByteCode.LSTORE_3: case ByteCode.LSUB: case ByteCode.LUSHR: case ByteCode.LXOR: case ByteCode.MONITORENTER: case ByteCode.MONITOREXIT: case ByteCode.NOP: case ByteCode.POP: case ByteCode.POP2: case ByteCode.RETURN: case ByteCode.SALOAD: case ByteCode.SASTORE: case ByteCode.SWAP: case ByteCode.WIDE: return 0; case ByteCode.ALOAD: case ByteCode.ANEWARRAY: case ByteCode.ASTORE: case ByteCode.BIPUSH: case ByteCode.CHECKCAST: case ByteCode.DLOAD: case ByteCode.DSTORE: case ByteCode.FLOAD: case ByteCode.FSTORE: case ByteCode.GETFIELD: case ByteCode.GETSTATIC: case ByteCode.GOTO: case ByteCode.GOTO_W: case ByteCode.IFEQ: case ByteCode.IFGE: case ByteCode.IFGT: case ByteCode.IFLE: case ByteCode.IFLT: case ByteCode.IFNE: case ByteCode.IFNONNULL: case ByteCode.IFNULL: case ByteCode.IF_ACMPEQ: case ByteCode.IF_ACMPNE: case ByteCode.IF_ICMPEQ: case ByteCode.IF_ICMPGE: case ByteCode.IF_ICMPGT: case ByteCode.IF_ICMPLE: case ByteCode.IF_ICMPLT: case ByteCode.IF_ICMPNE: case ByteCode.ILOAD: case ByteCode.INSTANCEOF: case ByteCode.INVOKEINTERFACE: case ByteCode.INVOKESPECIAL: case ByteCode.INVOKESTATIC: case ByteCode.INVOKEVIRTUAL: case ByteCode.ISTORE: case ByteCode.JSR: case ByteCode.JSR_W: case ByteCode.LDC: case ByteCode.LDC2_W: case ByteCode.LDC_W: case ByteCode.LLOAD: case ByteCode.LSTORE: case ByteCode.NEW: case ByteCode.NEWARRAY: case ByteCode.PUTFIELD: case ByteCode.PUTSTATIC: case ByteCode.RET: case ByteCode.SIPUSH: return 1; case ByteCode.IINC: case ByteCode.MULTIANEWARRAY: return 2; case ByteCode.LOOKUPSWITCH: case ByteCode.TABLESWITCH: return -1; } throw new IllegalArgumentException("Bad opcode: "+opcode); } /** * The effect on the operand stack of a given opcode. */ static int stackChange(int opcode) { // For INVOKE... accounts only for popping this (unless static), // ignoring parameters and return type switch (opcode) { case ByteCode.DASTORE: case ByteCode.LASTORE: return -4; case ByteCode.AASTORE: case ByteCode.BASTORE: case ByteCode.CASTORE: case ByteCode.DCMPG: case ByteCode.DCMPL: case ByteCode.FASTORE: case ByteCode.IASTORE: case ByteCode.LCMP: case ByteCode.SASTORE: return -3; case ByteCode.DADD: case ByteCode.DDIV: case ByteCode.DMUL: case ByteCode.DREM: case ByteCode.DRETURN: case ByteCode.DSTORE: case ByteCode.DSTORE_0: case ByteCode.DSTORE_1: case ByteCode.DSTORE_2: case ByteCode.DSTORE_3: case ByteCode.DSUB: case ByteCode.IF_ACMPEQ: case ByteCode.IF_ACMPNE: case ByteCode.IF_ICMPEQ: case ByteCode.IF_ICMPGE: case ByteCode.IF_ICMPGT: case ByteCode.IF_ICMPLE: case ByteCode.IF_ICMPLT: case ByteCode.IF_ICMPNE: case ByteCode.LADD: case ByteCode.LAND: case ByteCode.LDIV: case ByteCode.LMUL: case ByteCode.LOR: case ByteCode.LREM: case ByteCode.LRETURN: case ByteCode.LSTORE: case ByteCode.LSTORE_0: case ByteCode.LSTORE_1: case ByteCode.LSTORE_2: case ByteCode.LSTORE_3: case ByteCode.LSUB: case ByteCode.LXOR: case ByteCode.POP2: return -2; case ByteCode.AALOAD: case ByteCode.ARETURN: case ByteCode.ASTORE: case ByteCode.ASTORE_0: case ByteCode.ASTORE_1: case ByteCode.ASTORE_2: case ByteCode.ASTORE_3: case ByteCode.ATHROW: case ByteCode.BALOAD: case ByteCode.CALOAD: case ByteCode.D2F: case ByteCode.D2I: case ByteCode.FADD: case ByteCode.FALOAD: case ByteCode.FCMPG: case ByteCode.FCMPL: case ByteCode.FDIV: case ByteCode.FMUL: case ByteCode.FREM: case ByteCode.FRETURN: case ByteCode.FSTORE: case ByteCode.FSTORE_0: case ByteCode.FSTORE_1: case ByteCode.FSTORE_2: case ByteCode.FSTORE_3: case ByteCode.FSUB: case ByteCode.GETFIELD: case ByteCode.IADD: case ByteCode.IALOAD: case ByteCode.IAND: case ByteCode.IDIV: case ByteCode.IFEQ: case ByteCode.IFGE: case ByteCode.IFGT: case ByteCode.IFLE: case ByteCode.IFLT: case ByteCode.IFNE: case ByteCode.IFNONNULL: case ByteCode.IFNULL: case ByteCode.IMUL: case ByteCode.INVOKEINTERFACE: // case ByteCode.INVOKESPECIAL: // but needs to account for case ByteCode.INVOKEVIRTUAL: // pops 'this' (unless static) case ByteCode.IOR: case ByteCode.IREM: case ByteCode.IRETURN: case ByteCode.ISHL: case ByteCode.ISHR: case ByteCode.ISTORE: case ByteCode.ISTORE_0: case ByteCode.ISTORE_1: case ByteCode.ISTORE_2: case ByteCode.ISTORE_3: case ByteCode.ISUB: case ByteCode.IUSHR: case ByteCode.IXOR: case ByteCode.L2F: case ByteCode.L2I: case ByteCode.LOOKUPSWITCH: case ByteCode.LSHL: case ByteCode.LSHR: case ByteCode.LUSHR: case ByteCode.MONITORENTER: case ByteCode.MONITOREXIT: case ByteCode.POP: case ByteCode.PUTFIELD: case ByteCode.SALOAD: case ByteCode.TABLESWITCH: return -1; case ByteCode.ANEWARRAY: case ByteCode.ARRAYLENGTH: case ByteCode.BREAKPOINT: case ByteCode.CHECKCAST: case ByteCode.D2L: case ByteCode.DALOAD: case ByteCode.DNEG: case ByteCode.F2I: case ByteCode.FNEG: case ByteCode.GETSTATIC: case ByteCode.GOTO: case ByteCode.GOTO_W: case ByteCode.I2B: case ByteCode.I2C: case ByteCode.I2F: case ByteCode.I2S: case ByteCode.IINC: case ByteCode.IMPDEP1: case ByteCode.IMPDEP2: case ByteCode.INEG: case ByteCode.INSTANCEOF: case ByteCode.INVOKESTATIC: case ByteCode.L2D: case ByteCode.LALOAD: case ByteCode.LNEG: case ByteCode.NEWARRAY: case ByteCode.NOP: case ByteCode.PUTSTATIC: case ByteCode.RET: case ByteCode.RETURN: case ByteCode.SWAP: case ByteCode.WIDE: return 0; case ByteCode.ACONST_NULL: case ByteCode.ALOAD: case ByteCode.ALOAD_0: case ByteCode.ALOAD_1: case ByteCode.ALOAD_2: case ByteCode.ALOAD_3: case ByteCode.BIPUSH: case ByteCode.DUP: case ByteCode.DUP_X1: case ByteCode.DUP_X2: case ByteCode.F2D: case ByteCode.F2L: case ByteCode.FCONST_0: case ByteCode.FCONST_1: case ByteCode.FCONST_2: case ByteCode.FLOAD: case ByteCode.FLOAD_0: case ByteCode.FLOAD_1: case ByteCode.FLOAD_2: case ByteCode.FLOAD_3: case ByteCode.I2D: case ByteCode.I2L: case ByteCode.ICONST_0: case ByteCode.ICONST_1: case ByteCode.ICONST_2: case ByteCode.ICONST_3: case ByteCode.ICONST_4: case ByteCode.ICONST_5: case ByteCode.ICONST_M1: case ByteCode.ILOAD: case ByteCode.ILOAD_0: case ByteCode.ILOAD_1: case ByteCode.ILOAD_2: case ByteCode.ILOAD_3: case ByteCode.JSR: case ByteCode.JSR_W: case ByteCode.LDC: case ByteCode.LDC_W: case ByteCode.MULTIANEWARRAY: case ByteCode.NEW: case ByteCode.SIPUSH: return 1; case ByteCode.DCONST_0: case ByteCode.DCONST_1: case ByteCode.DLOAD: case ByteCode.DLOAD_0: case ByteCode.DLOAD_1: case ByteCode.DLOAD_2: case ByteCode.DLOAD_3: case ByteCode.DUP2: case ByteCode.DUP2_X1: case ByteCode.DUP2_X2: case ByteCode.LCONST_0: case ByteCode.LCONST_1: case ByteCode.LDC2_W: case ByteCode.LLOAD: case ByteCode.LLOAD_0: case ByteCode.LLOAD_1: case ByteCode.LLOAD_2: case ByteCode.LLOAD_3: return 2; } throw new IllegalArgumentException("Bad opcode: "+opcode); } /* * Number of bytes of operands generated after the opcode. * Not in use currently. */ /* int extra(int opcode) { switch (opcode) { case ByteCode.AALOAD: case ByteCode.AASTORE: case ByteCode.ACONST_NULL: case ByteCode.ALOAD_0: case ByteCode.ALOAD_1: case ByteCode.ALOAD_2: case ByteCode.ALOAD_3: case ByteCode.ARETURN: case ByteCode.ARRAYLENGTH: case ByteCode.ASTORE_0: case ByteCode.ASTORE_1: case ByteCode.ASTORE_2: case ByteCode.ASTORE_3: case ByteCode.ATHROW: case ByteCode.BALOAD: case ByteCode.BASTORE: case ByteCode.BREAKPOINT: case ByteCode.CALOAD: case ByteCode.CASTORE: case ByteCode.D2F: case ByteCode.D2I: case ByteCode.D2L: case ByteCode.DADD: case ByteCode.DALOAD: case ByteCode.DASTORE: case ByteCode.DCMPG: case ByteCode.DCMPL: case ByteCode.DCONST_0: case ByteCode.DCONST_1: case ByteCode.DDIV: case ByteCode.DLOAD_0: case ByteCode.DLOAD_1: case ByteCode.DLOAD_2: case ByteCode.DLOAD_3: case ByteCode.DMUL: case ByteCode.DNEG: case ByteCode.DREM: case ByteCode.DRETURN: case ByteCode.DSTORE_0: case ByteCode.DSTORE_1: case ByteCode.DSTORE_2: case ByteCode.DSTORE_3: case ByteCode.DSUB: case ByteCode.DUP2: case ByteCode.DUP2_X1: case ByteCode.DUP2_X2: case ByteCode.DUP: case ByteCode.DUP_X1: case ByteCode.DUP_X2: case ByteCode.F2D: case ByteCode.F2I: case ByteCode.F2L: case ByteCode.FADD: case ByteCode.FALOAD: case ByteCode.FASTORE: case ByteCode.FCMPG: case ByteCode.FCMPL: case ByteCode.FCONST_0: case ByteCode.FCONST_1: case ByteCode.FCONST_2: case ByteCode.FDIV: case ByteCode.FLOAD_0: case ByteCode.FLOAD_1: case ByteCode.FLOAD_2: case ByteCode.FLOAD_3: case ByteCode.FMUL: case ByteCode.FNEG: case ByteCode.FREM: case ByteCode.FRETURN: case ByteCode.FSTORE_0: case ByteCode.FSTORE_1: case ByteCode.FSTORE_2: case ByteCode.FSTORE_3: case ByteCode.FSUB: case ByteCode.I2B: case ByteCode.I2C: case ByteCode.I2D: case ByteCode.I2F: case ByteCode.I2L: case ByteCode.I2S: case ByteCode.IADD: case ByteCode.IALOAD: case ByteCode.IAND: case ByteCode.IASTORE: case ByteCode.ICONST_0: case ByteCode.ICONST_1: case ByteCode.ICONST_2: case ByteCode.ICONST_3: case ByteCode.ICONST_4: case ByteCode.ICONST_5: case ByteCode.ICONST_M1: case ByteCode.IDIV: case ByteCode.ILOAD_0: case ByteCode.ILOAD_1: case ByteCode.ILOAD_2: case ByteCode.ILOAD_3: case ByteCode.IMPDEP1: case ByteCode.IMPDEP2: case ByteCode.IMUL: case ByteCode.INEG: case ByteCode.IOR: case ByteCode.IREM: case ByteCode.IRETURN: case ByteCode.ISHL: case ByteCode.ISHR: case ByteCode.ISTORE_0: case ByteCode.ISTORE_1: case ByteCode.ISTORE_2: case ByteCode.ISTORE_3: case ByteCode.ISUB: case ByteCode.IUSHR: case ByteCode.IXOR: case ByteCode.L2D: case ByteCode.L2F: case ByteCode.L2I: case ByteCode.LADD: case ByteCode.LALOAD: case ByteCode.LAND: case ByteCode.LASTORE: case ByteCode.LCMP: case ByteCode.LCONST_0: case ByteCode.LCONST_1: case ByteCode.LDIV: case ByteCode.LLOAD_0: case ByteCode.LLOAD_1: case ByteCode.LLOAD_2: case ByteCode.LLOAD_3: case ByteCode.LMUL: case ByteCode.LNEG: case ByteCode.LOR: case ByteCode.LREM: case ByteCode.LRETURN: case ByteCode.LSHL: case ByteCode.LSHR: case ByteCode.LSTORE_0: case ByteCode.LSTORE_1: case ByteCode.LSTORE_2: case ByteCode.LSTORE_3: case ByteCode.LSUB: case ByteCode.LUSHR: case ByteCode.LXOR: case ByteCode.MONITORENTER: case ByteCode.MONITOREXIT: case ByteCode.NOP: case ByteCode.POP2: case ByteCode.POP: case ByteCode.RETURN: case ByteCode.SALOAD: case ByteCode.SASTORE: case ByteCode.SWAP: case ByteCode.WIDE: return 0; case ByteCode.ALOAD: case ByteCode.ASTORE: case ByteCode.BIPUSH: case ByteCode.DLOAD: case ByteCode.DSTORE: case ByteCode.FLOAD: case ByteCode.FSTORE: case ByteCode.ILOAD: case ByteCode.ISTORE: case ByteCode.LDC: case ByteCode.LLOAD: case ByteCode.LSTORE: case ByteCode.NEWARRAY: case ByteCode.RET: return 1; case ByteCode.ANEWARRAY: case ByteCode.CHECKCAST: case ByteCode.GETFIELD: case ByteCode.GETSTATIC: case ByteCode.GOTO: case ByteCode.IFEQ: case ByteCode.IFGE: case ByteCode.IFGT: case ByteCode.IFLE: case ByteCode.IFLT: case ByteCode.IFNE: case ByteCode.IFNONNULL: case ByteCode.IFNULL: case ByteCode.IF_ACMPEQ: case ByteCode.IF_ACMPNE: case ByteCode.IF_ICMPEQ: case ByteCode.IF_ICMPGE: case ByteCode.IF_ICMPGT: case ByteCode.IF_ICMPLE: case ByteCode.IF_ICMPLT: case ByteCode.IF_ICMPNE: case ByteCode.IINC: case ByteCode.INSTANCEOF: case ByteCode.INVOKEINTERFACE: case ByteCode.INVOKESPECIAL: case ByteCode.INVOKESTATIC: case ByteCode.INVOKEVIRTUAL: case ByteCode.JSR: case ByteCode.LDC2_W: case ByteCode.LDC_W: case ByteCode.NEW: case ByteCode.PUTFIELD: case ByteCode.PUTSTATIC: case ByteCode.SIPUSH: return 2; case ByteCode.MULTIANEWARRAY: return 3; case ByteCode.GOTO_W: case ByteCode.JSR_W: return 4; case ByteCode.LOOKUPSWITCH: // depends on alignment case ByteCode.TABLESWITCH: // depends on alignment return -1; } throw new IllegalArgumentException("Bad opcode: "+opcode); } */ private static String bytecodeStr(int code) { if (DEBUGSTACK || DEBUGCODE) { switch (code) { case ByteCode.NOP: return "nop"; case ByteCode.ACONST_NULL: return "aconst_null"; case ByteCode.ICONST_M1: return "iconst_m1"; case ByteCode.ICONST_0: return "iconst_0"; case ByteCode.ICONST_1: return "iconst_1"; case ByteCode.ICONST_2: return "iconst_2"; case ByteCode.ICONST_3: return "iconst_3"; case ByteCode.ICONST_4: return "iconst_4"; case ByteCode.ICONST_5: return "iconst_5"; case ByteCode.LCONST_0: return "lconst_0"; case ByteCode.LCONST_1: return "lconst_1"; case ByteCode.FCONST_0: return "fconst_0"; case ByteCode.FCONST_1: return "fconst_1"; case ByteCode.FCONST_2: return "fconst_2"; case ByteCode.DCONST_0: return "dconst_0"; case ByteCode.DCONST_1: return "dconst_1"; case ByteCode.BIPUSH: return "bipush"; case ByteCode.SIPUSH: return "sipush"; case ByteCode.LDC: return "ldc"; case ByteCode.LDC_W: return "ldc_w"; case ByteCode.LDC2_W: return "ldc2_w"; case ByteCode.ILOAD: return "iload"; case ByteCode.LLOAD: return "lload"; case ByteCode.FLOAD: return "fload"; case ByteCode.DLOAD: return "dload"; case ByteCode.ALOAD: return "aload"; case ByteCode.ILOAD_0: return "iload_0"; case ByteCode.ILOAD_1: return "iload_1"; case ByteCode.ILOAD_2: return "iload_2"; case ByteCode.ILOAD_3: return "iload_3"; case ByteCode.LLOAD_0: return "lload_0"; case ByteCode.LLOAD_1: return "lload_1"; case ByteCode.LLOAD_2: return "lload_2"; case ByteCode.LLOAD_3: return "lload_3"; case ByteCode.FLOAD_0: return "fload_0"; case ByteCode.FLOAD_1: return "fload_1"; case ByteCode.FLOAD_2: return "fload_2"; case ByteCode.FLOAD_3: return "fload_3"; case ByteCode.DLOAD_0: return "dload_0"; case ByteCode.DLOAD_1: return "dload_1"; case ByteCode.DLOAD_2: return "dload_2"; case ByteCode.DLOAD_3: return "dload_3"; case ByteCode.ALOAD_0: return "aload_0"; case ByteCode.ALOAD_1: return "aload_1"; case ByteCode.ALOAD_2: return "aload_2"; case ByteCode.ALOAD_3: return "aload_3"; case ByteCode.IALOAD: return "iaload"; case ByteCode.LALOAD: return "laload"; case ByteCode.FALOAD: return "faload"; case ByteCode.DALOAD: return "daload"; case ByteCode.AALOAD: return "aaload"; case ByteCode.BALOAD: return "baload"; case ByteCode.CALOAD: return "caload"; case ByteCode.SALOAD: return "saload"; case ByteCode.ISTORE: return "istore"; case ByteCode.LSTORE: return "lstore"; case ByteCode.FSTORE: return "fstore"; case ByteCode.DSTORE: return "dstore"; case ByteCode.ASTORE: return "astore"; case ByteCode.ISTORE_0: return "istore_0"; case ByteCode.ISTORE_1: return "istore_1"; case ByteCode.ISTORE_2: return "istore_2"; case ByteCode.ISTORE_3: return "istore_3"; case ByteCode.LSTORE_0: return "lstore_0"; case ByteCode.LSTORE_1: return "lstore_1"; case ByteCode.LSTORE_2: return "lstore_2"; case ByteCode.LSTORE_3: return "lstore_3"; case ByteCode.FSTORE_0: return "fstore_0"; case ByteCode.FSTORE_1: return "fstore_1"; case ByteCode.FSTORE_2: return "fstore_2"; case ByteCode.FSTORE_3: return "fstore_3"; case ByteCode.DSTORE_0: return "dstore_0"; case ByteCode.DSTORE_1: return "dstore_1"; case ByteCode.DSTORE_2: return "dstore_2"; case ByteCode.DSTORE_3: return "dstore_3"; case ByteCode.ASTORE_0: return "astore_0"; case ByteCode.ASTORE_1: return "astore_1"; case ByteCode.ASTORE_2: return "astore_2"; case ByteCode.ASTORE_3: return "astore_3"; case ByteCode.IASTORE: return "iastore"; case ByteCode.LASTORE: return "lastore"; case ByteCode.FASTORE: return "fastore"; case ByteCode.DASTORE: return "dastore"; case ByteCode.AASTORE: return "aastore"; case ByteCode.BASTORE: return "bastore"; case ByteCode.CASTORE: return "castore"; case ByteCode.SASTORE: return "sastore"; case ByteCode.POP: return "pop"; case ByteCode.POP2: return "pop2"; case ByteCode.DUP: return "dup"; case ByteCode.DUP_X1: return "dup_x1"; case ByteCode.DUP_X2: return "dup_x2"; case ByteCode.DUP2: return "dup2"; case ByteCode.DUP2_X1: return "dup2_x1"; case ByteCode.DUP2_X2: return "dup2_x2"; case ByteCode.SWAP: return "swap"; case ByteCode.IADD: return "iadd"; case ByteCode.LADD: return "ladd"; case ByteCode.FADD: return "fadd"; case ByteCode.DADD: return "dadd"; case ByteCode.ISUB: return "isub"; case ByteCode.LSUB: return "lsub"; case ByteCode.FSUB: return "fsub"; case ByteCode.DSUB: return "dsub"; case ByteCode.IMUL: return "imul"; case ByteCode.LMUL: return "lmul"; case ByteCode.FMUL: return "fmul"; case ByteCode.DMUL: return "dmul"; case ByteCode.IDIV: return "idiv"; case ByteCode.LDIV: return "ldiv"; case ByteCode.FDIV: return "fdiv"; case ByteCode.DDIV: return "ddiv"; case ByteCode.IREM: return "irem"; case ByteCode.LREM: return "lrem"; case ByteCode.FREM: return "frem"; case ByteCode.DREM: return "drem"; case ByteCode.INEG: return "ineg"; case ByteCode.LNEG: return "lneg"; case ByteCode.FNEG: return "fneg"; case ByteCode.DNEG: return "dneg"; case ByteCode.ISHL: return "ishl"; case ByteCode.LSHL: return "lshl"; case ByteCode.ISHR: return "ishr"; case ByteCode.LSHR: return "lshr"; case ByteCode.IUSHR: return "iushr"; case ByteCode.LUSHR: return "lushr"; case ByteCode.IAND: return "iand"; case ByteCode.LAND: return "land"; case ByteCode.IOR: return "ior"; case ByteCode.LOR: return "lor"; case ByteCode.IXOR: return "ixor"; case ByteCode.LXOR: return "lxor"; case ByteCode.IINC: return "iinc"; case ByteCode.I2L: return "i2l"; case ByteCode.I2F: return "i2f"; case ByteCode.I2D: return "i2d"; case ByteCode.L2I: return "l2i"; case ByteCode.L2F: return "l2f"; case ByteCode.L2D: return "l2d"; case ByteCode.F2I: return "f2i"; case ByteCode.F2L: return "f2l"; case ByteCode.F2D: return "f2d"; case ByteCode.D2I: return "d2i"; case ByteCode.D2L: return "d2l"; case ByteCode.D2F: return "d2f"; case ByteCode.I2B: return "i2b"; case ByteCode.I2C: return "i2c"; case ByteCode.I2S: return "i2s"; case ByteCode.LCMP: return "lcmp"; case ByteCode.FCMPL: return "fcmpl"; case ByteCode.FCMPG: return "fcmpg"; case ByteCode.DCMPL: return "dcmpl"; case ByteCode.DCMPG: return "dcmpg"; case ByteCode.IFEQ: return "ifeq"; case ByteCode.IFNE: return "ifne"; case ByteCode.IFLT: return "iflt"; case ByteCode.IFGE: return "ifge"; case ByteCode.IFGT: return "ifgt"; case ByteCode.IFLE: return "ifle"; case ByteCode.IF_ICMPEQ: return "if_icmpeq"; case ByteCode.IF_ICMPNE: return "if_icmpne"; case ByteCode.IF_ICMPLT: return "if_icmplt"; case ByteCode.IF_ICMPGE: return "if_icmpge"; case ByteCode.IF_ICMPGT: return "if_icmpgt"; case ByteCode.IF_ICMPLE: return "if_icmple"; case ByteCode.IF_ACMPEQ: return "if_acmpeq"; case ByteCode.IF_ACMPNE: return "if_acmpne"; case ByteCode.GOTO: return "goto"; case ByteCode.JSR: return "jsr"; case ByteCode.RET: return "ret"; case ByteCode.TABLESWITCH: return "tableswitch"; case ByteCode.LOOKUPSWITCH: return "lookupswitch"; case ByteCode.IRETURN: return "ireturn"; case ByteCode.LRETURN: return "lreturn"; case ByteCode.FRETURN: return "freturn"; case ByteCode.DRETURN: return "dreturn"; case ByteCode.ARETURN: return "areturn"; case ByteCode.RETURN: return "return"; case ByteCode.GETSTATIC: return "getstatic"; case ByteCode.PUTSTATIC: return "putstatic"; case ByteCode.GETFIELD: return "getfield"; case ByteCode.PUTFIELD: return "putfield"; case ByteCode.INVOKEVIRTUAL: return "invokevirtual"; case ByteCode.INVOKESPECIAL: return "invokespecial"; case ByteCode.INVOKESTATIC: return "invokestatic"; case ByteCode.INVOKEINTERFACE: return "invokeinterface"; case ByteCode.NEW: return "new"; case ByteCode.NEWARRAY: return "newarray"; case ByteCode.ANEWARRAY: return "anewarray"; case ByteCode.ARRAYLENGTH: return "arraylength"; case ByteCode.ATHROW: return "athrow"; case ByteCode.CHECKCAST: return "checkcast"; case ByteCode.INSTANCEOF: return "instanceof"; case ByteCode.MONITORENTER: return "monitorenter"; case ByteCode.MONITOREXIT: return "monitorexit"; case ByteCode.WIDE: return "wide"; case ByteCode.MULTIANEWARRAY: return "multianewarray"; case ByteCode.IFNULL: return "ifnull"; case ByteCode.IFNONNULL: return "ifnonnull"; case ByteCode.GOTO_W: return "goto_w"; case ByteCode.JSR_W: return "jsr_w"; case ByteCode.BREAKPOINT: return "breakpoint"; case ByteCode.IMPDEP1: return "impdep1"; case ByteCode.IMPDEP2: return "impdep2"; } } return ""; } final char[] getCharBuffer(int minimalSize) { if (minimalSize > tmpCharBuffer.length) { int newSize = tmpCharBuffer.length * 2; if (minimalSize > newSize) { newSize = minimalSize; } tmpCharBuffer = new char[newSize]; } return tmpCharBuffer; } private static final int LineNumberTableSize = 16; private static final int ExceptionTableSize = 4; private final static long FileHeaderConstant = 0xCAFEBABE0003002DL; // Set DEBUG flags to true to get better checking and progress info. private static final boolean DEBUGSTACK = false; private static final boolean DEBUGLABELS = false; private static final boolean DEBUGCODE = false; private String generatedClassName; private ExceptionTableEntry itsExceptionTable[]; private int itsExceptionTableTop; private int itsLineNumberTable[]; // pack start_pc & line_number together private int itsLineNumberTableTop; private byte[] itsCodeBuffer = new byte[256]; private int itsCodeBufferTop; private ConstantPool itsConstantPool; private ClassFileMethod itsCurrentMethod; private short itsStackTop; private short itsMaxStack; private short itsMaxLocals; private ObjArray itsMethods = new ObjArray(); private ObjArray itsFields = new ObjArray(); private ObjArray itsInterfaces = new ObjArray(); private short itsFlags; private short itsThisClassIndex; private short itsSuperClassIndex; private short itsSourceFileNameIndex; private static final int MIN_LABEL_TABLE_SIZE = 32; private int[] itsLabelTable; private int itsLabelTableTop; // itsFixupTable[i] = (label_index << 32) | fixup_site private static final int MIN_FIXUP_TABLE_SIZE = 40; private long[] itsFixupTable; private int itsFixupTableTop; private ObjArray itsVarDescriptors; private char[] tmpCharBuffer = new char[64]; } final class ExceptionTableEntry { ExceptionTableEntry(int startLabel, int endLabel, int handlerLabel, short catchType) { itsStartLabel = startLabel; itsEndLabel = endLabel; itsHandlerLabel = handlerLabel; itsCatchType = catchType; } int itsStartLabel; int itsEndLabel; int itsHandlerLabel; short itsCatchType; } final class ClassFileField { ClassFileField(short nameIndex, short typeIndex, short flags) { itsNameIndex = nameIndex; itsTypeIndex = typeIndex; itsFlags = flags; itsHasAttributes = false; } void setAttributes(short attr1, short attr2, short attr3, int index) { itsHasAttributes = true; itsAttr1 = attr1; itsAttr2 = attr2; itsAttr3 = attr3; itsIndex = index; } int write(byte[] data, int offset) { offset = ClassFileWriter.putInt16(itsFlags, data, offset); offset = ClassFileWriter.putInt16(itsNameIndex, data, offset); offset = ClassFileWriter.putInt16(itsTypeIndex, data, offset); if (!itsHasAttributes) { // write 0 attributes offset = ClassFileWriter.putInt16(0, data, offset); } else { offset = ClassFileWriter.putInt16(1, data, offset); offset = ClassFileWriter.putInt16(itsAttr1, data, offset); offset = ClassFileWriter.putInt16(itsAttr2, data, offset); offset = ClassFileWriter.putInt16(itsAttr3, data, offset); offset = ClassFileWriter.putInt16(itsIndex, data, offset); } return offset; } int getWriteSize() { int size = 2 * 3; if (!itsHasAttributes) { size += 2; } else { size += 2 + 2 * 4; } return size; } private short itsNameIndex; private short itsTypeIndex; private short itsFlags; private boolean itsHasAttributes; private short itsAttr1, itsAttr2, itsAttr3; private int itsIndex; } final class ClassFileMethod { ClassFileMethod(short nameIndex, short typeIndex, short flags) { itsNameIndex = nameIndex; itsTypeIndex = typeIndex; itsFlags = flags; } void setCodeAttribute(byte codeAttribute[]) { itsCodeAttribute = codeAttribute; } int write(byte[] data, int offset) { offset = ClassFileWriter.putInt16(itsFlags, data, offset); offset = ClassFileWriter.putInt16(itsNameIndex, data, offset); offset = ClassFileWriter.putInt16(itsTypeIndex, data, offset); // Code attribute only offset = ClassFileWriter.putInt16(1, data, offset); System.arraycopy(itsCodeAttribute, 0, data, offset, itsCodeAttribute.length); offset += itsCodeAttribute.length; return offset; } int getWriteSize() { return 2 * 4 + itsCodeAttribute.length; } private short itsNameIndex; private short itsTypeIndex; private short itsFlags; private byte[] itsCodeAttribute; } final class ConstantPool { ConstantPool(ClassFileWriter cfw) { this.cfw = cfw; itsTopIndex = 1; // the zero'th entry is reserved itsPool = new byte[ConstantPoolSize]; itsTop = 0; } private static final int ConstantPoolSize = 256; private static final byte CONSTANT_Class = 7, CONSTANT_Fieldref = 9, CONSTANT_Methodref = 10, CONSTANT_InterfaceMethodref = 11, CONSTANT_String = 8, CONSTANT_Integer = 3, CONSTANT_Float = 4, CONSTANT_Long = 5, CONSTANT_Double = 6, CONSTANT_NameAndType = 12, CONSTANT_Utf8 = 1; int write(byte[] data, int offset) { offset = ClassFileWriter.putInt16((short)itsTopIndex, data, offset); System.arraycopy(itsPool, 0, data, offset, itsTop); offset += itsTop; return offset; } int getWriteSize() { return 2 + itsTop; } int addConstant(int k) { ensure(5); itsPool[itsTop++] = CONSTANT_Integer; itsTop = ClassFileWriter.putInt32(k, itsPool, itsTop); return (short)(itsTopIndex++); } int addConstant(long k) { ensure(9); itsPool[itsTop++] = CONSTANT_Long; itsTop = ClassFileWriter.putInt64(k, itsPool, itsTop); int index = itsTopIndex; itsTopIndex += 2; return index; } int addConstant(float k) { ensure(5); itsPool[itsTop++] = CONSTANT_Float; int bits = Float.floatToIntBits(k); itsTop = ClassFileWriter.putInt32(bits, itsPool, itsTop); return itsTopIndex++; } int addConstant(double k) { ensure(9); itsPool[itsTop++] = CONSTANT_Double; long bits = Double.doubleToLongBits(k); itsTop = ClassFileWriter.putInt64(bits, itsPool, itsTop); int index = itsTopIndex; itsTopIndex += 2; return index; } int addConstant(String k) { int utf8Index = 0xFFFF & addUtf8(k); int theIndex = itsStringConstHash.getInt(utf8Index, -1); if (theIndex == -1) { theIndex = itsTopIndex++; ensure(3); itsPool[itsTop++] = CONSTANT_String; itsTop = ClassFileWriter.putInt16(utf8Index, itsPool, itsTop); itsStringConstHash.put(utf8Index, theIndex); } return theIndex; } boolean isUnderUtfEncodingLimit(String s) { int strLen = s.length(); if (strLen * 3 <= MAX_UTF_ENCODING_SIZE) { return true; } else if (strLen > MAX_UTF_ENCODING_SIZE) { return false; } return strLen == getUtfEncodingLimit(s, 0, strLen); } /** * Get maximum i such that start <= i <= end and * s.substring(start, i) fits JVM UTF string encoding limit. */ int getUtfEncodingLimit(String s, int start, int end) { if ((end - start) * 3 <= MAX_UTF_ENCODING_SIZE) { return end; } int limit = MAX_UTF_ENCODING_SIZE; for (int i = start; i != end; i++) { int c = s.charAt(i); if (0 != c && c <= 0x7F) { --limit; } else if (c < 0x7FF) { limit -= 2; } else { limit -= 3; } if (limit < 0) { return i; } } return end; } short addUtf8(String k) { int theIndex = itsUtf8Hash.get(k, -1); if (theIndex == -1) { int strLen = k.length(); boolean tooBigString; if (strLen > MAX_UTF_ENCODING_SIZE) { tooBigString = true; } else { tooBigString = false; // Ask for worst case scenario buffer when each char takes 3 // bytes ensure(1 + 2 + strLen * 3); int top = itsTop; itsPool[top++] = CONSTANT_Utf8; top += 2; // skip length char[] chars = cfw.getCharBuffer(strLen); k.getChars(0, strLen, chars, 0); for (int i = 0; i != strLen; i++) { int c = chars[i]; if (c != 0 && c <= 0x7F) { itsPool[top++] = (byte)c; } else if (c > 0x7FF) { itsPool[top++] = (byte)(0xE0 | (c >> 12)); itsPool[top++] = (byte)(0x80 | ((c >> 6) & 0x3F)); itsPool[top++] = (byte)(0x80 | (c & 0x3F)); } else { itsPool[top++] = (byte)(0xC0 | (c >> 6)); itsPool[top++] = (byte)(0x80 | (c & 0x3F)); } } int utfLen = top - (itsTop + 1 + 2); if (utfLen > MAX_UTF_ENCODING_SIZE) { tooBigString = true; } else { // Write back length itsPool[itsTop + 1] = (byte)(utfLen >>> 8); itsPool[itsTop + 2] = (byte)utfLen; itsTop = top; theIndex = itsTopIndex++; itsUtf8Hash.put(k, theIndex); } } if (tooBigString) { throw new IllegalArgumentException("Too big string"); } } return (short)theIndex; } private short addNameAndType(String name, String type) { short nameIndex = addUtf8(name); short typeIndex = addUtf8(type); ensure(5); itsPool[itsTop++] = CONSTANT_NameAndType; itsTop = ClassFileWriter.putInt16(nameIndex, itsPool, itsTop); itsTop = ClassFileWriter.putInt16(typeIndex, itsPool, itsTop); return (short)(itsTopIndex++); } short addClass(String className) { int theIndex = itsClassHash.get(className, -1); if (theIndex == -1) { String slashed = className; if (className.indexOf('.') > 0) { slashed = ClassFileWriter.getSlashedForm(className); theIndex = itsClassHash.get(slashed, -1); if (theIndex != -1) { itsClassHash.put(className, theIndex); } } if (theIndex == -1) { int utf8Index = addUtf8(slashed); ensure(3); itsPool[itsTop++] = CONSTANT_Class; itsTop = ClassFileWriter.putInt16(utf8Index, itsPool, itsTop); theIndex = itsTopIndex++; itsClassHash.put(slashed, theIndex); if (className != slashed) { itsClassHash.put(className, theIndex); } } } return (short)theIndex; } short addFieldRef(String className, String fieldName, String fieldType) { FieldOrMethodRef ref = new FieldOrMethodRef(className, fieldName, fieldType); int theIndex = itsFieldRefHash.get(ref, -1); if (theIndex == -1) { short ntIndex = addNameAndType(fieldName, fieldType); short classIndex = addClass(className); ensure(5); itsPool[itsTop++] = CONSTANT_Fieldref; itsTop = ClassFileWriter.putInt16(classIndex, itsPool, itsTop); itsTop = ClassFileWriter.putInt16(ntIndex, itsPool, itsTop); theIndex = itsTopIndex++; itsFieldRefHash.put(ref, theIndex); } return (short)theIndex; } short addMethodRef(String className, String methodName, String methodType) { FieldOrMethodRef ref = new FieldOrMethodRef(className, methodName, methodType); int theIndex = itsMethodRefHash.get(ref, -1); if (theIndex == -1) { short ntIndex = addNameAndType(methodName, methodType); short classIndex = addClass(className); ensure(5); itsPool[itsTop++] = CONSTANT_Methodref; itsTop = ClassFileWriter.putInt16(classIndex, itsPool, itsTop); itsTop = ClassFileWriter.putInt16(ntIndex, itsPool, itsTop); theIndex = itsTopIndex++; itsMethodRefHash.put(ref, theIndex); } return (short)theIndex; } short addInterfaceMethodRef(String className, String methodName, String methodType) { short ntIndex = addNameAndType(methodName, methodType); short classIndex = addClass(className); ensure(5); itsPool[itsTop++] = CONSTANT_InterfaceMethodref; itsTop = ClassFileWriter.putInt16(classIndex, itsPool, itsTop); itsTop = ClassFileWriter.putInt16(ntIndex, itsPool, itsTop); return (short)(itsTopIndex++); } void ensure(int howMuch) { if (itsTop + howMuch > itsPool.length) { int newCapacity = itsPool.length * 2; if (itsTop + howMuch > newCapacity) { newCapacity = itsTop + howMuch; } byte[] tmp = new byte[newCapacity]; System.arraycopy(itsPool, 0, tmp, 0, itsTop); itsPool = tmp; } } private ClassFileWriter cfw; private static final int MAX_UTF_ENCODING_SIZE = 65535; private UintMap itsStringConstHash = new UintMap(); private ObjToIntMap itsUtf8Hash = new ObjToIntMap(); private ObjToIntMap itsFieldRefHash = new ObjToIntMap(); private ObjToIntMap itsMethodRefHash = new ObjToIntMap(); private ObjToIntMap itsClassHash = new ObjToIntMap(); private int itsTop; private int itsTopIndex; private byte itsPool[]; } final class FieldOrMethodRef { FieldOrMethodRef(String className, String name, String type) { this.className = className; this.name = name; this.type = type; } @Override public boolean equals(Object obj) { if (!(obj instanceof FieldOrMethodRef)) { return false; } FieldOrMethodRef x = (FieldOrMethodRef)obj; return className.equals(x.className) && name.equals(x.name) && type.equals(x.type); } @Override public int hashCode() { if (hashCode == -1) { int h1 = className.hashCode(); int h2 = name.hashCode(); int h3 = type.hashCode(); hashCode = h1 ^ h2 ^ h3; } return hashCode; } private String className; private String name; private String type; private int hashCode = -1; } jenkins-htmlunit-core-js-2.6-hudson-1/rhino/build-date0000644000175000017500000000004711314263504024646 0ustar jamespagejamespage00000000000000This version was built on @datestamp@. jenkins-htmlunit-core-js-2.6-hudson-1/rhinoDiff.txt0000644000175000017500000000670111314263504024246 0ustar jamespagejamespage00000000000000HtmlUnit's core js is mainly a repakaging of Rhino classes from org.mozilla to net.sourceforge.htmlunit.corejs. The diff below contains the other changes made to the original Rhino version. Index: org/mozilla/javascript/Context.java =================================================================== RCS file: /cvsroot/mozilla/js/rhino/src/org/mozilla/javascript/Context.java,v retrieving revision 1.279 diff -u -r1.279 Context.java --- org/mozilla/javascript/Context.java 15 May 2009 12:09:51 -0000 1.279 +++ org/mozilla/javascript/Context.java 6 Jul 2009 08:42:59 -0000 @@ -315,6 +315,13 @@ */ public static final int FEATURE_ENHANCED_JAVA_ACCESS = 13; + /** + * Special to HtmlUnit's Rhino fork. + * Enable assignment to properties with only a getter defined. + * This was Rhino's standard behaviour until 1.7R2. + * By default {@link #hasFeature(int)} returns false. + */ + public static final int FEATURE_HTMLUNIT_WRITE_READONLY_PROPERTIES = 14; public static final String languageVersionProperty = "language version"; public static final String errorReporterProperty = "error reporter"; @@ -1358,7 +1365,7 @@ securityDomain); } - final Script compileString(String source, + protected Script compileString(String source, Evaluator compiler, ErrorReporter compilationErrorReporter, String sourceName, int lineno, Index: org/mozilla/javascript/ContextFactory.java =================================================================== RCS file: /cvsroot/mozilla/js/rhino/src/org/mozilla/javascript/ContextFactory.java,v retrieving revision 1.34 diff -u -r1.34 ContextFactory.java --- org/mozilla/javascript/ContextFactory.java 15 May 2009 12:09:55 -0000 1.34 +++ org/mozilla/javascript/ContextFactory.java 6 Jul 2009 08:42:59 -0000 @@ -310,6 +310,7 @@ return false; case Context.FEATURE_ENHANCED_JAVA_ACCESS: + case Context.FEATURE_HTMLUNIT_WRITE_READONLY_PROPERTIES: return false; } // It is a bug to call the method with unknown featureIndex Index: org/mozilla/javascript/ScriptableObject.java =================================================================== RCS file: /cvsroot/mozilla/js/rhino/src/org/mozilla/javascript/ScriptableObject.java,v retrieving revision 1.151 diff -u -r1.151 ScriptableObject.java --- org/mozilla/javascript/ScriptableObject.java 22 Jun 2009 01:08:20 -0000 1.151 +++ org/mozilla/javascript/ScriptableObject.java 6 Jul 2009 08:43:01 -0000 @@ -2320,9 +2320,16 @@ Object setterObj = ((GetterSlot)slot).setter; if (setterObj == null) { if (((GetterSlot)slot).getter != null) { + if (Context.getContext().hasFeature(Context.FEATURE_HTMLUNIT_WRITE_READONLY_PROPERTIES)) { + // Odd case: Assignment to a property with only a getter + // defined. The assignment cancels out the getter. + ((GetterSlot)slot).getter = null; + } + else { // Based on TC39 ES3.1 Draft of 9-Feb-2009, 8.12.4, step 2, // we should throw a TypeError in this case. throw ScriptRuntime.typeError1("msg.set.prop.no.setter", name); + } } } else { Context cx = Context.getContext();